• Stars
    star
    116
  • Rank 303,894 (Top 6 %)
  • Language
    TypeScript
  • License
    Apache License 2.0
  • Created over 2 years ago
  • Updated 3 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Convert your CosmWasm smart contracts into dev-friendly TypeScript classes so you can focus on shipping code.

@cosmwasm/ts-codegen

Generate TypeScript SDKs for your CosmWasm smart contracts

npm install -g @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!

Table of contents

Quickstart

Clone your project and cd into your contracts folder

git clone https://github.com/public-awesome/launchpad.git
cd launchpad/contracts/sg721-base/

Run cosmwasm-ts-codegen to generate your code.

cosmwasm-ts-codegen generate \
          --plugin client \
          --schema ./schema \
          --out ./ts \
          --name SG721 \
          --no-bundle

The output will be in the folder specified by --out, enjoy!

Usage

You can get started quickly using our cli by globally installing via npm:

npm install -g @cosmwasm/ts-codegen

Programmatic Usage

For production usage, we recommend setting up a build script that uses the main entry point:

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
    },
    useContractsHooks: {
      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.

see example output code

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

Client

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.

see example output code

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 via CLI

cosmwasm-ts-codegen generate \
    --plugin client
    --schema ./schema \
    --out ./ts \
    --name MyContractName

React Query

Generate react-query v3 or react-query v4 bindings for your contracts with the react-query command.

see example output code

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

React Query via CLI

Here is an example without optional client, using v3 for react-query, without mutations:

cosmwasm-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:

cosmwasm-ts-codegen generate \
    --plugin react-query \
    --schema ./schema \
    --out ./ts \
    --name MyContractName \
    --optionalClient \
    --version v4 \
    --mutations

Recoil

Generate recoil bindings for your contracts with the recoil command.

see example output code

Recoil via CLI

cosmwasm-ts-codegen generate \
    --plugin recoil \
    --schema ./schema \
    --out ./ts \
    --name MyContractName

Recoil Options

option description
recoil.enabled enable the recoil plugin

Message Composer

Generate pure message objects with the proper utf8 encoding and typeUrl configured that you can broadcast yourself via cosmjs with the message-composer command.

see example output code

Message Composer via CLI

cosmwasm-ts-codegen generate \
    --plugin message-composer \
    --schema ./schema \
    --out ./ts \
    --name MyContractName

Message Composer Options

option description
messageComposer.enabled enable the messageComposer plugin

Message Builder

Generate raw message jsons for use in your application with the message-builder command.

see example output code

Message Builder via CLI

cosmwasm-ts-codegen generate \
    --plugin message-builder \
    --schema ./schema \
    --out ./ts \
    --name MyContractName

Message Builder Options

option description
messageBuilder.enabled enable the messageBuilder plugin

Use Contracts Hooks

option description
useContractsHooks.enabled enable the useContracts plugin

Use Contracts Provider Usage

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 (
    <ContractsProvider
      contractsConfig={{
        address,
        getCosmWasmClient,
        getSigningCosmWasmClient,
      }}
    >
        <SomeCoolComponent />
    </ContractsProvider>
  )
};

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:

 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:

const { marketplace } = useContracts();
const marketplaceClient = marketplace.signingClient(marketplaceContract);
await marketplaceClient.updateAskPrice({
  collection: token.collectionAddr,
  price: {
    amount,
    denom,
  },
  tokenId,
});

Bundles

The bundler will make a nice package of all your contracts. For example:

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):

  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:

  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;
  }

CLI Usage and Examples

Interactive prompt

The CLI is interactive, and if you don't specify an option, it will interactively prompt you.

cosmwasm-ts-codegen generate
? [plugin] which plugins? (Press <space> to select, <a> to toggle all, <i> 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:

cosmwasm-ts-codegen generate \
    --plugin client
    --schema ./schema \
    --out ./ts \
    --name MyContractName

You can specify multiple --plugin options using the generate command:

cosmwasm-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-<name> to set the value to false. Here is an example without optional client, using v3 for react-query, without mutations:

cosmwasm-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:

cosmwasm-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;

cosmwasm-ts-codegen generate \
          --typesOnly \
          --schema ./schema \
          --out ./ts \
          --name SG721

Advanced Usage

for lower-level access, you can import the various plugins directly:

import {
  generateTypes,
  generateClient,
  generateReactQuery,
  generateRecoil,
  generateMessageComposer
} from '@cosmwasm/ts-codegen';

Example Output

  • cosmwasm-ts-codegen generate --typesOnly

https://gist.github.com/pyramation/107d4e8e30dc5eb3ffc07bc3000f4dd0

  • cosmwasm-ts-codegen generate --plugin client

https://gist.github.com/pyramation/30508678b7563e286f06ccc5ac384817

  • cosmwasm-ts-codegen generate --plugin react-query

https://gist.github.com/pyramation/70aef28fd3af0ee164f7711704d3dfc0

  • cosmwasm-ts-codegen generate --plugin recoil

https://gist.github.com/pyramation/a9520ccf131177b1841e02a97d7d3731

  • cosmwasm-ts-codegen generate --plugin message-composer

https://gist.github.com/pyramation/43320e8b952751a0bd5a77dbc5b601f4

  • cosmwasm-ts-codegen generate --plugin message-builder

https://gist.github.com/adairrr/b394e62beb9856b0351883f776650f26

JSON Schema

We generate code from the JSON Schema exported from CosmWasm smart contracts.

JSON Schema Generation

Currently you have to have the JSON Schema output. Here is an example to start.

First, get the Rust contracts and run cargo build:

git clone [email protected]:public-awesome/stargaze-contracts.git
cd stargaze-contracts
cargo build

now build the schema with cargo schema

cd contracts/sg721/
cargo schema

Exporting Schemas

cosmwasm v1.1 Example

Using the new write_api method, you can export schemas:

use cosmwasm_schema::write_api;

use cw4_group::msg::{ExecuteMsg, InstantiateMsg, QueryMsg};

fn main() {
    write_api! {
        instantiate: InstantiateMsg,
        execute: ExecuteMsg,
        query: QueryMsg,
    }
}

cosmwasm_std Example

Here is a legacy example:

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<Empty>),
      &out_dir,
      "CosmosMsg_for_Empty",
);

Developing

Initial setup

yarn
yarn bootstrap

Building

yarn build

Tests

Then cd into a package and run the tests

cd ./packages/wasm-ast-types
yarn test:watch

Working with ASTs

See the docs in the wasm-ast-types package.

Related

Checkout these related projects:

  • @cosmology/telescope Your Frontend Companion for Building with TypeScript with Cosmos SDK Modules.
  • @cosmwasm/ts-codegen Convert your CosmWasm smart contracts into dev-friendly TypeScript classes.
  • chain-registry Everything from token symbols, logos, and IBC denominations for all assets you want to support in your application.
  • cosmos-kit Experience the convenience of connecting with a variety of web3 wallets through a single, streamlined interface.
  • create-cosmos-app Set up a modern Cosmos app by running one command.
  • interchain-ui The Interchain Design System, empowering developers with a flexible, easy-to-use UI kit.
  • starship Unified Testing and Development for the Interchain.

Credits

πŸ›  Built by Cosmology β€”Β if you like our tools, please consider delegating to our validator βš›οΈ

Disclaimer

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.

More Repositories

1

cosmwasm

Framework for building smart contracts in Wasm for the Cosmos SDK
Rust
1,060
star
2

cw-plus

Production Quality contracts under open source licenses
Rust
506
star
3

wasmd

Basic cosmos-sdk app with web assembly smart contracts
Go
367
star
4

cw-template

Quickstart template to get started writing your own cosmwasm contracts
Rust
283
star
5

awesome-cosmwasm

😎 Curated list of tools, contracts, and projects working with CosmWasm
242
star
6

wasmvm

Go bindings to the CosmWasm VM
Go
173
star
7

optimizer

Dockerfile and script to deterministically produce the smallest possible Wasm for your Rust contract
Rust
123
star
8

sylvia

CosmWasm smart contract framework
Rust
93
star
9

mesh-security-hackathon

Implementation of Sunny's Mesh Security talk (Hackathon / Prototype status)
Rust
88
star
10

cw-tokens

Examples of cw20 usage, extracted from cw-plus, maintained by the community
Rust
85
star
11

dApps

A collection of sample dApps for CosmWasm contracts, using CosmJS frontend SDK
TypeScript
55
star
12

docs-deprecated

Updated documentation repo
JavaScript
52
star
13

CosmWasmJS

Source of the cosmwasm npm package
TypeScript
50
star
14

cw-multi-test

CosmWasm multi-contract testing framework
Rust
46
star
15

cw-storage-plus

Storage abstractions for CosmWasm smart contracts
Rust
35
star
16

testnets

Information on all public CosmWasm testnets
TypeScript
34
star
17

book

CosmWasm book
34
star
18

cosmwasm-go

Enabling CosmWasm smart contracts in Go using TinyGo
Go
29
star
19

token-factory

Pulling out Osmosis token factory module and the custom CosmWasm bindings into it's own repo for easier reuse
Go
24
star
20

resources

23
star
21

tinyjson

Fast JSON serializer for golang.
Go
22
star
22

code-explorer

A code explorer for CosmWasm
TypeScript
21
star
23

cw-minus

Contract helpers originally used for cw-plus contracts/specs
Rust
16
star
24

cosmwasm-verify

Verify CosmWasm build results
Shell
15
star
25

advisories

To publicly communicate advisories about serious bugs in CosmWasm, wasmvm, and wasmd
Shell
14
star
26

drand-verify

A drand verification library in Rust. This can be used by other crates or be compiled to a Wasm blob (< 500 kilobytes) with JavaScript bindings.
Rust
12
star
27

cosmwasm-simulate

Simulation tool for cosmwasm smart contract
Rust
10
star
28

cw-academy-course

CosmWasm academy smart contracts course projects
Rust
7
star
29

mesh-security-ui

Basic UI to try out mesh security
TypeScript
6
star
30

docs

MDX
6
star
31

token-bindings

Minimal Rust bindings for token factory
Rust
5
star
32

CWIPs

CosmWasm Improvement Proposals
Shell
5
star
33

storey

Experimental storage abstractions for blockchain key-value stores
Rust
5
star
34

academy-deploy

TypeScript
4
star
35

cw-cron

Basic job scheduler service implementation for CosmWasm
3
star
36

sylvia-book

3
star
37

name-app

Simple react app on top of cosmwasm, showing use of name server contract
TypeScript
3
star
38

terra-contracts

Custom bindings and sample contracts for Terra integration
Rust
2
star
39

cw-mcs-academy-course

Repository for multi contract systems academy course
Rust
2
star
40

docs-old

Documentation for cosmwasm
JavaScript
2
star
41

simple-option

Demo repo for hackatom video
Rust
2
star
42

cw-storage

CosmWasm library with useful helpers for Storage patterns
Rust
1
star
43

chat.cosmwasm.com

Redirect to our community chat
HTML
1
star
44

cw-tools

Rust
1
star
45

idl

The CosmWasm IDL docs
1
star
46

sylvia-template

Rust
1
star