Перейти к содержимому

Cosmos sdk что это

  • автор:

Обзор проекта Cosmos (Atom)

Одна из главных проблем блокчейнов – проблема совместимости. Каждый блокчейн работает внутри своей сети. Но взаимодействие между блокчейнами, если и возможно, то пока лишь за счет специальных мостов. А это может быть небезопасно, долго, дорого. Поэтому стали возникать проекты, занимающиеся решением проблемы совместимости.

Ранее мы уже разбирали один из таких проектов – Polkadot. Прямым конкурентом Polkadot является проект Cosmos. Разработчики Cosmos также занимаются созданием собственной экосистемы, позволяющей эффективно взаимодействовать с другими блокчейнами. Но технология Cosmos значительно отличается от Polkadot.

В этой статье мы проведем обзор на cosmos atom и прочие составляющие проекта Cosmos.

Cosmos – это быстро расширяющаяся экосистема независимых взаимосвязанных блокчейнов, построенных с использованием удобных для разработчиков приложений и соединенных новаторским протоколом IBC.

Сам Cosmos – это не блокчейн, а экосистема. А основной блокчейн экосистемы Cosmos – это Cosmos Hub. Cosmos Hub является центром Cosmos, его связующим звеном.

К Хабу могут подключаться другие блокчейны – Зоны (Osmosis, Juno и др.). Зоны могут обмениваться данными между собой как раз за счет связи с Хабом. Такая связь позволяет совершать транзакции быстро и с минимальной комиссией.

Далее мы более детально рассмотрим принципиально важные элементы экосистемы Cosmos.

Tendermint – это ядро Cosmos, на основе которого строятся блокчейн-приложения. Он состоит из следующих компонентов:

  • Consensus – уровень консенсуса. Устанавливает правила работы блокчейна.
  • Networking – сетевой уровень. Занимается обработкой транзакций внутри сети. Скорость обработки в Cosmos поразительно высокая – 10.000 в секунду. Для сравнения: в Ethereum – 15 в секунду.
  • Application – приложение на основе сети и консенсуса.

На самом деле, подобная структура не является новаторской. Многие разработчики и так могут брать за основу консенсус и сеть другого блокчейна и на их основе строить приложения.

Возьмите, например, тот же STEPN – в его основе лежит сеть и консенсус Solana. Или любые NFT-коллекции – они также создаются на основе функционирующих блокчейнов: BAYC – на Ethereum, DeGods – на Solana и т.д.

Однако у Cosmos имеются дополнительные функциональные преимущества.

Cosmos SDK – это фреймворк, значительно упрощающий процесс создания приложений на Tendermint.

Разработчики могут создавать блокчейн-приложения на любом языке программирования. Также они могут использовать готовые модули и импортировать их в свои приложения. При этом им не нужно будет кодировать каждую строчку кода с нуля.

IBC – это один из модулей Cosmos SDK, позволяющий блокчейнам передавать между собой токены и другие данные. За счет этого блокчейны с разными приложениями и наборами валидаторов становятся совместимы.

У cosmos криптовалюта – ATOM. Токен ATOM торгуется на всех крупных биржах.

  • Запуск собственной ноды за счет стейкинга монеты
  • Право голоса за изменения внутри блокчейна
  • Оплата транзакций

Статистика ATOM на момент написания статьи:

Рыночная капитализация: $4,062,926,368

Рыночный ранг: 20

Кстати, за последнюю неделю ATOM смог приятно выделиться на фоне большинства токенов. В то время пока рынок падал, цена ATOM стремилась вверх.

Cosmos предоставляет огромный функционал для реализации децентрализованных приложений (DApps). Однако на данный момент на Cosmos не так много приложений. Дело в том, что разработчикам пока что вполне хватает функционала блокчейнов прошлого поколения (Ethereum, Solana, Polygon и др.) и у них нет нужды разбираться с фичами Cosmos.

Однако со временем сложность DApps будет расти, а функционала старых блокчейнов будет не хватать. И тогда Cosmos может оказаться главным героем. Если такое произойдет, то и монета ATOM станет более востребованной, а все ее холдеры смогут неплохо заработать.

Это не является инвестиционной рекомендацией, ведь главным героем может стать и прямой конкурент Cosmos – Polkadot. Либо могут появиться другие, более перспективные проекты.

Но на данный момент проект Cosmos выглядит довольно перспективно и, как нам кажется, заслуживает внимания.

High-level Overview

The Cosmos SDK is an open-source framework for building multi-asset public Proof-of-Stake (PoS) blockchains , like the Cosmos Hub, as well as permissioned Proof-of-Authority (PoA) blockchains. Blockchains built with the Cosmos SDK are generally referred to as application-specific blockchains.

The goal of the Cosmos SDK is to allow developers to easily create custom blockchains from scratch that can natively interoperate with other blockchains. We envision the Cosmos SDK as the npm-like framework to build secure blockchain applications on top of CometBFT. SDK-based blockchains are built out of composable modules, most of which are open-source and readily available for any developers to use. Anyone can create a module for the Cosmos SDK, and integrating already-built modules is as simple as importing them into your blockchain application. What's more, the Cosmos SDK is a capabilities-based system that allows developers to better reason about the security of interactions between modules. For a deeper look at capabilities, jump to Object-Capability Model.

What are Application-Specific Blockchains​

One development paradigm in the blockchain world today is that of virtual-machine blockchains like Ethereum, where development generally revolves around building decentralized applications on top of an existing blockchain as a set of smart contracts. While smart contracts can be very good for some use cases like single-use applications (e.g. ICOs), they often fall short for building complex decentralized platforms. More generally, smart contracts can be limiting in terms of flexibility, sovereignty and performance.

Application-specific blockchains offer a radically different development paradigm than virtual-machine blockchains. An application-specific blockchain is a blockchain customized to operate a single application: developers have all the freedom to make the design decisions required for the application to run optimally. They can also provide better sovereignty, security and performance.

Why the Cosmos SDK​

The Cosmos SDK is the most advanced framework for building custom application-specific blockchains today. Here are a few reasons why you might want to consider building your decentralized application with the Cosmos SDK:

Architectural Design Overview

Jay | Human Being

The Cosmos SDK is a npm-like framework that allows developers to easily build complex, secure and application-agnostic state-machines on top of Tendermint. Applications built with the Cosmos SDK are essentially multi-asset, interoperable public chains based on BPoS (Bonded Proof-of-Stake).

Below is a infographic of how transactions are handled by an application built with Cosmos SDK when replayed from Tendermint via ABCI, or DeliverTx to be specific:

Application Anatomy

A Cosmos SDK application generally consists of the following major components:

I. Full-Node Client

A full-node client is a binary (or daemon) built and run by participants in the Cosmos network to instantiate their own state-machine, and connect to other full-nodes. A full-node fully validates transactions and blocks of a blockchain.

II. Core Application

The core of a Cosmos SDK application mainly consists of Type Definition and Constructor Functions

Type Definition

Defined in app.go the type definition of a custom application is merely a struct comprised of the following:

  • Reference tobaseapp : A reference to the baseapp defines a custom app type embedding baseapp for your application. In other words, the reference to baseapp allows the custom application to inherit most of baseapp 's core logic such as ABCI methods and routing logic.
  • List of Store Keys: Each module in the Cosmos SDK uses multistore to persist their part of the state. Access to such stores requires a list of keys that are declared in the type definition of the app .
  • List of Each Module’sKeepers: keeper is an abstract piece in each module to handle the module's interaction with stores, specify references to other modules' keeper s, and implement other core functionalities of the module. For cross-module interactions to work all modules in the Cosmos SDK need to have their keeper s declared in the app 's type definition and exported as interfaces to other modules so that the keeper 's methods of one module can be called and accessed in other modules when authorized.
  • Reference tocodec : Defaulted to go-amino, the codec in your Cosmos SDK application can be substituted with other suitable encoding frameworks as long as they persist data stores in byte slices and are deterministic.
  • Reference to Module Manager: Self-explanatory. A reference to an object containing a list of the applications modules, a.k.a the Module Manager.

Constructor Function

As the name would suggest, a constructor function creates an instance of the app with the application's type definition declared in it. Specifically constructor functions perform the following actions when called:

  1. Initialize a new app instance with a reference to a codec , a reference to baseapp , and a list of store keys
  2. Initialize each module’s keeper s as defined in Type Definition in correct order (i.e. module Jay 's keeper s need to be instantiated before module Ken 's if module Ken 's keeper s require a reference to module Jay 's)
  3. Initialize the app 's Module Manager — an object where
  • A reference to each module is passed in (assuming the modules initialized here are intended to be modified later)
  • routes (to a module's handler ) and query routes (to a module's querier ) are initialized
  • Invariants (i.e. variables evaluated at the end of each block) of each module are registered. Each invariant’s value needs to be equal to a pre-defined value specified in its corresponding module
  • Order of execution between key functions (e.g. InitGenesis , BeginBlocker , EndBlocker ) of each module is set.
  • Remainers of app 's parameters are set
  • Stores are mounted
  • An app instance is returned

III. Modules

With many of key modules needed for a coherent application already built into the Cosmos SDK developers can easily build complex state-machines by integrating custom modules with the existing ones. Currently the SDK supports the following modules:

In the rest of this section, we will briefly explore two of the most fundamental building blocks of a module — Interfaces and Message Types.

Interfaces

By definition a Cosmos SDK module implements two interfaces: AppModuleBasic and AppModule . AppModule typically contains a module's inter-module dependent methods while the non-dependent ones (e.g. codec ) going into AppModuleBasic .

Message Types

Each module that implements the message interface needs to define its own custom message types. Such message types shall also be seen as "messages to be included in transactions". After receiving a block of transactions relayed from Tendermint through DeliverTx , the application needs to go through a 4-step procedure before committing state changes:

  1. Unmarshal each transaction from byte slices or []bytes
  2. Perform sanity checks (e.g. fees, signatures) and extract the message(s) contained in the transaction
  3. Route the message(s) to the appropriate module’s handler
  4. Process the message(s)

IV. Application Interfaces

Each Cosmos SDK application implements a Command-Line Interface (CLI) that is used to interact with full-node clients. Out of the box the CLI supports the following generic commands:

V. Dependencies and Makefile

The Cosmos SDK gives the developers the freedom to choose their preferred dependency manager and project building method. Go Modules is commonly used for the former and Makefile for the latter.

Remarks

Whether you are new to blockchain or not, learning a new codebase can be a bit daunting at first. This piece was my attempt to give developers looking to build on the Cosmos SDK a glance into the framework, and to hopefully help ease up their code break-in period. If you are ready to get your hands dirty with building your own application-specific blockchains, check out the tutorial here. Last but not least, thank you for checking out!

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

⛓️ A Framework for Building High Value Public Blockchains ✨

License

cosmos/cosmos-sdk

Name already in use

  • Local
  • Codespaces

Use Git or checkout with SVN using the web URL.

Work fast with our official CLI. Learn more about the CLI.

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

The Cosmos SDK is a framework for building blockchain applications. CometBFT (BFT Consensus) and the Cosmos SDK are written in the Go programming language. Cosmos SDK is used to build Gaia, the implementation of the Cosmos Hub.

WARNING: The Cosmos SDK has mostly stabilized, but we are still making some breaking changes.

Note: Requires Go 1.20+

To learn how the Cosmos SDK works from a high-level perspective, see the Cosmos SDK High-Level Intro.

If you want to get started quickly and learn how to build on top of Cosmos SDK, visit Cosmos SDK Tutorials. You can also fork the tutorial’s repository to get started building your own Cosmos SDK application.

For more information, see the Cosmos SDK Documentation.

See CONTRIBUTING.md for details on how to contribute and participate in our dev calls. If you want to follow the updates or learn more about the latest design then join our Discord.

Tools and Frameworks

The Cosmos ecosystem is vast. Awesome Cosmos is a community-curated list of notable frameworks, modules and tools.

Cosmos Hub Mainnet

The Cosmos Hub application, gaia , has its own cosmos/gaia repository. Go there to join the Cosmos Hub mainnet and more.

Inter-Blockchain Communication (IBC)

The IBC module for the Cosmos SDK has its own cosmos/ibc-go repository. Go there to build and integrate with the IBC module.

This Cosmos SDK project is not related to the React-Cosmos project (yet). Many thanks to Evan Coury and Ovidiu (@skidding) for this Github organization name. As per our agreement, this disambiguation notice will stay here.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *