尧图网络 高端网站定制 · 原创设计
免费咨询热线
400-888-6620
免费获取方案
CosmJS模块化开发:从基础包到自定义Stargate模块全攻略
CosmJS模块化开发从基础包到自定义Stargate模块全攻略【免费下载链接】cosmjsThe Swiss Army knife to power JavaScript based client solutions ranging from Web apps/explorers over browser extensions to server-side clients like faucets/scrapers.项目地址: https://gitcode.com/gh_mirrors/co/cosmjsCosmJS作为Cosmos生态系统中强大的JavaScript开发工具包提供了从Web应用、浏览器扩展到服务器端客户端如水龙头和刮板的全方位支持。本文将带您深入了解CosmJS的模块化架构从核心基础包到自定义Stargate模块的完整开发流程帮助您快速掌握这一瑞士军刀级工具的使用方法。一、CosmJS模块化架构解析CosmJS采用了精心设计的模块化架构通过多个npm包组成的monorepo形式提供功能。这种设计确保了代码质量并让用户可以精确选择所需功能。核心包概览CosmJS生态包含多个核心包每个包专注于特定功能cosmjs/stargate(packages/stargate): 用于Cosmos SDK 0.40Stargate的客户端库cosmjs/cosmwasm(packages/cosmwasm): 支持CosmWasm模块的Stargate链客户端cosmjs/crypto(packages/crypto): 区块链项目的加密功能包括哈希、签名、HD密钥派生等cosmjs/encoding(packages/encoding): 区块链项目的编码辅助工具cosmjs/math(packages/math): 安全整数和金融金额处理的小数运算模块化依赖关系CosmJS的模块化设计体现在清晰的依赖关系上。每个包都有明确的职责右侧包依赖于左侧包如果您需要查看包含应用运行时依赖的完整版本可以查看cosmjs-tree-full.png。二、开发环境搭建开始使用CosmJS进行模块化开发前需要准备以下开发环境系统要求Node.js 20现代浏览器Chromium/Firefox/Safari浏览器扩展开发环境如需要TypeScript支持安装依赖首先克隆CosmJS仓库git clone https://gitcode.com/gh_mirrors/co/cosmjs cd cosmjs然后安装项目依赖yarn install对于特定功能开发您可能需要安装以下核心包dependencies: { cosmjs/proto-signing: ^0.26.4, cosmjs/stargate: ^0.26.4, cosmjs/tendermint-rpc: ^0.26.4 }同时安装开发依赖yarn add --dev ts-proto您还需要安装protocProtocol Buffers编译器本文基于版本3.17。三、基础包使用指南1. 加密功能 (cosmjs/crypto)packages/crypto提供了区块链开发所需的各种加密功能哈希算法SHA-2, Keccak256, Ripemd160签名算法secp256k1, ed25519HD密钥派生BIP-39, SLIP-0010密钥存储的KDF和对称加密PBKDF2, Argon2, XChaCha20Poly1305基本使用示例import { sha256, secp256k1 } from cosmjs/crypto; // 哈希计算 const hash sha256(Buffer.from(hello world)); // 密钥对生成 const { privkey, pubkey } await secp256k1.generateKeyPair(); // 签名 const message Buffer.from(important message); const signature await secp256k1.sign(privkey, message);2. 编码功能 (cosmjs/encoding)packages/encoding提供了区块链开发中常用的编码和解码功能Base64编码/解码Bech32地址编码Hex编码/解码UTF8字符串处理使用示例import { bech32, base64, hex } from cosmjs/encoding; // Bech32地址编码 const address bech32.encode(cosmos, new Uint8Array([0x01, 0x02, 0x03])); // Base64编码 const encoded base64.encode(Buffer.from(hello)); // Hex编码 const hexString hex.encode(Buffer.from(hello));3. 数学功能 (cosmjs/math)packages/math提供了安全处理整数和金融金额的功能import { Decimal, Int53 } from cosmjs/math; // 安全整数处理 const safeNumber Int53.fromString(9007199254740991); // 小数运算金融金额 const amount Decimal.fromUserInput(123.456, 6); const doubled amount.multiply(Decimal.fromAtomics(2, 0));四、Stargate客户端开发packages/stargate是CosmJS的核心包提供了与Cosmos SDK 0.40Stargate兼容的客户端功能。1. 连接到区块链import { StargateClient } from cosmjs/stargate; async function connect() { const client await StargateClient.connect(https://rpc.cosmos.network); console.log(Connected to chain:, await client.getChainId()); console.log(Latest block height:, await client.getHeight()); } connect();2. 创建签名客户端import { DirectSecp256k1HdWallet, SigningStargateClient } from cosmjs/stargate; async function createSigningClient() { const mnemonic economy stock theory fatal elder harbor betray wasp final emotion task crumble siren bottom lizard educate guess current outdoor pair theory focus wife stone; const wallet await DirectSecp256k1HdWallet.fromMnemonic(mnemonic, { prefix: cosmos }); const client await SigningStargateClient.connectWithSigner( https://rpc.cosmos.network, wallet ); return client; }3. 发送交易async function sendTokens() { const client await createSigningClient(); const [firstAccount] await client.getAccounts(); const recipient cosmos1abcdefghijklmnopqrstuvwxyz; const amount [{ denom: uatom, amount: 100000 }]; const fee { amount: [{ denom: uatom, amount: 500 }], gas: 200000, }; const result await client.sendTokens(firstAccount.address, recipient, amount, fee); console.log(Transaction hash:, result.transactionHash); } sendTokens();五、自定义Stargate模块开发全流程CosmJS不仅支持标准Cosmos SDK模块还允许您为自定义模块开发客户端支持。以下是创建自定义Stargate模块客户端的完整流程。步骤1获取Protocol Buffer定义文件首先您需要获取自定义模块的.proto定义文件。通常有两种方式从外部源下载副本到项目中例如使用脚本下载使用Git子模块链接外部仓库CosmJS使用脚本下载定义文件的示例可参考此脚本。步骤2生成TypeScript编解码器使用ts-proto生成TypeScript编解码器protoc \ --plugin./node_modules/.bin/protoc-gen-ts_proto \ --ts_proto_out./path/to/output/directory \ --proto_path./path/to/definitions \ --ts_proto_optesModuleInteroptrue,forceLonglong,useOptionalstrue \ ./path/to/definitions/file.protoCosmJS的stargate包使用的生成脚本可参考此处。步骤3使用自定义消息类型创建包含自定义消息的签名客户端import { DirectSecp256k1HdWallet, Registry } from cosmjs/proto-signing; import { defaultRegistryTypes, SigningStargateClient } from cosmjs/stargate; import { MsgXxx } from ./path/to/generated/codec/my/custom/tx; // 创建包含自定义类型的注册表 const myRegistry new Registry(defaultRegistryTypes); myRegistry.register(/my.custom.MsgXxx, MsgXxx); async function createCustomClient() { const mnemonic your mnemonic here; const signer await DirectSecp256k1HdWallet.fromMnemonic(mnemonic, { prefix: myprefix }); const client await SigningStargateClient.connectWithSigner( my.endpoint.com, signer, { registry: myRegistry } ); return client; }发送自定义消息async function sendCustomMessage() { const client await createCustomClient(); const [firstAccount] await client.getAccounts(); const message { typeUrl: /my.custom.MsgXxx, value: MsgXxx.fromPartial({ foo: bar, creator: firstAccount.address, }), }; const fee { amount: [{ denom: udenom, amount: 120000 }], gas: 100000, }; const response await client.signAndBroadcast(firstAccount.address, [message], fee); console.log(Custom message sent. Transaction hash:, response.transactionHash); }步骤4创建自定义查询服务实例化查询客户端import { createProtobufRpcClient, QueryClient } from cosmjs/stargate; import { Tendermint34Client } from cosmjs/tendermint-rpc; import { QueryClientImpl } from ./path/to/generated/codec/my/custom/query; async function createCustomQueryClient() { const tendermintClient await Tendermint34Client.connect(my.endpoint.com); const queryClient new QueryClient(tendermintClient); const rpcClient createProtobufRpcClient(queryClient); return new QueryClientImpl(rpcClient); }扩展查询客户端// 定义扩展 function setupXxxExtension(base: QueryClient) { const rpcClient createProtobufRpcClient(base); const queryService new QueryClientImpl(rpcClient); return { mymodule: { customQuery: async (foo: string) queryService.MyCustomQuery({ foo }), anotherQuery: async () queryService.MyAnotherQuery({}), }, }; } // 使用扩展 async function useExtendedQueryClient() { const tendermintClient await Tendermint34Client.connect(my.endpoint.com); const queryClient QueryClient.withExtensions(tendermintClient, setupXxxExtension); const result await queryClient.mymodule.customQuery(bar); console.log(Custom query result:, result); }CosmJS如何为默认查询客户端设置bank扩展的示例可参考此处。六、Webpack配置使用Webpack 5时需要显式配置Node.js类型和模块module.exports { plugins: [ new webpack.ProvidePlugin({ Buffer: [buffer, Buffer], }), ], resolve: { fallback: { buffer: false, crypto: false, events: false, path: false, stream: false, string_decoder: false, }, }, };对于CosmJS 0.28版本stream配置有所不同resolve: { fallback: { // ...其他配置 stream: require.resolve(stream-browserify), }, }七、总结与进阶资源CosmJS的模块化设计为Cosmos生态系统的JavaScript开发提供了强大支持。通过本文介绍的基础包使用和自定义Stargate模块开发流程您可以构建从简单查询到复杂交易的全方位区块链应用。进阶学习资源完整API文档cosmos.github.io/cosmjsCosmJS示例guided tour测试用例signingstargateclient.spec.ts自定义模块文档CUSTOM_PROTOBUF_CODECS.md通过这些资源您可以进一步探索CosmJS的强大功能开发出更加复杂和高效的Cosmos生态应用。无论您是构建Web应用、浏览器扩展还是服务器端工具CosmJS的模块化设计都能满足您的需求让开发过程更加灵活和高效。【免费下载链接】cosmjsThe Swiss Army knife to power JavaScript based client solutions ranging from Web apps/explorers over browser extensions to server-side clients like faucets/scrapers.项目地址: https://gitcode.com/gh_mirrors/co/cosmjs创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考
RELATED

相关推荐

从零搭建AI考研知识体系:用LLM自动构建专业课思维导图+错题归因模型(含可运行Python脚本)

从零搭建AI考研知识体系:用LLM自动构建专业课思维导图+错题归因模型(含可运行Python脚本)

更多请点击: https://kaifayun.com 第一章:AI考研专业课备考的核心挑战与LLM赋能范式 AI考研专业课涵盖数据结构、算法设计、机器学习原理、计算机组成原理及数学基础(线性代数、概率论、最优化)等多个高耦合模块,考…

📅 2026/10/3 17:11:54
5个简单技巧:用SillyTavern打造有灵魂的AI角色对话体验

5个简单技巧:用SillyTavern打造有灵魂的AI角色对话体验

5个简单技巧:用SillyTavern打造有灵魂的AI角色对话体验 【免费下载链接】SillyTavern LLM Frontend for Power Users. 项目地址: https://gitcode.com/GitHub_Trending/si/SillyTavern 你是否曾幻想过与AI角色进行真正有情感的对话?厌倦了机械式的…

📅 2026/11/18 9:25:12
CLIP:连接视觉与语言的桥梁,开启零样本智能新时代

CLIP:连接视觉与语言的桥梁,开启零样本智能新时代

CLIP:连接视觉与语言的桥梁,开启零样本智能新时代 【免费下载链接】CLIP CLIP (Contrastive Language-Image Pretraining), Predict the most relevant text snippet given an image 项目地址: https://gitcode.com/GitHub_Trending/cl/CLIP 想象…

📅 2026/10/7 13:32:38
MORE NEWS

更多资讯

📰

哪里考特种工操作证复审延期怎么办理

南阳卧龙区公路工程从业者怎么报名特种工操作证?实操考试心里没底怕挂科别慌 实操考试心里没底怕挂科,特别是像南阳卧龙区公路工程这些需要持证上岗的行业,特种作业操作证不仅是门槛,更是你职业发展的关键。如果你正考虑怎么报名特种工操作证,这篇文章就…

📰

急需特种作业证才能上岗找工作,哪里考特种工操作证多少钱你知道吗

急需特种作业证才能上岗找工作,哪里考特种工操作证多少钱你知道吗 你是不是正在找工作,却被“必须持证上岗”拦住去路?很多从事建筑、制造、维修等行业的小伙伴,都面临着同一个难题: 没有特种作业操作证,连面试资格都没有 。现在问题来了:…

📰

电焊证电工证培训考证真实经历:急需特种作业证才能上岗找工作

电焊证电工证培训考证真实经历:急需特种作业证才能上岗找工作 刚入职工地那会儿,我连电焊证和电工证都没考,结果师傅直接说:“不考证,别想上手干活。”那时候真懵,以为手上会点活就OK了,没想到特种作业证是硬性门槛, 真实经历…

📰

四川如何办理电工证内部消息曝光 证书过期了不知道怎么复审延期

四川如何办理电工证内部消息曝光 证书过期了不知道怎么复审延期 证书过期了不知道怎么复审延期?这是很多电工朋友最怕遇到的糟心事。尤其是在四川,随着政策的不断收紧,电工证一旦过期,不仅影响日常工作,还可能带来严重的法律后果。如果你正为这个问题发…

📰

湖北阳新电工证怎么考不被坑?郑州报考避坑指南来了

湖北阳新电工证怎么考不被坑?郑州报考避坑指南来了 怕考不过白交培训费?现在考湖北阳新电工证的人越来越多,但培训机构五花八门,真假难辨。很多人一不小心就踩坑,交了钱却连报名都没搞明白,更别说考试通过了。别急,这篇文章从报名到考试再到复审,教你…

📰

青岛低压电工证的价格2026河南最新政策怎么影响报考?

青岛低压电工证的价格2026河南最新政策怎么影响报考? 你是不是也遇到过这样的情况:想考低压电工证,但不知道去哪报名,怕被中介骗钱?2026年河南最新政策对低压电工证的报考、价格、考试要求都有了新变化,这篇文章就告诉你怎么不被坑,怎么考得上…

TODAY

今日更新

THIS WEEK

本周精选

THIS MONTH

本月热门

读完文章,想聊聊您的网站?

告诉我们您的行业与需求,资深顾问一对一梳理方案与报价,全程免费。

📞 💬