Skip to content

Instantly share code, notes, and snippets.

@arvitaly
Forked from fadeev/script.js
Created July 18, 2023 00:10
Show Gist options
  • Save arvitaly/14719f5650be525ad6ad4a3ada634a2e to your computer and use it in GitHub Desktop.
Save arvitaly/14719f5650be525ad6ad4a3ada634a2e 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;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment