Skip to content

Instantly share code, notes, and snippets.

@fadeev
Created January 1, 2021 13:21
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save fadeev/a4981eff1cf3a805ef10e25313d5f2b7 to your computer and use it in GitHub Desktop.
Save fadeev/a4981eff1cf3a805ef10e25313d5f2b7 to your computer and use it in GitHub Desktop.
Example of using CosmJS with `protobufjs` to encode a custom proto message
// Every chain has at least two API endpoints: 26657 (the Tendermint one, roughly
// speaking, lower level, deals with bytes, exposes info about blocks, consensus,
// validators, etc.) and 1317 (the Cosmos one, higher level, your chain's API).
// Since every transaction broadcasted to a chain should be signed (and you don't
// want to do the signing manually), it makes sense to use a signing library.
// For JS/TS it's CosmJS.
// With CosmJS you create a wallet from a mnemonic, create a client from a wallet,
// and use client.signAndBroadcast method to, well, sign and broadcast transaction
// (an array of messages from an address). The client uses 26657 endpoint under the
// hood and needs to know how to encode your messages. For that a client has a registry.
// Let's consider an example.
// We use protobufjs to create a type with fields that mirrors what we have in our proto,
// pass the type to the registry and broadcast our message.
import { coins } from "@cosmjs/launchpad";
import { SigningStargateClient } from "@cosmjs/stargate";
import { Registry, DirectSecp256k1HdWallet } from "@cosmjs/proto-signing";
import { Type, Field } from "protobufjs";
const MsgCreatePost = new Type("MsgCreatePost")
.add(new Field("creator", 1, "string"))
.add(new Field("title", 2, "string"))
.add(new Field("body", 3, "string"));
const typeUrl = "/foo.foo.MsgCreatePost";
const registry = new Registry([[typeUrl, MsgCreatePost]]);
const api = "http://localhost:26657";
const mnemonic =
"slight recycle much magnet crumble spatial jar rotate drill soccer exhaust wrap scale horse catalog camera talent account rice business trial unit kitten noble";
const wallet = await DirectSecp256k1HdWallet.fromMnemonic(mnemonic);
const stargate = SigningStargateClient;
const client = await stargate.connectWithWallet(api, wallet, { registry });
const fromAddress = await wallet.address;
const msg = {
typeUrl,
value: {
title: "foo1",
body: "bar1",
creator: fromAddress,
},
};
const fee = {
amount: coins(0, "token"),
gas: "200000",
};
await client.signAndBroadcast(fromAddress, [msg], fee)
syntax = "proto3";
package foo.foo;
message MsgCreatePost {
string creator = 1;
string title = 2;
string body = 3;
}
@Chen120322
Copy link

How does Field define the Coin type

@riskers
Copy link

riskers commented Feb 17, 2023

@Chen120322 Have you define Coin type successed?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment