SDK Background

Welcome to the Abstract Documentation!

Abstract is an account-based smart-contract development and distribution platform. Our platform and tooling allow developers to build and scale their applications in a chain-agnostic manner.

This first part of our documentation aims to provide you with the conceptual knowledge you need to understand the Abstract framework. The second part is a step-by-step guide on how to use the Abstract SDK to build your decentralized application.

Info

Prefer to watch? Check out our video library!

Who is Abstract For?

The Abstract SDK is designed for organizations and individual developers who want to build composable distributed applications in a fast, secure, and cost-effective manner.

We expect developers to be familiar with the Rust programming language and general programming concepts.

Info

Coming from 👾EVM👾 ? Be sure to read up on CosmWasm and its differences from EVM in the CosmWasm section.

Abstract Products

  • Abstract SDK: The Abstract Software Development Kit (SDK) is a Rust library that is tightly integrated with Abstract’s on-chain infrastructure. By using the SDK, developers can easily perform accounting-based operations and interactions with other smart contracts.

  • cw-orchestrator: A developer tool that simplifies the testing and deployment of smart contracts.

  • Abstract JS: A JavaScript library that facilitates smart-contract interactions from a browser-based environment.

Together these products form a complete end-to-end development platform for distributed applications.

How to Navigate the Docs

You can read the documentation in the order it is presented, or you can jump to the section that’s most relevant to you.

Help and Support

If you have any questions or ideas you want to discuss about our products, please contact us on Discord.

Want to make Abstract better?

Look at the Contributing & Community section if you want to get involved.

Technologies

In this section, we’ll briefly introduce you to the tech-stack that Abstract depends on. We’ll do this from a top-down approach, starting with the smart-contract framework.

Info

Already familiar with the stack? Jump to the next page to start learning about the Abstract SDK.

CosmWasm

The Abstract SDK and cw-orchestrator are tightly integrated with the CosmWasm smart-contract framework.

CosmWasm is a smart contract framework that is built on Rust and WebAssembly (WASM) to perform deterministic compute suitable for decentralized systems. It was born out of a desire to outgrow Solidity’s shortcomings.

It is the only smart contract platform for public blockchains that has seen heavy adoption and stress-testing outside of the EVM ecosystem.

To learn more about CosmWasm, check out its official documentation.

CosmWasm Coming from EVM

There are a few key differences between the EVM and CosmWasm that you should be aware of. The most important one is that instances of contracts and the code that they run against are two different concepts in CosmWasm. This means that you can have multiple instances of the same contract code running at the same time, each with their own state. This is not possible in EVM, where the contract code and the contract instance are the same thing.

This is an important difference to be aware of when we talk about migrations further in our documentation.

Summary

Migrations are a key feature of CosmWasm. They allow you to upgrade a contract’s code while retaining the state of the contract.

A migration doesn’t delete the code that was previously running for a contract. Code (a WebAssembly binary) is referred to by code-ids and contracts run against a specific code-id and get their own address space (and state) when they are instantiated. Hence migrations just update the code-id that a contract uses to run. I.e. The contract keeps its address and state but now runs on a different code-id (binary).

If you’re looking for a more in-depth comparison go read this article by the creator of CosmWasm.

Rust

Diving one level deeper, we have the Rust programming language. While theoretically any language can be compiled to WebAssembly, Rust is the only language that is officially supported. This is because Rust is a systems programming language that is designed to be fast and extremely safe.

Learn more about Rust here, or learn by doing the rustlings.

Javascript

You need to have a basic understanding of Javascript to use our front-end library.

You can learn about Javascript here.

Hosting Layer

The last component in the Abstract stack is the hosting layer. This is the layer that actually hosts the CosmWasm VM in which the smart-contracts run. Currently the Cosmos-SDK is the only officially supported hosting layer, but we are working on adding support for other hosting layers as they roll out.

Account Abstraction

Abstract uses Account Abstraction as a conceptual framework for building smart-contract applications. Our central idea is that, instead of building a monolithic smart-contract that users interact with, you let the smart-contract interact with a user-owned smart-contract wallet instead. Let’s dive a bit deeper into this concept and how it applies to Abstract’s own Abstract Accounts.

What is Account Abstraction?

In traditional blockchain interactions, a transaction is typically initiated by a user signing some data with their private key and transmitting that data (and its signature) to an endpoint for validation. Account abstraction modifies this process by making the transaction initiation and validation programmable. Essentially, it allows the transaction logic to be customized within a smart-contract, vastly extending the scope of UX possibilities.

The Abstract SDK provides what we call an Abstract Account, an extensible smart-contract wallet capable of holding tokens and interacting with other smart contracts. The ownership structure of an Abstract Account is customizable to fit your use-case.

flowchart
    subgraph Account Abstraction
    User2[fa:fa-user User] -- owns --> AA["Abstract Account (holds funds)"]
    direction TB
    Application2[Application] == interacts ==> AA
    end

    subgraph Traditional
    User[fa:fa-user Wallet] == funds ==> Application
    end

As displayed in the figure above, the Abstract Account (AA) is a smart contract wallet that is owned by the user. User action validation on the account is currently still performed through regular transaction authorization (wallet-based) but can be customized in the future to allow for OAuth login or other types of login methods.

The purpose of the Account is to hold funds for the user. Now if the user wants to interact with an application, they give the application permission to interact with the Abstract Account, and its funds. This way the user never gives the application custody over his/her funds.

Info

See EIP-4337 to read about account abstraction in the Ethereum ecosystem.

In the next section we’ll dig into the architecture of Abstract Accounts.

Abstract Accounts

Abstract Accounts are programmable smart-contract wallets used as the backbone for Abstract Apps, which will be covered later. Abstract Accounts hold funds for users and/or applications while exposing a set of programmable endpoints that can be used to configure and interact with the account.

Abstract Apps use the Abstract Account on which they are installed as the settlement layer for their transactions. In other words, Abstract Apps rarely hold funds themselves. Instead they control the funds of the Account that they are installed on. This separation of concerns allows for a more secure and modular design.

In the upcoming sections, we will delve deeper into the architecture of Abstract Accounts, providing insights into its design principles and components.

Architecture

Abstract’s infrastructure provides users with the ability to create a sovereign smart-contract wallet. We call this smart-contract wallet an Abstract Account. The account’s architecture has two primary components (smart-contracts): the Manager contract and the Proxy contract.

flowchart LR
    subgraph Abstr[Abstract Account]
        direction TB
        Manager --> Proxy
    end

    Owner -.-> Manager

As shown in the image above, an owner of an account, can configure his Abstract Account by sending messages to the manager contract. We don’t make any assumptions about the nature of this owner, it can be a wallet, multi-sig or any other ownership structure, allowing you to customize your ownership structure to fit your needs.

Info

You can read up on the different ownership structures that we explicitly support in our Ownership section.

The account’s architecture centers around configurable programmability. In other words, how can one configure the account (install applications, set permissions, etc.) to enable users and developers to easily customize it to do what they want?

Let’s dive deeper into the two components of the Abstract Account.

Manager Contract

The Manager is responsible for the account’s configuration and security, serving as the controller of the Abstract Account. It is responsible for the account’s important operations, including:

  • Authentication 🔐: Authenticating privileged calls and ensuring only approved entities can interact with the account.

  • Application Management 📦: Managing and storing information about the applications installed on the account, their inter-dependencies, permissions and configurations.

  • Account Details 📄: Storing the account’s details, such as its name, description, and other relevant information.

Proxy Contract

The Proxy is responsible for the account’s programmability and assets management, serving as the asset vault of the Abstract Account, taking care of:

  • Asset Management & Pricing 💰: Holding the account’s assets, including tokens, NFTs, and other fungible and non-fungible assets as well as allows for pricing assets based on decentralized exchange or oracle prices.

  • Transaction Forwarding (Proxying) 🔀: Routing approved transactions from the Manager or other connected smart-contracts to other actors.

Question

Why are these two contracts instead of one?

  1. Separation of concerns: By separating the contracts the proxy’s functionality (and attack surface) is as small as possible. The separation also allows for simple permission management as we want to separate the admin calls (verified by the manager) from module calls.

  2. Minimizing WASM size: Whenever a contract is loaded for execution the whole WASM binary needs to be loaded into memory. Because all the apps proxy their messages through the Proxy contract it would be smart to have this contract be as small as possible to make it cheap to load. While CosmWasm currently has a fixed cost for loading a contract irrespective of its size. We think that might change in the future.

Example Interactions

Proxy: Perform an action on Your Abstract Account

The diagram below depicts an Owner interacting with his Abstract Account through the Manager, and proxying a call to an external contract through the Proxy.

sequenceDiagram
    actor Owner
    participant Manager
    participant Proxy
    participant External Contract


    Owner ->> Manager: Account Action
    Manager ->> Proxy: Forward to Proxy
    Proxy ->> External Contract: Execute

Manager: Enabling IBC on Your Abstract Account

Enabling the IBC functionality on your Abstract Account is done via the Manager contract with the UpdateSettings message. By doing so the IBC client will be registered to your account, enabling your modules to execute cross-chain commands.

sequenceDiagram
    autonumber
    actor U as Owner
    participant M as Manager
    participant VC as Version Control

    U ->> M: UpdateSettings
    Note right of U: ibc_enabled
    M -->>+ VC: Query IBC Client address
    VC -->>- M: Return IBC Client address
    M ->> M: Register IBC Client

Modules

Modularity is a core design principle of the Abstract platform. What enables this modularity are smart-contracts that we call modules.

A module in Abstract is a smart-contract that can be installed on an Abstract Account to extend the account’s capabilities. Modules can be installed, removed, and configured by the account’s owner, allowing for a high degree of customization. Additionally, modules can take on dependencies on other modules and securely interact with each other.

Instead of building every part of an application from scratch, application developers can make use of an existing availability of pre-built logical components.

Question

When you’re writing software, do you use libraries or do you write everything from scratch?

The obvious answer is that you use libraries. You use libraries because they save you time and effort, allowing you to focus on the core functionality of your application. You also use libraries because they’re tested and proven to work, reducing the risk of bugs and vulnerabilities.

Modules allow you to do the same thing, but with smart-contracts.

You can leverage modules either from Abstract’s extensive library or those crafted by other developers available in the module library. Most importantly any application on Abstract, including yours, is a module.

How Modules Work

As mentioned, a module’s functionality can be accessed by installing it on an Abstract Account. The process of installing a module involves calling the Manager contract of an Abstract Account to perform its installation. An analogy to installing a module is pressing the “install” button for any app in the iOS/Android app store where the module is the App and the Abstract Account is the phone.

Info

As described in a previous section, the Manager keeps track of all installed modules and manages their permissions and interactions.

Through this system users can easily customize individual Abstract Accounts, permitting the installation or removal of modules according to their needs. In doing so, it effectively adapts the Account’s functionality.

From the perspective of a developer, the Abstract framework sets conventions and standards that allow leveraging existing modules during the development of new ones. It also provides a supply chain for smart-contract software, allowing developers to create and market their modules to users and other developers through our platform.

Security

Security is a top priority at Abstract. Every module listed on the mainnet marketplaces must undergo a thorough auditing process before it is made available to users and developers. This process scrutinizes the module’s code, checking for potential vulnerabilities, and ensuring that it adheres to best security practices. Additionally we are firm believers of open-source software and encourage developers to publish their code on GitHub.

While no system can guarantee absolute security, this rigorous vetting process, coupled with the inherent security benefits of Abstract’s and CosmWasm’s architecture, mitigates potential risks to a considerable extent.

The Abstract platform also maintains a Version Control for all the modules, allowing developers to track changes, understand the evolution of a module, and choose versions that have passed security audits.

Module Types

As explained in the previous section, a module is a smart-contract that extends an Account’s functionality. You can explore all the available modules on the modules tab of your Account through the web-app.

Modules are classified in the following categories:

  • App: modules that add a functionality, exposing new entry-points for you or your users.
  • Adapter: modules that act as a standard interface between your Account and external services.
  • Standalone: modules not built within Abstract, but registered to your Account so that your Account can manage them.
drawing

Module IDs

Every module is uniquely identified by a module ID. This ID is a string that follows the following format:

<namespace>:<name>

The namespace is a string that resembles the publishing domain of a module developer, while the name is the name of the module itself. For example, the abstract:etf module is an App module developed by Abstract where abstract is the namespace and etf is the name of the module.

Additionally each module has a SEMVER version number that can be used to uniquely identify a specific version of a module, or just get the latest version. Module IDs and their versions are used to install modules on an Abstract Account.

A module ID is independent of the kind of module it refers to.

Apps

An App module adds or alters the functionality of an Abstract Account, exposing new functions to you and/or your users. This could range from adding advanced financial logic to data management features or permission systems, depending on your use-case.

Each App module instance is exclusive to a single Abstract Account, meaning the instance is created and owned by the Account, ensuring the owner has full control over the module’s functionality and lifecycle. This level of control extends to the management of upgrades, maintenance, and any customization that might be required for the specific use case of the application.

Because each Account has its own instance of an App, App modules can be tightly integrated with the Account’s existing infrastructure. This includes the ability to interact directly with other modules (including Apps) installed on the same account, enabling powerful synergies and cross-module functionality.

Example

The abstract:etf module is an app that allows external users to buy and sell “shares” in your Account, representing a portion of the Accounts’ value.

Adapters

Adapters serve as standard interfaces that facilitate communication between your Abstract Account and various external services. They act like bridges, enabling your account to interact with different smart contracts and blockchain services, thereby enhancing the interoperability of your applications.

The key function of an Adapter is to generalize functionality. Regardless of the underlying blockchain or smart contract protocol, the Adapter provides a standard interface that maintains consistency and simplifies the interaction process. As such, Adapters significantly simplify the developer experience and reduce the time required to integrate with various external systems.

Unlike other modules specific to each Abstract Account, Adapters are “global” in nature. This means that they are shared between multiple accounts. Due to this, Adapter modules are not migratable. This design choice is aimed at preventing supply-chain attacks that could potentially compromise the security of the Abstract ecosystem.

While individual Abstract Account owners can decide which Adapters and versions they wish to utilize, the overall control and maintenance of Adapters are handled at a platform level. This approach ensures that Adapters remain reliable, secure, and consistent across all Accounts.

Example

The abstract:dex module allows Accounts to access standard functions on dexes with the same interface, regardless of whether they’re local to the chain or across IBC.

flowchart LR
    subgraph Accounts
        direction BT
        subgraph Acc1["Account 1"]
            App1["abstract:etf"]
        end
        subgraph Acc2["Account 2"]
            App2["abstract:etf"]
        end
    end

    subgraph Adapters
        Acc1 --> Adapter1{{"abstract:dex"}}
        Acc2 --> Adapter1
    end

    Adapter1 --> dex1([Osmosis])
    Adapter1 --> dex2([Wyndex])
    Adapter1 --> dex3([Astroport])
Two Accounts with the abstract:etf app module installed, using the abstract:dex adapter to interact with multiple dexes

Installing and Uninstalling Modules

The following are sequence diagrams of the process of installing and uninstalling a module on an Abstract Account. As you can see, the process happens via the Manager, and it can be done by the Account owner through the web-app.

sequenceDiagram
    autonumber
    actor U as Owner
    participant M as Manager
    participant MF as Module Factory
    participant VC as Version Control
    participant P as Proxy
    U ->> M: InstallModule
    M ->> MF: InstallModule
    MF -->>+ VC: Query Module Details
    alt adapter
        VC -->>+ MF: Return address
    else app / standalone
        VC -->>- MF: Return code_id
        MF -> MF: Instantiate module
    end
    MF ->> M: Register module address
    M ->> P: Update module allowlist
Installing a Module

At this point you should be able to understand the message flow depicted above. Just to be sure, we’ll briefly outline the process’s steps.

Installing a module starts by the Owner of the Account requesting the installation of the module on the Account. This request is sent to the Manager contract of the Account. The request contains the module ID(s) and possible instantiate messages for any App/Standalone modules that should be installed (aka instantiated).

The Manager contract verifies the request and forwards it to the Module Factory. The Module Factory then queries the Version Control (the on-chain module registry) for the module details. These module details contain both the version of the module as well as its type-specific data. This type-specific data is depicted by the two alternatives (alt) of the returned query.

Either the query returns an Adapter’s address (which is already instantiated) or it returns an App/Standalone code-id. This code-id is then used by the Module Factory to instantiate an instance of that module.

After instantiating the modules the Manager registers the modules internally and updates the whitelist on the Account’s Proxy contract. This whitelisting provides the modules with the ability to proxy message execution through the Account.

sequenceDiagram
    autonumber
    actor U as Owner
    participant M as Manager
    participant P as Proxy
    U ->> M: UninstallModule
    M -> M: Deregister module
    M ->> P: Update Proxy Whitelist
Uninstalling a Module

Uninstalling a Module follows a similar execution flow as shown above.

Info

In both flows we omitted the dependency-check logic, which will be discussed in more detail later.

Example Execution Flows

The following are sequence diagrams of the process of executing a function on a module of an Abstract Account. We show three examples of executing a module: Owner Execution, Adapter Execution, and Dependency Execution.

Let’s explore each of them.

Owner Execution

To execute a (permissioned) message on a specific module, the Owner can call the module directly. The Module knows who the Owner of the Account is.

sequenceDiagram
    autonumber
    actor U as Owner
    participant Md as Module ("addr123")
    U ->> Md: Execute

Adapter Execution

In the following example, the abstract:dex adapter is installed on an Account, and the Owner requests a swap on a dex. By providing the proxy address of the Account in the call, the adapter can assert that the caller is the Owner of the Account.

sequenceDiagram
    autonumber
    actor U as Owner
    participant D as abstract:dex
    participant VC as Version Control
    participant A as ANS
    participant P as Proxy
    participant T as Dex Pool
    Note right of U: Dex::Swap {proxy: "juno1xd..."}
    U ->> D: Call module
    D -->+ VC: Load proxy address for Account
    VC -->- D: Address
    D -->>+ A: Resolve asset names
    A -->> D: Asset infos
    D --> A: Resolve dex pool
    A -->>- D: Pool metadata
    D --> D: Build swap msg for target dex
    D ->> P: Forward execution
    Note over VC, A: DexMsg
    P ->> T: Execute
    Note right of P: DexMsg

Dependency Execution

In this example, we use the Equilibrium App’s Rebalance function as an example. Modules with dependencies (equilibrium:balancer is dependent on abstract:etf and abstract:dex) have their addresses dynamically resolved when called.

sequenceDiagram
    autonumber
    actor U as User
    participant B as equilibrium:balancer
    participant P as Proxy
    participant M as Manager
    participant D as abstract:dex
    participant T as Target Dex
    U ->> B: Rebalance
    B -->>+ P: Query Allocations
    P -->>- B: Allocations
    B --> B: Calculate rebalancing requirements
    B -->>+ M: Query abstract:dex address
    M -->>- B: Address
    B ->> D: Call SwapRouter on dex
    D --> D: Build swap msg for target dex
    D --> D: Load proxy address
    D ->> P: Forward execution
    Note over M: DexMsg
    P ->> T: Execute
    Note over D, M: DexMsg

Module Upgradability

Smart-contract migrations are a highly-debated feature in smart-contract development. Nonetheless Abstract believes it to be a powerful feature that allows for fast product iteration and bug-fixing. In the spirit of crypto we’ve designed a system that allows for permissionless software upgrades while maintaining trustlessness.

Info

If this is the first time you hear about smart-contract migrations, we recommend you to read the CosmWasm documentation on the topic.

Module Version Registry

Upgrading a module is facilitated by the module version registry in the version control contract. The mapping allows your Account to:

  • Instantiate a module of the latest versions. (see the previous section on modules)
  • Upgrade a module to a new version.
  • Provide custom modules to other developers.
  • Do all this without losing sovereignty.

There are two types of possible upgrade paths, although they appear the same to you as a developer.

Migration Upgrade

Most module updates will perform a contract migration. The migration can be evoked by the owner and is executed by the manager contract. Migrations apply to the App and Standalone module types.

Move Upgrade

Adapter modules can not undergo any migrations. Therefore, each Adapter version is instantiated on a different address.

When a user decides to upgrade an Adapter module, the abstract infrastructure moves that user’s configuration on that Adapter to the new Adapter and removes the permissions of the old Adapter.

However, any modules that depend on the upgraded Adapter module don’t have to update any of their state as a module’s address is resolved dynamically through the manager contract, similar to how DNS works! This is explained in more detail in the dependency execution flow of the last section.

Module Upgrade Flow

You can skip this section if you're not interested in the technical details of how module upgrades work.

Abstract manages the state-management related to module upgrades for you, ensuring your infrastructure remains intact and your applications continue to function smoothly through every upgrade.

Upgrades are carried out in a manner that consistently maintains the integrity and security of your system. I.e. we programmed the system to disallow any upgrade actions that would break your system’s version requirements.

The process for upgrading modules is shown in the following diagram:

sequenceDiagram
    autonumber
    actor U as Owner
    participant M as Manager
    participant VC as Version Control
    participant P as Proxy
    U ->> M: Upgrade
    loop for each module
        M -->> VC: Query reference
        alt adapter
            VC -->> M: Return address
            M ->> M: Update module address
            M ->>+ P: Remove old adapter from allowlist
            M ->> P: Add new adapter to allowlist
            deactivate P
        else app / standalone
            VC -->> M: Return code_id
            M ->> M: Migrate module to new code_id
        end
    end

    opt
        M -> M: Migrate self
    end
    M -> M: Update dependencies
    M --> M: Check dependencies  

An important aspect of this process is how the integrity of the modules is ensured.

Proposed module upgrades are performed sequentially and atomically while keeping track of all changes. As the last step in the upgrade flow a collection of version requirements and dependency checks are performed to ensure that module’s dependencies are present and version-compatible.

Abstract SDK

The attentive reader will already know that the Abstract SDK is a Rust library that is tightly integrated with Abstract’s on-chain infrastructure. More importantly though, the Abstract SDK is a tool that allows developers to easily perform accounting-based operations and interactions with other smart contracts within their own module.

From a high-level perspective, modules built with the Abstract SDK can use on-chain dependencies (other modules) to isolate specific functionalities. In this way, a module built with the Abstract SDK can explicitly define its dependencies and use them to perform complex multi-contract interactions with very minimal code. This, in turn, allows you to focus on the novel functionality of your application without inheriting the complexity of the underlying infrastructure.

SDK Features

At the heart of the Abstract SDK are “features” - Rust traits that can be seen as building blocks you can combine in various ways. Each feature provides a specific capability or function. By composing these features it is possible to write advanced APIs that are automatically implemented on objects that support its required features.

APIs

Abstract APIs are Rust structs that can be constructed from within a module if that module implements a set of features. Most of these features will already be implemented by us, so don’t have to worry about their implementation.

These retrievable API objects then exposes functions that simplify module development.

For example, the Bank API allows developers to transfer assets from and to an address. The Bank API can be constructed and used as follows:

// Construct the Bank API
let bank: Bank = app.bank(deps.as_ref());
// Do a transfer
let transfer_action: AccountAction = bank.transfer(vec![asset.clone()], recipient)?;

Note: The Bank API is just one of the many APIs that are available in the Abstract SDK. You can find a list of all available APIs (and how to build one yourself) in the abstract-sdk Rust docs section.

We’ll dive deeper into the Abstract SDK’s APIs in the Build With Abstract section.

Module Bases

Our module bases are generic CosmWasm contract implementations that:

  • Have some state and functionality already implemented.
  • Can be extended and composed by appending your custom logic to them.

Think of each of these bases as a foundation for building your application using the Abstract SDK. There are different types of bases available, each tailored for specific needs and functionalities.

We will go into the technical details of these bases and their differences in the Build With Abstract section.

Example: Autocompounder

Let’s take a look at what an Autocompounder app built with the Abstract SDK would look like. This Autocompounder has a dependency on two adapters, a Dex and Staking adapter. Drawing out the architecture would result in something like this:

flowchart LR
    subgraph Autocompounder Application
        direction BT
        Autocompounder -.-> Dex
        Autocompounder -.-> Staking
        Staking --> Account
        Autocompounder --> Account
        Dex --> Account
    end

    User[fa:fa-users Users] ==> Autocompounder

Note

The Account is a set of smart-contracts that function as smart-contract wallet infrastructure. It holds the application’s funds. We covered the Account architecture in detail here.

Each solid arrow represents permissions to perform actions on behalf of the account. These permissions allow the contracts to move funds, interact with other contracts through the account, and perform other actions. It does this by sending messages to the account, which then executes them on behalf of the module. This is the basic idea behind account abstraction and is further elaborated in on the account abstraction page. Now, let’s focus on the dotted arrows.

Each dotted arrow indicates a dependency between modules. These dependencies are explicitly defined in the module that takes on the dependencies and are asserted when the module is installed. In this example the Autocompounder module is able to access special functionality (like swapping or staking assets) from its dependencies (the dex and staking adapters). Through this mechanism, a major reduction in the application’s amount of code and complexity is achieved.

From a developer ecosystem standpoint, this modular approach encourages collaboration and cross-team code re-use, a practice that has been proven to accelerate development and increase developers’ productivity.

Account Ownership

Abstract Accounts can be owned by any (custom) governance infrastructure. Because most developers appreciate an easy-to-use interface to control their Account, Abstract supports two fully integrated governance structures that ensure a seamless user experience.

When configuring the governance for your Account, you will be prompted to choose between supported governance types, Monarchy or Multi-signature.

Info

Not interested in account ownership? Skip to our section on Framework Components.

Monarchy

In a monarchy, a single wallet has full control over the Account. If you’re connected with a wallet, your address will be automatically inserted as the owner.

graph TD
    A[Single Account] -->|Controls| B(Abstract Account)

Multi-signature

Multi-signature (“multisig”) governance is a governance structure that requires a subset of its members to approve an action before it can be executed. Abstract implemented this functionality with the cw-3 standard.

Here are a few terms you need to know about when configuring your multisig:

  • Voter weight 🏋️‍♂️: The weight that the voter has when voting on a proposal.
  • Threshold 📊: The minimal % of the total weight that needs to vote YES on a proposal for it to pass.
graph TD
    subgraph Voters
        V1[Voter 1]
        V2[Voter 2]
        V3[Voter 3]
    end

    V1 --> A[Multisig Wallet]
    V2 --> A
    V3 --> A
    
    A -->|Controls| B(Abstract Account)

    B[Abstract Account]

Example

Suppose you share an account with your friends and want to use a multisig governance structure to prevent unilateral control over the account. You have five stakeholders, and you want at least 60% of the total voting weight to approve a proposal for it to pass.

  1. Set up the multisig module in your dApp.
  2. Assign voter weights to each of the five stakeholders. For instance, A: 30%, B: 20%, C: 20%, D: 15%, and E: 15%.
  3. Configure the multisig module with a 60% threshold.

With this configuration, any proposal will require approval from stakeholders with a combined voting weight of at least 60% to be executed. This ensures a more democratic decision-making process and reduces the risk of a single stakeholder making unilateral decisions.

Sub-Accounts

A Sub-Account is an Abstract Account that is owned by another Abstract Account. They are important to users as they allow users to safely experiment with different apps without the concern of those apps accessing funds from their main account or other apps.

Sub-accounts are easily created by calling CreateSubAccount on any account. The diagram below shows how sub-accounts are owned by a main Account or other sub-accounts.

flowchart TB
    Account
    SubAccount-A
    SubAccount-B
    SubAccount-C
    Owner --> Account
    Account --> SubAccount-A
    Account --> SubAccount-B
    SubAccount-A --> SubAccount-C

To simplify accessing or configuring a sub-account or app we allow calling any sub-account or any app on a sub-account directly without requiring the message to be proxied through the top-level account. The diagram below shows how an account owner can configure the sub-accounts and apps directly that are part of his main account.

flowchart TB
    direction TB
    subgraph AbstrA[Sub-Account A]
        direction TB
        ManagerA[Manager] --> ProxyA[Proxy]
        AppA[App]
    end

    subgraph AbstrB[Sub-Account B]
        direction TB
        ManagerB[Manager] --> ProxyB[Proxy]
    end

    subgraph AbstrC[Sub-Account C]
        direction TB
        ManagerC[Manager] --> ProxyC[Proxy]
        App
    end

    subgraph Abstr[Account]
        direction TB
        Manager --> Proxy
    end

Owner --> Manager
Manager --> ManagerA
Manager ---> ManagerB
ManagerB --> ManagerC

Owner -.Configure App.....-> AppA
Owner -.Configure Account....-> ManagerC

As a result of this structure, complex multi-account systems can easily be transferred between governance systems by simply changing the owner of the top-level account.

Info

Sub-accounts have a depth of 2. I.e. an account can have sub-accounts, and those sub-accounts can have sub-accounts themselves, but no further.

Interchain Abstract Accounts

The cosmos is going interchain. The arrival of Inter-Blockchain Communication (IBC) launched us into a new paradigm in application development. New use-cases and solutions to existing UX problems are now possible. As the interchain application platform, Abstract attempts to make IBC accessible to developers and users alike. In this section we’ll delve into interchain application development, what makes it so hard and how Abstract can help you create your first #Interchain application.

What is The Interchain?

The interchain, sometimes called the internet of blockchains, is the concept of a network of blockchains that can communicate with each other. This is made possible by the Inter-Blockchain Communication (IBC) protocol, which is a standard for communication between blockchains. IBC is a protocol that allows for the transfer of arbitrary data between blockchains. This means that users can send data (like tokens) from one blockchain to another without third-party trust assumptions. This is a huge step forward for the blockchain industry, as it allows for the creation of a network of blockchains that can independently communicate with each other.

Info

If you’re interested in a visual representation of the interchain, check out the map of zones.

Building on The Interchain

Developers quickly started developing applications with IBC after its release. But they quickly ran into a major problem. IBC is not developer friendly. It’s a low-level protocol that requires extensive knowledge about its inner workings. These problems were quickly recognized by the CosmWasm community. In response DAO-DAO built Polytone, an Interchain Account (ICA) solution for CosmWasm smart-contracts. This was a great step forward for interchain CosmWasm development, but it introduced its own complexities and knowledge requirements.

As a response, Abstract has created its own ICA solution called Interchain Abstract Account (ICAA). The goal of ICAA is multifold. First, it aims to make IBC accessible to developers by removing any knowledge requirements about the underlying technology. Using IBC is as simple as enabling it on an Abstract Account and interacting with it through our SDK. Second, it aims to make IBC a backend technology, unbeknown to users. Users should not have to know about IBC. They should only have to know about the application they are using.

Interchain Abstract Accounts (ICAA)

An Interchain Abstract Account is an Abstract Account that is owned by another Abstract Account which is located on a different chain. This relationship is showcased in the diagram below.

flowchart LR
    subgraph Juno
        direction BT
        Account
    end

    subgraph Osmosis
        direction BT
        Account -- Polytone --> ICAAOsmo[ICAA]
    end
direction TB
Owner[fa:fa-user Owner] ==> Account

When a user creates an Abstract Account they do so locally on whichever chain they prefer. In this scenario the user opted to create his account on the Juno network.

After account creation the user (or his application) opted to create an ICAA on Osmosis. The ICAA creation is handled by the Account Factory in a similar way to regular account creation. After successfully creating the ICAA, the user (and his/her applications) can interact with the ICAA as if it were a regular account. Applications can send tokens to the ICAA, execute smart-contract calls, request queries and more. With the help of Polytone, the ICAA returns the result of these actions to the application.

Info

The account creation process is covered in detail in the Account Factory section.

ICAAs can be chained together, creating a network of accounts that can interact with each other. This allows for the creation of complex applications that span multiple chains. The diagram below showcases this relationship.

flowchart LR
    subgraph Juno
        direction BT
        Account([Account])
    end

    subgraph Osmosis
        direction LR
        Account --> ICAAOsmo([ICAA])
        ICAAOsmo2([ICAA 2])
    end

    subgraph Terra
        direction RL
        Account --> ICAATerra([ICAA])
    end

    subgraph Archway
        direction RL
        ICAATerra --> ICAAArch([ICAA])
        ICAAArch --> ICAAOsmo2
    end
    Owner[fa:fa-user Owner] ==> Account

Each of these accounts has a unique AccountId defined by the account’s origin chain and the path over which it was created. This allows the account’s owner to decide how messages should be routed.

flowchart LR
    subgraph Juno
        direction BT
        Account([local:1])
    end

    subgraph Osmosis
        direction LR
        Account --> ICAAOsmo([juno:1])
        ICAAOsmo2([juno>terra>archway:1])
    end

    subgraph Terra
        direction RL
        Account --> ICAATerra([juno:1])
    end

    subgraph Archway
        direction RL
        ICAATerra --> ICAAArch([juno>terra:1])
        ICAAArch --> ICAAOsmo2
    end
direction TB
Owner[fa:fa-user Owner] ==> Account

Interchain Applications

We’re now able to easily create interchain applications. I.e. a single smart-contract that we can deploy to multiple blockchains that uses IBC to communicate about its state. Any chain-specific logic can be handled by the application’s dependencies, like the dex or staking adapter.

Info

Need a refresher on adapters? Check out the Adapters section.

Account Oracle

The Account Oracle is an integrated on-chain service that allows you to retrieve the value of all assets held in an account in terms of a base asset. This simple functionality can be used to create account-based debt positions, automated trading bots and much more!

Info

This section is mainly focused on developers. If you’re a user feel free to skip this section!

Value is relative

The value of something is always relative to some other thing. A bitcoin isn’t valued at 20,000, it’s valued at 20,000 USD. Likewise the first setting required to configure Abstract’s oracle is: In what currency do you want your Account’s assets to be valued?

We’ll call this currency the base asset. There can never be more than one base asset and every asset will be valued in terms of this base asset.

With a base asset selected you can set up a value-reference for each asset that is held in your Account. A value-reference is a configuration that references some data that tells the contract how it should determine the value for that asset. Consequently your base asset won’t have an associated value-reference as everything is valued relative to it! Don’t worry, we’ll show some examples after covering the basics.

Types of Value-References

To ensure that you configure and use the oracle correctly you’ll need to understand, on a high level, how the value-reference system works and what its limitations are. Your app’s security might depend on it!

Hint

Remember: Every asset, apart from the base asset, has an associated value-reference and that value-reference allows the Oracle to determine the value of the asset in terms of the base asset.

Currently there are four value-reference types that can be applied to an asset. Lets go over them.

1. Reference Pool

This is the most common value-reference type. It points to a dex trading pair where one of the two assets of the pair is the asset on which this value-reference is applied. The Account takes this information and does three things.

  1. Query how much X the Account holds.
  2. Determine the price of asset X, defined by the pool X/Y.
  3. Calculate the value of asset X in terms of asset Y given the price. This gives us the value of asset X in terms of asset Y.

Example

Your Account has 10 $JUNO and 50 $USDC. You’d like to be shown the value of your assets in terms of USD.

  1. You identify that you want every asset denominated in US dollars. Therefore you choose $USDC as your base asset.
  2. You identify the easiest route to swap your $JUNO for $USDC which is a trading pair on Osmosis. Therefore you add $JUNO to your Account with a Pool value-reference.
  3. The ratio of $JUNO/$USDC in the pool is 1/10 so 1 $JUNO = 10 $USDC.

The Oracle can then presume that if you would swap your $JUNO to $USDC in that pool, you would end up getting 10 $USDC. Therefore the total value of your assets is 60 $USDC.

2. Liquidity Token

A liquidity token is nothing more than a claim on a set of assets in a liquidity pool. Therefore the value of each liquidity token is defined by the composition of asset held within that pool.

3. Value As

You might want to set the value of some asset in terms of another asset. For example, you could argue that every stablecoin is equal in value, irrespective of small fluctuations between them.

4. External

Some assets/positions are more complex. These include, but are not limited to: staked tokens, locked tokens and most third-party vault-like products. The Account needs to interact with Adapter modules that interact with these services to find out how it should value the asset/position.

Use With Caution

As we’ve outlined, each asset is valued relative to an asset or multiple assets. By recursively calling this value-reference function on each asset we can determine the value of any asset relative to our base asset.

Warning

As each asset’s value is referenced to some other asset through a price relation it exposes assets with a weak link to the base asset to a lot more volatility and attack surface. Therefore we recommend that you select a highly-liquid base asset with the highest liquidity trading pairs when configuring your assets.

Danger

While this way of determining an asset’s value is very intuitive, it doesn’t account for bad actors. Manipulation of asset prices to trigger smart-contract actions isn’t uncommon. Therefore we don’t recommend this version of the Account for creating high-value automated-trading products. No worries, an implementation based on oracle prices is in the works!

Any questions regarding the oracle and its configuration can be asked in our Discord server!

Monetization

Our app-store provides developers with the ability to monetize their modules by configuring an installation fee for their modules. By introducing monetization strategies, Abstract offers developers incentives to build and share valuable modules with the community.

Here’s a concise breakdown of how this works:

  • As explained, modules are the building blocks of Abstract Apps and can be installed on Abstract Accounts.
  • Modules can be developed and published to the Abstract App Store by any developer.
  • Each module can be configured with a Monetization strategy, primarily:
    • InstallFee: A fee set by the developer which must be paid by other users to install the module. This fee is then transferred to the namespace owner’s account, which is fetched from the version control registry.
    • None: No monetization strategy is applied for the module.

All module monetization details are stored in the version control but are verified and enforced by the module factory.

To assist users in budgeting, the module factory provides the SimulateInstallModules query, which returns the total sum of funds required to install a specified set of modules, including monetization and initialization funds.

Subscriptions

In addition to one-time installation fees, the Abstract framework empowers developers to introduce subscription-based monetization strategies for their modules. This model facilitates a steady stream of revenue, enhancing the sustainability and continuous development of the modules.

Subscriptions are being worked on and will be available soon, stay tuned!.

Account Console

Warning

The Account Console is in beta. Please report any issues you encounter on our Discord.

The Account Console is a web-based developer tool that allows you to inspect and interact with your Abstract Accounts.

It also allows you to easily view the abstract-specific infrastructure details like the Abstract Name Service or the Version Control.

The Account Console allows you to:

  • Account Management: Create, update, and delete accounts.
  • Module Management: Install, update, and delete modules.
  • Name Service: Register and manage human-readable names for your accounts.
  • Dev Tools: Visual contract message builder, contract explorer, and more.

Info

Note that using the Console is not required to develop on Abstract. All the features available in the console can be accessed programmatically using the Abstract Client crate. Using the Abstract Client crate is recommended for production use cases.

Accessing the Account Console

You can access the Account Console where you can create an account, claim namespaces and more by visiting console.abstract.money. You will be able to select the network you want to connect to, and then proceed to create your Abstract Account.

Account Management

Create Account

Creating an account is straight forward process. Once in the Account Console, click “Create Account”. You will be able to select the network you want to connect to, and then proceed to create your Abstract Account.

Are you having trouble creating an account? Please contact us on Discord and we’ll help you out.

Once the account is created, you can see the overview of the account, including the manager and the proxy contracts, among other details.

Claim a Namespace

Now that you have your account you can proceed to claim your namespace. The namespace will be exclusively linked to your Abstract Account and will prefix your module names to form a unique module identifier.

For example, if your namespace is myapp and your module name is mymodule then your module identifier will be myapp:mymodule.

You can easily claim your namespace by going to your Account on our website and click the “Claim Namespace” button on the account page. You will be asked to pay a small fee to claim your namespace. This fee is used to prevent namespace squatting and to help us maintain the Abstract ecosystem.

Info

Please be aware that you need access to claim namespace on mainnet. Reach out to us on discord.

Abstract Name Service

The Abstract Name Service (or ANS in short) is an on-chain data store of the most important address space related data of the blockchain it is deployed on. It allows for chain-agnostic action execution and dynamic address resolution. These features enable both users and developers to engage with the blockchain in a more intuitive manner.

ANS Architecture

The ANS is a smart contract that stores the following data:

  • Assets: The most relevant assets on the local blockchain.
  • Contracts: Contracts related to certain protocols or applications that could be dynamically resolved. This could be used to store the address for an asset-pair for a dex. For example, “osmosis/juno,osmo” could be resolved to the address of the osmosis pool that allows you to swap osmo for juno.
  • Channels: IBC channel data to map a protocol + destination chain to a channel id. This allows for dynamic IBC transfers without having to know the channel id beforehand.

The ANS contract state layout is defined here. It consists of key-value mappings for the different entries.

#![allow(unused)]
fn main() {
    /// Stores name and address of tokens and pairs
    /// LP token pairs are stored alphabetically
    pub const ASSET_ADDRESSES: Map<&AssetEntry, AssetInfo> = Map::new("assets");
    pub const REV_ASSET_ADDRESSES: Map<&AssetInfo, AssetEntry> = Map::new("rev_assets");

    /// Stores contract addresses
    pub const CONTRACT_ADDRESSES: Map<&ContractEntry, Addr> = Map::new("contracts");

    /// stores channel-ids
    pub const CHANNELS: Map<&ChannelEntry, String> = Map::new("channels");

    /// Stores the registered dex names
    pub const REGISTERED_DEXES: Item<Vec<DexName>> = Item::new("registered_dexes");

    /// Stores the asset pairing entries to their pool ids
    /// (asset1, asset2, dex_name) -> {id: uniqueId, pool_id: poolId}
    pub const ASSET_PAIRINGS: Map<&DexAssetPairing, Vec<PoolReference>> = Map::new("pool_ids");

    /// Stores the metadata for the pools using the unique pool id as the key
    pub const POOL_METADATA: Map<UniquePoolId, PoolMetadata> = Map::new("pools");
}

Info

You can find the full source code for the ANS contract here.

Resolving Entries

The information provided by the ANS is great to have. However, directly calling CosmWasm smart queries on the ANS contract can make your code messy and significantly raise gas usage. For this reason, we offer three methods to efficiently and dependably execute low-gas queries on the ANS contract.

Resolving your asset/contract name to its matching value is much like resolving a domain name like abstract.money to its IP address (172.67.163.181).

There are three ways to resolve your entry into its matching value.

Both App and Adapter objects implement the AbstractNameService trait which allows you to resolve entries.

let juno_name = AssetEntry::new("juno");
let juno_asset_info = my_app.name_service(deps).query(&juno_name)?;

Resolve Trait

Entries that are resolvable by the Abstract Name Service implement the Resolve trait which gives them the ability to be resolved by ANS explicitly.

let ans_host = my_app.ans_host(deps)?;
let juno_name = AssetEntry::new("juno");
let juno_asset_info = juno_name.resolve(&deps.querier, &ans_host)?;

AnsHost Object

You can also load or create an AnsHost struct. This struct is a simple wrapper around an Addr and implements methods that perform raw queries on the wrapped address.

let ans_host = AnsHost {address: "juno1...."};
let juno_name = AssetEntry::new("juno");
let juno_asset_info = ans_host.query_asset(deps, &juno_name)?;

Contracts

Info

At this point you have enough knowledge to start building your own Abstract Module. If you want to start building, head over to our Getting Started section! 🛠️

In the previous sections, we covered different high-level aspects of the Abstract framework. In the following sections, we will explore the different contracts of the Abstract framework in more detail.

Here’s a peek into the key elements that form the foundation of the Abstract framework:

  • Abstract Name Service (ANS): A smart-contract oriented name service that enables chain-agnostic action execution by storing easily retrievable address related data on the blockchain.

  • Version Control: A comprehensive on-chain registry for accounts and modules. It exposes namespace claiming, module registrations, and detailed querying of modules by namespace, name, and version.

  • Account Factory: Allows for the creation of (Interchain) Abstract Accounts, detailed in the section on Interchain Abstract Accounts.

  • Account Console: A web-based developer-oriented interface designed to simplifying managing and interacting with your Accounts. Access it here: console.abstract.money.

  • Module Factory: Facilitates installing Abstract Modules on an Account. You can install modules by interacting with the Account Manager directly, i.e. via CLI/scripts, or by using the Account Console.

Features

Through the interplay of the components above, Abstract offers a number of features that make it a powerful framework for sustainable application development.

  • Monetization: Developers have the ability to monetize their modules by setting installation fee or usage fees for their modules. By providing direct monetization strategies we aim to reduce funding intermediaries and improved the sustainability of small team/solo developer projects.

  • Account Value Oracle: An integrated way to easily get the value of your Account’s assets on-chain.

Version Control

The Version Control contract acts as the registry for all modules and accounts within the Abstract platform. Abstract Accounts can use it to claim namespaces and register their modules. The Version Control contract allows modules to be queried by its namespace, name, and version, returning its reference which may be a code id or address.

Namespaces

An account’s namespace is a unique identifier that is used to provide a publishing domain for modules and a human readable name for any Abstract Account.

Namespaces are claimed by an account and can be used to publish modules. Namespaces are unique and can only be claimed once. An account can only claim one namespace.

When a namespace is removed from an account, any modules published under that namespace will be removed from the registry. This is to prevent malicious actors from registering modules under trusted namespaces.

Propose Modules

Developers that wish to publish modules to the Abstract platform need to call ProposeModules on the Version Control contract. The modules will subsequently be reviewed by the Abstract platform for registration.

Info

For documentation on how to register modules, see Module Deployment

Modules cannot be registered without their namespaces being claimed by an Account. This is to prevent malicious actors from registering modules under trusted namespaces.

Below details the assertion process.

sequenceDiagram
    autonumber
    actor U as Owner

    participant VC as Version Control
    participant Man as Manager of Namespace
    participant M as Adapter Instance

    U ->> VC: ProposeModules

    loop

        VC --> VC: Load Account ID for namespace
        VC --> VC: Load Account Manager address
        VC -->>+ Man: Query Account owner
        Man -->>- VC: Address

        opt adapter
            VC -->> M: Assert no sudo admin
            activate M
            VC -->> M: Assert same cw2 data
            deactivate M
        end

    end
    VC ->> VC: Save modules

Warning

For mainnet deployment proposed modules are reviewed by the Abstract team. To get them approved, reach out to us on Discord. For testnet deployment there is no review process.

Account Factory

The Account Factory is a contract that is used to create and manage Abstract Accounts, which can be interacted with via the contract or the Account Console.

To recap from that chapter, an Abstract Account is composed of a Manager and a Proxy contract. Those contracts will be created for you by the Account Factory using the latest versions of these contracts, which are store on the Version Control contract.

Flow Diagram

When a developer requests the creation of an account, the following internal process is initiated:

sequenceDiagram
    autonumber
    actor U as User
    participant F as Account Factory
    participant VC as Version Control
    participant M as New Manager
    participant P as New Proxy

    U ->> F: CreateAccount
    F -->>+ VC: Query for Manager reference
    VC -->>- F: Manager code_id

F-->>+VC: Query for Proxy reference
VC-->>-F: Proxy code_id
F->F: Compute Instantiate2 Addresses
F-x+M: Instantiate Manager
F-x+P: Instantiate Proxy

F->>VC: Register Account

If you want to see in details how this is accomplished, please refer to our Github repository.

Module Factory

The Module Factory is a contract that allows Account owners to install and manage Abstract Modules for their Account. You can install modules by interacting with the Account Manager directly, i.e. via CLI, or by using the Account Console.

To recap from that chapter, there are three types of modules: App, Adapter, and Standalone.

Flow Diagrams

Install Module

When a developer requests the installation of a module, the following internal process is initiated:

sequenceDiagram
    autonumber
    actor U as Owner
    participant M as Manager
    participant MF as Module Factory
    participant VC as Version Control
    participant P as Proxy

    U ->> M: InstallModule
    M ->> MF: InstallModule
    MF -->>+ VC: Query reference
    alt adapter
        VC -->>+ MF: Return address
    else app / standalone
        VC -->>- MF: Return code_id
        MF -> MF: Instantiate module
    end
    MF ->> M: Register module address

    M ->> P: Update module allowlist
Installation of a module

Execute on Module

Once the module is installed, there are essentially three ways to interact with it depending on the type of module:

Owner Execution

The owner of an Account can always execute on the module directly, even if the module is installed on a sub-account.

sequenceDiagram
    autonumber
    actor U as Owner
    participant Md as Module ("addr123")
    Note right of U: ModuleMsg

    U ->> Md: Execute
Module Execution

Adapter Execution

In the following example, the abstract:dex module is installed on an Account and the user requests a swap on a dex. This swap will use the funds held in the Account to execute the swap on the target dex.

sequenceDiagram
    autonumber
    actor U as Owner
    participant D as abstract:dex
    participant A as ANS
    participant P as Proxy
    participant T as Dex Pool
    Note right of U: Dex::Swap {proxy: "juno1xd..."}
    U ->> D: Call module
    D -->>+ A: Resolve asset names
    A -->> D: Asset infos
    D --> A: Resolve dex pool
    A -->>- D: Pool metadata
    D --> D: Build swap msg for target dex
    D ->> P: Forward execution
    Note over D, A: DexMsg
    P ->> T: Execute
    Note right of P: DexMsg
Adapter Execution

App Execution w/ Dependencies

In this example, we use Equilibrium’s Rebalance permissionless function as an example. Modules with dependencies (equilibrium:balancer is dependent on abstract:etf and abstract:dex) have their addresses dynamically resolved when called.

sequenceDiagram
    autonumber
    actor U as User
    participant B as equilibrium:balancer
    participant P as Proxy
    participant M as Manager
    participant D as abstract:dex
    participant T as Target Dex

    U ->> B: Rebalance
    B -->>+ P: Query Allocations (Oracle)
    P -->>- B: Allocations
    B --> B: Calculate rebalancing requirements

    B -->>+ M: Query abstract:dex address
    M -->>- B: Address

    B ->> D: Call SwapRouter on dex
    D --> D: Build swap msg for target dex
    D --> D: Load proxy address

    D ->> P: Forward execution
    Note over M: DexMsg
    P ->> T: Execute
    Note over D, M: DexMsg
Dependent Execution

Tools and Libraries

At Abstract, we are dedicated to expanding the horizons of blockchain development through our innovative and ever-growing suite of products. Our products aim to simplify and enhance the development process, allowing creators to bring their visions to life with efficiency and security.

Abstract App Template

  • Quick Start: Jumpstart your app development with our robust template.
  • Integration Friendly: Easy to integrate with existing systems.
  • TypeScript Support: Build with confidence using TypeScript.

CW-Orchestrator

  • Scripting Power: Simplify your interactions with CosmWasm contracts.
  • Macros for Efficiency: Generate type-safe interfaces to streamline your workflow.
  • Code Reusability: Use the same logic for testing and deployment.

Abstract JS

  • Seamless Interactions: Engage with the blockchain from your web application effortlessly.
  • Type Declarations: Develop with type safety in mind.
  • Comprehensive: From queries to transactions, we’ve got you covered.

CW-Orchestrator

The cw-orchestrator package is a scripting tool designed to simplify interactions with CosmWasm smart contracts. By providing a set of macros that generate type-safe interfaces for your contracts, it not only enhances the code’s readability and maintainability but also reduces testing and deployment overhead. These interfaces can be seamlessly combined into a single object, fostering easier integration and collaboration.

Furthermore, cw-orchestrator allows for code reusability between testing and deployments, making it our primary tool in enabling Abstract’s infrastructure to be highly available.

Usage

Here’s a snippet that sets up the complete Abstract SDK framework on a cw-multi-test environment, and deploys the Counter App to the App store.

#![allow(unused)]
fn main() {
// Create a sender and instantiate the mock environment
let sender = Addr::unchecked("sender");
let mock = Mock::new(&sender);

// Construct the counter interface (a wrapper around the contract's entry points)
let contract = CounterApp::new(COUNTER_ID, mock.clone());

// Deploy Abstract to the mock
let abstr_deployment = Abstract::deploy_on(mock, sender.to_string())?;

// Create a new account to install the app onto
let account =
    abstr_deployment
        .account_factory
        .create_default_account(GovernanceDetails::Monarchy {
            monarch: sender.to_string(),
        })?;

// Claim the namespace so app can be deployed
abstr_deployment
    .version_control
    .claim_namespace(1, "my-namespace".to_string())?;

// Deploy the app!
contract.deploy(APP_VERSION.parse()?)?;
}

For more details on how to use cw-orchestrator, please refer to the cw-orchestrator Documentation, where you can find a quick start and a detailed guide on how to use the tool with your smart contracts, supported chains and more. Also, check out the cw-orchestrator Github Repo for more details about the tool’s code.

Abstract JS

Abstract.js is a comprehensive JavaScript library designed to facilitate seamless interactions with the on-chain Abstract framework. Whether you’re a developer looking to integrate blockchain functionalities into your application or a blockchain enthusiast aiming to explore the Abstract framework, Abstract.js provides the essential tools to make the process straightforward.

Features

  • Easy Integration 🛠️ : Designed with developers in mind, Abstract.js ensures a hassle-free integration process with existing JavaScript applications.
  • Type Declarations 🔍: For TypeScript enthusiasts, Abstract.js comes with type declarations, ensuring type safety and enhancing the development experience.
  • Comprehensive Methods 🌐: From querying blockchain data to sending transactions, Abstract.js covers a wide range of functionalities required for on-chain operations.
  • React Support ⚛︎️: With the @abstract-money/abstract.js-react package, you can easily integrate and manage the Abstract framework in their React applications.

Installation

To install the main library:

npm i @abstract-money/abstract.js

For React-specific functionalities:

npm i @abstract-money/abstract.js-react

To read more about the available types and methods, please refer to the Abstract.js Documentation.

Abstract App Template

The Abstract App Module Template is a starting point for developing apps that enable features or transform Abstract Accounts into standalone products.

For a deeper understanding of Abstract Accounts, please refer to the abstract accounts documentation. If you need a refresher about apps, consult the app module documentation.

The primary focus of the Abstract App Template is to provide a template for building a new Abstract App, as well as support for generating TypeScript client code for the contract, which can then be imported into a frontend application.

Getting Started

To get started, please go to the Abstract App Template Github Repo and follow the instructions in the README.

In there you can find instructions on how to generate a new Abstract App, how to test it, deploy it, and generate TypeScript client code.

The Abstract App Design Space

The Abstract SDK broadens your design space beyond traditional smart contract application architectures. While applications built with stand-alone smart contracts can also be crafted using the SDK, the Abstract SDK promotes a level of code reusability that goes beyond stand-alone smart contract development. It is through this code reusability that novel applications can be constructed with little effort in a short time.

Design Spaces Explained

Traditional: Hosted Applications

Traditionally applications have been created by composing “stand-alone” smart contracts. With each smart contract designed to fulfill a different role in the application’s logic. We call these applications hosted applications since they’re deployed and controlled by the code maintainers, and to use them, users transfer funds to the application’s smart contract. Dexes, lending markets, yield aggregators are all examples of hosted applications.

flowchart LR
    subgraph Developer Team [fas:fa-users-cog Developer Team]
    %% subgraph Application
        direction BT
        A[Application]
    %% end
    end

    User[fa:fa-users Users] ==> A

Building a Hosted Auto-Compounder

Hosted applications can be built more efficiently with the Abstract SDK because of it’s modular design. As an example, let’s consider an auto-compounder application. The auto-compounder provides liquidity to DEX trading pairs and re-invests the received rewards into the pairs. The application’s logic can be split into three modules:

  • DEX Adapter: Provides an interface to perform DEX operations. (e.g., swap tokens, provide liquidity, etc.)
  • Staking Adapter: Provides an interface to perform staking operations. (e.g., claim rewards, stake, unstake, etc.)
  • Auto-Compounder: Orchestrates the DEX and staking adapters to perform the auto-compounding logic.

If we visualize this application, we can see that the DEX and staking adapters are reusable components that can be used in other applications. The auto-compounder, in this approach, is a unique application that can be installed on an account and used by users to deposit into and withdraw from the auto-compounder application. The account essentially acts as a vault that holds all the users’ funds.

flowchart LR
    subgraph Autocompounder Application
        direction BT
        Autocompounder -.-> Dex
        Autocompounder -.-> Staking
        Staking --> Account
        Autocompounder --> Account
        Dex --> Account
    end

    User[fa:fa-users Users] ==> Autocompounder

This approach offers two significant benefits:

  • Code Reusability: Developers can reuse the DEX and staking adapters in other applications. Furthermore, Abstract already provides a library of adapters for the most popular protocols. This saves you both time and money as you don’t need to write the integrations yourself.
  • Security: The auto-compounder application’s logic is reduced to it’s bare minimum, making it easier to audit and maintain. Furthermore, the DEX and staking adapters are battle-tested smart contracts, which further reduces the attack surface.

Innovative: Self-Hosted Applications

Self-hosted applications, on the other hand, represent a novel concept only achievable with the Abstract SDK. Here, _ users own their applications_ and don’t need to transfer funds to the application’s smart contract. Instead, they deploy the smart contract to their account, which grants the application rights to access those funds. Each application is a new instantiation of a smart contract that is owned and configurable by the user. The user can thus update the application’s code, parameters, and permissions at any time, without relying on the application’s maintainers.

flowchart LR
    subgraph Developers [fas:fa-users-cog Developers]
        direction RL
        A[App]
    end

    subgraph Acc1 [fas:fa-user User's Account]
        direction TB
        Ap1[App] --> A1[Account]
    end

    subgraph Acc2 [fas:fa-user User's Account]
        direction TB
        Ap2[App] --> A2[Account]
    end

    subgraph Acc3 [fas:fa-user User's Account]
        direction TB
        Ap3[App] --> A3[Account]
    end

    Store -.-> Ap1
    Store -.-> Ap2
    Store -.-> Ap3

    A ==> Store[fa:fa-store App Store]

This approach offers two significant benefits:

  • Sovereignty: Users have more control over their funds as they don’t need to trust application maintainers.
  • Customizability: Users can tailor their application, leading to novel customization options unavailable with hosted applications.

Let’s see how this applies to the auto-compounder application from before:

Building a Self-Hosted Auto-Compounder

The auto-compounder application can easily be converted into a self-hosted application. Again, by self-hosted we mean that instead of users moving their funds to an externally owned account, they deploy the auto-compounder application to their own account. The auto-compounder application is now owned by the user and can be configured to their liking.

flowchart BT
    subgraph Alex[Alex's Account]
        direction TB
        A1[Autocompounder] -.-> D1[Dex]
        A1[Autocompounder] -.-> S1[Staking]
        S1[Staking] --> C1[Account]
        A1[Autocompounder] --> C1[Account]
        D1[Dex] --> C1[Account]
    end

    subgraph Sarah[Sarah's Account]
        direction TB
        A2[Autocompounder] -.-> D2[Dex]
        A2[Autocompounder] -.-> S2[Staking]
        S2[Staking] --> C2[Account]
        A2[Autocompounder] --> C2[Account]
        D2[Dex] --> C2[Account]
    end

    AppStore[fa:fa-store App Store] ==> A1
    AppStore[fa:fa-store App Store] ==> A2

With this setup Alex and Sarah can both use the auto-compounder application, but they can configure it to their liking. For example, Alex can configure the auto-compounder to compound his rewards every 24 hours, while Sarah can configure the auto-compounder to compound her rewards every 12 hours. This approach allows for a very customizable and personalized experience.

Abstract SDK - How to get started

SDK Background

Welcome to the builder section of the Abstract documentation. The following sections will walk you through the process of setting up your development environment, creating an App Module and deploying it to our on-chain registry so that it can be used by others.

Tools used in this guide

Here are the most important tools you will need to know about to get started with the Abstract SDK:

  1. A minimal understanding of Rust is expected. If you are new to Rust, you can find a great introduction to the language in the The Rust Book.

  2. The Abstract SDK is built using the CosmWasm smart-contract framework. If you are new to CosmWasm, you can find a great introduction to the framework in the CosmWasm Book.

  3. Abstract also makes extensive use of cw-orchestrator, our CosmWasm scripting library. You can read its documentation here.

  • Rust Analyzer: Rust Analyzer is a language server that provides IDE support for Rust. If you use VS-Code it’s highly recommended.
  • Intellij Rust Plugin: open-source Rust plugin compatible with all IntelliJ-based IDEs. You are going to need it if you are using the Intellij IDEA Community Edition IDE, however it’s not needed for the Rust Rover.
  • Just: Just is a command runner that we use to improve the development flow. You can install it by following the instructions on the Github repository.

Setting up the environment

Before you get started with the Abstract SDK, you will need to set up your development environment. This guide will walk you through the process of doing just that.

Info

Experienced with CosmWasm? Skip to the Using The Template section.

Rust

To work with the SDK you will need a Rust toolchain installed on your machine. If you don’t have it installed, you can find installation instructions on the official Rust website.

WASM

Additionally, you will need the WASM compile target installed to build WASM binaries. You will need rustup, which you got when installing Rust on the previous step. To install it the WASM compile target, run:

$ rustup target add wasm32-unknown-unknown
> installing wasm32-unknown-unknown

Docker

Docker is used to create a containerized environment for facilitating reproducible builds. Specifically we’ll be using a slightly modified builder image available here. You can read about the slight modifications we made in this PR.

Git

You will also need git installed to clone our template repository. You can find instructions for installing git on your operative system here.

Using the Template

Now we’ll get you set up with the Abstract App template which contains:

  • A scaffold app module with:
    • A basic contract
    • cw-orchestrator interface and deployment script
    • Integration tests
  • A set of just commands that will help you in your development.

Go to our App Template on Github and click on the “Use this template” button to create a new repository based on the template. You can name the repository whatever you want, but we recommend using the name of your module.

Success

To quickly get started, run ./template_setup.sh and install the recommended tools.

Go ahead and read through the readme of the template repository to learn how it is structured. It contains instructions on how to set up your development environment, useful commands you can perform using just, how to test and deploy your app, and more.

Contract file structure

The template contains a scaffold contract that you can use as a starting point for your own contract. The contract is located in the src directory and is structured as follows:

  • contract.rs: Top-level file for your module. It contains the type definition of you module and the const builder that constructs your contract. It also contains a macro that exports your contract’s entry points. You can also specify the contract’s dependencies here.
  • error.rs: Error types that your contract can return.
  • msg.rs: Custom message types that your contract can receive. These messages also have cw-orchestrator macros attached to them which comes in useful when you are writing your integration tests.
  • state.rs: State types that your contract will use to store state to the blockchain.
  • interface.rs: Interface that your contract will use to interact with the cw-orchestrator library.
  • replies/: Reply handlers that your contract will use to handle replies.
  • handlers/: Message handlers that your contract will use to handle the different messages it can receive.

If there’s anything you don’t understand about the template please don’t hesitate to reach out to us on our Discord server.

Tools used in the template

The following Rust tools are used extensively in our template to improve your productivity.

  • Taplo: The CI shipped with the template will perform formatting checks. To ensure you pass the checks, you can install Taplo and use the just format command to format your code and toml files.
  • Nextest: A better cargo test runner.
  • Cargo Limit: Prioritizes errors over warnings in compile output as well as some other small improvements.
  • Cargo Watch: Allows you to automatically re-run compilation when files change. This is useful when you are working on the contracts and want to fix compiler errors one by one.

You can install them by running just install-tools. All the tools are built from the source by Cargo.

Module Builder

Abstract provides multiple module bases, as detailed in our section on modules. These bases (App and Adapter) implement some basic functionality and store some abstract-related state that will enable you to easily interact with our infrastructure through our SDK (which we’ll introduce later).

For now just know that we provide you with a builder pattern that allows you to easily add custom logic to these module bases. In the rest of this section we’ll outline how you can use this builder pattern to add custom functionality to your contract.

Overview

The builder pattern employed in building an Abstract module is a slight variation of the actual “builder” design pattern. Instead of creating a new builder at runtime, our module builder lets you set custom attributes on your module at compile time, meaning you end up with a const value can be heavily optimized by the compiler. This system ensures that the overhead of using Abstract has little effect on both the code’s runtime and WASM binary size.

Info

The code-snippets in this example can be found in the app template.

In this tutorial we will be working on an App module.

App Type

Your custom AppType will be a type alias for a specific type that fills in the base AppContract type provided by the abstract-app crate. By constructing this type you’re defining which messages you expect to receive at the custom endpoints of your contract.

Here’s what this looks like in the template:

// src/contract.rs
pub type App = AppContract<AppError, AppInstantiateMsg, AppExecuteMsg, AppQueryMsg, AppMigrateMsg>;

The type above contains all the mandatory types (Error, Instantiate, Execute, Query). An optional MigrateMsg type is also added to allow you to customize the migration logic of your contract.

This new App type alias will be used in a few more places throughout the contract, so it’s a good idea to define it at the top of the file.

Module ID

The Module identifier (Module ID) is a string that will identify your application. We covered it in detail in the section on modules, here.

You define your ID as a &'static str like so:

pub const APP_ID: &str = "my-namespace:app";

Module Version

This is the version of your module. The version will be stored on-chain. When installing a module that depends on your module, our infrastructure will assert its version requirements. Ensuring that the contracts that depend on each other are version compatible. We’ll cover dependencies in more detail in the dependencies section.

pub const APP_VERSION: &str = env!("CARGO_PKG_VERSION");

By default you should use the version of your package as your app version. That is what the env! macro is doing in the example above. Alternatively you can provide any 3-digit version number as a valid version.

Build The App

Now that you have defined your type and all your attributes you can begin using the builder. To initiate this, first create the builder for the App:

// src/contract.rs
const APP: App = App::new(APP_ID, APP_VERSION, None)

The builder constructor takes three variables:

  1. module_id: The module ID is a string that we defined above.
  2. contract_version: The contract version.
  3. metadata: An optional URL that can be used to retrieve data off-chain. Can be used with the Abstract Metadata Standard to automatically generate interactive front-end components for the module. This is explained in more detail in the metadata section.

Amazing! You now have a very basic Abstract module. You can now add your custom logic to your module by adding handlers to the module.

Below we’ve defined a complete App module with a few custom handlers set:

const APP: App = App::new(APP_ID, APP_VERSION, None)
    .with_instantiate(handlers::instantiate_handler)
    .with_execute(handlers::execute_handler)
    .with_query(handlers::query_handler)
    .with_migrate(handlers::migrate_handler)
    .with_replies(&[(INSTANTIATE_REPLY_ID, replies::instantiate_reply)]);

Handlers

The handler functions are defined in the src/handlers dir.

The app can then be customized by adding handler functions for your endpoints. These functions are executed whenever a specific endpoint is called on the module.

Writing a handler function

These handlers are where you will write your custom logic for your App. For example, below we’ve defined a custom execute handler that handles all the different AppExecuteMsg variants of our module.

A special feature of these functions is that we insert the instance of your module into the function’s attributes. This enables you to access the module struct in your code. You will learn why this is such a powerful feature in the next section on the Abstract SDK.

// src/handlers/execute.rs
pub fn execute_handler(
    deps: DepsMut,
    _env: Env,
    info: MessageInfo,
    app: App,
    msg: AppExecuteMsg,
) -> AppResult {
    match msg {
        AppExecuteMsg::Increment {} => increment(deps, app),
        AppExecuteMsg::Reset { count } => reset(deps, info, count, app),
        AppExecuteMsg::UpdateConfig {} => update_config(deps, info, app),
    }
}

The code above should look very familiar. It’s only a slight variation of the code you would write in a regular CosmWasm contract. The only difference is that you have access to the app: App attribute, which is the instance of your module.

Info

You can find more application code to read in our 💥 Awesome Abstract repository 💥.

Summary

The Abstract SDK allows you to easily make new custom smart contracts through a simple builder pattern and straight forward type system usage.

In the next section we’ll cover how you can use the module object that we make available in the function handlers to write highly functional smart contract code.

Ever wanted to swap on any cosmos DEX with only one line of code? Look no further!

Appendix

This appendix contains all the available handlers, what type of handler Fn they expect and the format of the messages that are exposed on the contract endpoints.

An overview of the available handlers:

  • with_execute: Called when the App’s ExecuteMsg is called on the instantiate entry point.
  • with_instantiate: Called when the App’s InstantiateMsg is called on the instantiate entry point.
  • with_query: Called when the App’s QueryMsg::Module is called on the query entry point.
  • with_migrate: Called when the App’s MigrateMsg is called on the migrate entry point.
  • with_replies: Called when the App’s reply entry point is called. Matches the function’s associated reply-id.
  • with_sudo: Called when the App’s SudoMsg is called on the sudo entry point.
  • with_receive: Called when the App’s ExecuteMsg::Receive variant is called on the execute entry point.
  • with_ibc_callbacks: Called when the App’s ExecuteMsg::IbcCallback is called on the execute entry point. Matches the callback’s callback ID to its associated function.

In the case of adapters, the handlers are the same, except for with_migrate and with_sudo that are missing for reasons we explain in the adapter section.

For a full overview of the list of handlers available, please refer to the respective module type documentation:

Below, we examine each handler in greater detail. The base fields and variants mentioned in the messages below are defined by the base module type that you chose to use, an App in this case.

Instantiate

The instantiate entry point is a mutable entry point of the contract that can only be called on contract instantiation. Instantiation of a contract is essentially the association of a public address to a contract’s state.

Function Signature

Expected function signature for the custom instantiate handler:

/// Function signature for an instantiate handler.
pub type InstantiateHandlerFn<Module, CustomInitMsg, Error> =
    fn(DepsMut, Env, MessageInfo, Module, CustomInitMsg) -> Result<Response, Error>;

Message

In order to instantiate an Abstract Module, you need to provide an InstantiateMsg with the following structure:

#[cosmwasm_schema::cw_serde]
pub struct InstantiateMsg<BaseMsg, CustomInitMsg = Empty> {
    /// base instantiate information
    pub base: BaseMsg,
    /// custom instantiate msg
    pub module: CustomInitMsg,
}

When the module’s instantiate function is called the struct’s module field is passed to your custom instantiation handler for you to perform any custom logic.

Execute

The execute entry point is a mutable entry point of the contract. Logic in this function can update the contract’s state and trigger state changes in other contracts by calling them. It is where the majority of your contract’s logic will reside.

Function Signature

Expected function signature for the custom execute handler:

/// Function signature for an execute handler.
pub type ExecuteHandlerFn<Module, CustomExecMsg, Error> =
    fn(DepsMut, Env, MessageInfo, Module, CustomExecMsg) -> Result<Response, Error>;

Message

Called when the App’s ExecuteMsg::Module variant is called on the execute entry point.

/// Wrapper around all possible messages that can be sent to the module.
#[cosmwasm_schema::cw_serde]
pub enum ExecuteMsg<BaseMsg, CustomExecMsg, ReceiveMsg = Empty> {
    /// A configuration message, defined by the base.
    Base(BaseMsg),
    /// An app request defined by a base consumer.
    Module(CustomExecMsg),
    /// IbcReceive to process IBC callbacks
    /// In order to trust this, the apps and adapters verify this comes from the ibc-client contract.
    IbcCallback(IbcResponseMsg),
    /// Receive endpoint for CW20 / external service integrations
    Receive(ReceiveMsg),
}

The content of the Module variant is passed to your custom execute handler.

Query

The query entry point is the non-mutable entry point of the contract. Like its name implies it it used to retrieve data from the contract’s state. This state retrieval can have a computation component but it can not alter the contract’s or any other state.

Function Signature

Expected function signature for the custom query handler:

/// Function signature for a query handler.
pub type QueryHandlerFn<Module, CustomQueryMsg, Error> =
    fn(Deps, Env, &Module, CustomQueryMsg) -> Result<Binary, Error>;

Message

Called when the App’s QueryMsg::Module variant is called on the query entry point.

#[cosmwasm_schema::cw_serde]
#[derive(QueryResponses)]
#[query_responses(nested)]
pub enum QueryMsg<BaseMsg, CustomQueryMsg = Empty> {
    /// A query to the base.
    Base(BaseMsg),
    /// Custom query
    Module(CustomQueryMsg),
}

The content of the Module variant is passed to your custom query handler.

Migrate

The migrate entry point is a mutable entry point that is called after a code_id change is applied to the contract. A migration in CosmWasm essentially swaps out the code that’s executed at the contract’s address while keeping the state as-is. The implementation of this function is often used to change the format of the contract’s state by loading the data as the original format and overwriting it with a new format, in case it changed. All adapter base implementations already perform version assertions that make it impossible to migrate to a contract with a different ID or with a version that is lesser or equal to the old version.

Function Signature

Expected function signature for the custom migrate handler:

/// Function signature for a migrate handler.
pub type MigrateHandlerFn<Module, CustomMigrateMsg, Error> =
    fn(DepsMut, Env, Module, CustomMigrateMsg) -> Result<Response, Error>;

Message

Called when the App’s migrate entry point is called. Uses the struct’s module field to customize the migration. Only this field is passed to the handler function.

#[cosmwasm_schema::cw_serde]
pub struct MigrateMsg<BaseMsg = Empty, CustomMigrateMsg = Empty> {
    /// base migrate information
    pub base: BaseMsg,
    /// custom migrate msg
    pub module: CustomMigrateMsg,
}

Reply

The reply entry point is a mutable entry point that is optionally called after a previous mutable action. It is often used by factory contracts to retrieve the contract of a newly instantiated contract. It essentially provides the ability perform callbacks on actions. A reply can be requested using CosmWasm’s SubMsg type and requires a unique ReplyId which is a u64. The customizable handler takes an array of (ReplyId, ReplyFn) tuples and matches any incoming reply on the correct ReplyId for you.

Function Signature

Expected function signature for the custom reply handler:

/// Function signature for a reply handler.
pub type ReplyHandlerFn<Module, Error> = fn(DepsMut, Env, Module, Reply) -> Result<Response, Error>;

Message

There is no customizable message associated with this entry point.

Sudo

The sudo entry point is a mutable entry point that can only be called by the chain’s governance module. I.e. any calls made to this contract should have been required to have gone through the chain’s governance process. This can vary from chain to chain.

Function Signature

Expected function signature for the custom sudo handler:

/// Function signature for a sudo handler.
pub type SudoHandlerFn<Module, CustomSudoMsg, Error> =
    fn(DepsMut, Env, Module, CustomSudoMsg) -> Result<Response, Error>;

Message

There is no base message for this entry point. Your message will be the message that the endpoint accepts.

Receive

The receive handler is a mutable entry point of the contract. It is similar to the execute handler but is specifically geared towards handling messages that expect a Receive variant in the ExecuteMsg. Examples of this include but are not limited to:

  • Cw20 send messages
  • Nois Network random number feed

Function Signature

Expected function signature for the custom receive handler:

/// Function signature for a receive handler.
pub type ReceiveHandlerFn<Module, ReceiveMsg, Error> =
    fn(DepsMut, Env, MessageInfo, Module, ReceiveMsg) -> Result<Response, Error>;

Message

Called when the App’s ExecuteMsg::Receive variant is called on the execute entry point.

/// Wrapper around all possible messages that can be sent to the module.
#[cosmwasm_schema::cw_serde]
pub enum ExecuteMsg<BaseMsg, CustomExecMsg, ReceiveMsg = Empty> {
    /// A configuration message, defined by the base.
    Base(BaseMsg),
    /// An app request defined by a base consumer.
    Module(CustomExecMsg),
    /// IbcReceive to process IBC callbacks
    /// In order to trust this, the apps and adapters verify this comes from the ibc-client contract.
    IbcCallback(IbcResponseMsg),
    /// Receive endpoint for CW20 / external service integrations
    Receive(ReceiveMsg),
}

Ibc Callback

The ibc callback handler is a mutable entry point of the contract. It is similar to the execute handler but is specifically geared towards handling callbacks from IBC actions. Since interacting with IBC is an asynchronous process we aim to provide you with the means to easily work with IBC. Our SDK helps you send IBC messages while this handler helps you execute logic whenever the IBC action succeeds or fails. Our framework does this by optionally allowing you to add callback information to any IBC action. A callback requires a unique CallbackId which is a String. The callback handler takes an array of (CallbackId, IbcCallbackFn) tuples and matches any incoming callback on the correct CallbackId for you. Every call to this handler is verified by asserting that the caller is the framework’s IBC-Client contract.

Function Signature

/// Function signature for an IBC callback handler.
pub type IbcCallbackHandlerFn<Module, Error> = fn(
    DepsMut,
    Env,
    MessageInfo,
    Module,
    CallbackId,
    CallbackMessage,
    Callback,
) -> Result<Response, Error>;

Message

Called when the App’s ExecuteMsg::IbcCallback variant is called on the execute entry point. The receiving type is not customizable but contains the IBC action acknowledgment.

/// Wrapper around all possible messages that can be sent to the module.
#[cosmwasm_schema::cw_serde]
pub enum ExecuteMsg<BaseMsg, CustomExecMsg, ReceiveMsg = Empty> {
    /// A configuration message, defined by the base.
    Base(BaseMsg),
    /// An app request defined by a base consumer.
    Module(CustomExecMsg),
    /// IbcReceive to process IBC callbacks
    /// In order to trust this, the apps and adapters verify this comes from the ibc-client contract.
    IbcCallback(IbcResponseMsg),
    /// Receive endpoint for CW20 / external service integrations
    Receive(ReceiveMsg),
}

Dependencies

There is another method accessible on the module builder, which is the with_dependencies function. As it states it allows you to specify any smart contract dependencies that your module might require. This is a key requirement for building truly composable and secure applications. We’ll cover dependencies further the dependencies section.

SDK

Now that that you’re familiar with construction of your module you’re ready for our hot sauce. While you can traditional code in your module, using our SDK will give you a huge productivity boost. In short, we’ve created an account abstraction programming toolbox that allows you to easily control an Abstract Account’s interactions, as well as create your own APIs that can be used by other developers to interact with your unique application. Composability galore!

APIs

Abstract API objects are Rust structs that expose some smart contract functionality. Such an API object can only be constructed if a contract implements the traits that are required for that API. Access to an API is automatically provided if the trait constraints for the API are met by the contract.

We’ve created a set of APIs that can be used to interact with the Abstract Account and have implemented their trait requirements on the module base types that we provide (App and Adapter). So for you, it’s just plug and play! 🎉

Most of the APIs either return a CosmosMsg or an AccountAction.

CosmosMsg Example

The CosmosMsg is a message that should be added as-is to the Response to perform some action.

This example sends coins from the local contract (module) to the account that the application is installed on.

            // Get bank API struct from the app
            let bank: Bank<'_, MockModule> = app.bank(deps.as_ref());
            // Define coins to send
            let coins: Vec<Coin> = coins(100u128, "denom");
            // Construct messages for deposit (transfer from this contract to the account)
            let deposit_msgs: Vec<CosmosMsg> = bank.deposit(coins.clone()).unwrap();
            // Create response and add deposit msgs
            let response: Response = app.response("deposit").add_messages(deposit_msgs);

            Ok(response)

source

Custom CosmosMsgs can be added in the same way through the app.response("<action>") function. The action attribute of the function is a string that will be added to the response’s attributes and will be available in the transaction result under the wasm-abstract event. This way you can easily figure out which actions were called in a tx!

The above example can equally be written as:

#![allow(unused)]
fn main() {
let coins: Vec<Coin> = coins(100u128, "denom");
// Create CosmosMsg
let bank_msg: CosmosMsg = CosmosMsg::Bank(BankMsg::Send {
    to_address: "<proxy_address>".to_string(),
    amount: coins,
});
// Add to Response
let response: Response = app.response("deposit").add_message(deposit_msg);

Ok(response)
}

This gives you all the flexibility you are used to when working with CosmWasm!

AccountAction Example

The other kind of struct that can be returned by an Abstract API is the AccountAction. An AccountAction is a single, or collection of CosmosMsgs that should be executed on the App’s Abstract Account.

AccountActions can be executed with the Executor API. The returned CosmosMsg should be added to the action’s Response.

The following example sends coins from the account to another address. This action requires the account itself to execute the message and transfer the funds.

            let recipient: Addr = Addr::unchecked("recipient");
            let bank: Bank<'_, MockModule> = app.bank(deps.as_ref());
            let coins: Vec<Coin> = coins(100u128, "asset");
            let bank_transfer: AccountAction = bank.transfer(coins.clone(), &recipient).unwrap();

            let executor: Executor<'_, MockModule> = app.executor(deps.as_ref());
            let account_message: ExecutorMsg = executor.execute(vec![bank_transfer]).unwrap();
            let response: Response = Response::new().add_message(account_message);

source

So through the Executor API you can execute messages on behalf of the Account! Also notice that you can provide multiple actions to the executor to be executed in sequence.

How it works

As you’re aware, abstract-sdk crate is a toolbox for developers to create composable smart contract APIs. It does this through a combination of supertraits and blanket implementations, two concepts that are native to the Rust language.

Info

Supertraits are Rust traits that have one or multiple trait bounds while a blanket implementation is a Rust trait implementation that is automatically implemented for every object that meets that trait’s trait bounds. The Abstract SDK uses both to achieve its modular design.

For more information about traits, supertraits and blanket implementations, check out the Rust documentation:

Features

Features are the lowest-level traits that are contained within the SDK and they don’t have any (custom) trait bounds. They generally act as data accessor traits. I.e. if a struct implements a feature it means that it has some way to get the information required by that feature.

Here’s an example of such a feature:

#![allow(unused)]
fn main() {
/// Accessor to the Abstract Name Service.
pub trait AbstractNameService: Sized {
    /// Get the ANS host address.
    fn ans_host(&self, deps: Deps) -> AbstractSdkResult<AnsHost>;

    /// Construct the name service client.
    fn name_service<'a>(&'a self, deps: Deps<'a>) -> AbstractNameServiceClient<Self> {
        AbstractNameServiceClient {
            _base: self,
            deps,
            host: self.ans_host(deps).unwrap(),
        }
    }
}
}

Any structure that implements this trait has access to the AnsHost struct, which is a wrapper around an Addr. Because that structure now has the address of that contract, it can resolve ANS entries.

Now instead of letting you implement these traits yourself, we’ve already gone ahead and implemented them for the App and Adapter structs.

So when you’re building your application, the module struct already has the features and data required to do abstract operations (😉). With this in place we can start creating more advanced functionality.

Info

Other structs that implement a feature without being module bases are called Feature Objects.

Usage

Add abstract-sdk to your Cargo.toml by running:

cargo add abstract-sdk

Then import the prelude in your contract. This will ensure that you have access to all the traits which should help your IDE with auto-completion.

use abstract_sdk::prelude::*;

Creating your own API

The Bank API allows developers to transfer assets from and to the Account. We now want to use this API to create a Splitter API that splits the transfer of some amount of funds between a set of receivers.

// Trait to retrieve the Splitter object
// Depends on the ability to transfer funds
pub trait SplitterInterface: TransferInterface + ModuleIdentification {
    fn splitter<'a>(&'a self, deps: Deps<'a>) -> Splitter<Self> {
        Splitter { base: self, deps }
    }
}

// Implement for every object that can transfer funds
impl<T> SplitterInterface for T where T: TransferInterface + ModuleIdentification {}

impl<'a, T: SplitterInterface> AbstractApi<T> for Splitter<'a, T> {
    fn base(&self) -> &T {
        self.base
    }
    fn deps(&self) -> Deps {
        self.deps
    }
}

impl<'a, T: SplitterInterface> ApiIdentification for Splitter<'a, T> {
    fn api_id() -> String {
        "Splitter".to_owned()
    }
}

#[derive(Clone)]
pub struct Splitter<'a, T: SplitterInterface> {
    base: &'a T,
    deps: Deps<'a>,
}

impl<'a, T: SplitterInterface> Splitter<'a, T> {
    /// Split an asset to multiple users
    pub fn split(&self, asset: AnsAsset, receivers: &[Addr]) -> AbstractSdkResult<AccountAction> {
        // split the asset between all receivers
        let receives_each = AnsAsset {
            amount: asset
                .amount
                .multiply_ratio(Uint128::one(), Uint128::from(receivers.len() as u128)),
            ..asset
        };

        // Retrieve the bank API
        let bank = self.base.bank(self.deps);
        receivers
            .iter()
            .map(|receiver| {
                // Construct the transfer message
                bank.transfer(vec![&receives_each], receiver)
            })
            .try_fold(AccountAction::new(), |mut acc, v| match v {
                Ok(action) => {
                    // Merge two AccountAction objects
                    acc.merge(action);
                    Ok(acc)
                }
                Err(e) => Err(e),
            })
    }
}

source

These APIs can then be used by any contract that implements its required traits, in this case the TransferInterface.

        let asset = AnsAsset {
            amount: Uint128::from(100u128),
            name: "usd".into(),
        };

        let receivers = vec![
            Addr::unchecked("receiver1"),
            Addr::unchecked("receiver2"),
            Addr::unchecked("receiver3"),
        ];

        let split_funds = module.splitter(deps.as_ref()).split(asset, &receivers)?;
        assert_eq!(split_funds.messages().len(), 3);

        let msg: ExecutorMsg = module.executor(deps.as_ref()).execute(vec![split_funds])?;

        Ok(Response::new().add_message(msg))

Appendix

Available API Objects

The following API objects are available in the Abstract SDK:

Other projects have also started building APIs. Here are some examples:

Testing Your Module

Testing your smart contracts is a crucial step in its development. Without proper testing you risk compromising the accounts of your users and with it the funds that they hold. For that reason we expect modules to be thoroughly tested before they are allowed on our platform.

This section of the documentation outlines the different testing methods. Each method is accompanied by an Abstract helper. These helpers assist you in setting up your testing environment.

Unit-testing

The lowest level of testing is unit testing. Unit tests allow you to easily test complex, self-contained logic. Because unit tests should be self-contained, any queries made to other contracts need to be mocked. These mocks act as “query catchers”, allowing you to specify a response for a specific query.

Sadly constructing these mock queries is time-consuming and involves a lot of boilerplate. Additionally, there are queries that your module should always support as they are part of its base implementation. For those reasons we created an abstract-testing package.

The abstract-testing provides you with some small abstractions that allow you to mock Smart and Raw queries with ease.

Info

What’s the difference between a Smart and a Raw query?

  • Smart Queries: A smart query is a query that contains a message in its request. It commonly involves computation on the queried contract. After this optional computation and state loading, the contract responds with a ResponseMsg. Mocking this type of query involves matching the serialized query request message (Binary) to a specific message type and returning a serialized response. Any expected computation needs to be mocked as well.

  • Raw Queries: A raw query is a simple database key-value lookup. To mock this type of query you need to provide a mapping of the raw key to a raw value. The returned value then needs to be interpreted correctly according to the store’s type definitions.

Mock Querier

The abstract-testing package contains a MockQuerierBuilder. It uses the common builder pattern to allow for efficient mock construction. Let’s see how!

Mocking Smart Queries

Mocking a smart-query with the MockQuerierBuilder is easy! You do it by calling the with_smart_handler function.

Example
#![allow(unused)]
fn main() {
            let querier = MockQuerierBuilder::default()
                .with_smart_handler("contract_address", |msg| {
                    // handle the message
                    let MockModuleQueryMsg {} = from_json::<MockModuleQueryMsg>(msg).unwrap();
                    to_json_binary(&MockModuleQueryResponse {}).map_err(|e| e.to_string())
                })
                .build();
}

Mocking Raw Queries

Instead of manually mapping the key-value relation and it’s types, we can use the available contract storage types. Using the storage types ensures that the mock and its data operations are the same as in the actual implementation. It also saves us a lot of work related to key serialization.

This approach allow you to easily map Item and Map datastores.

Warning

Multi-index maps are currently not supported. PRs on this issue are welcome! 🤗

Example
#![allow(unused)]
fn main() {
            let querier = MockQuerierBuilder::default()
                .with_raw_handler("contract_address", |key: &str| {
                    // Example: Let's say, in the raw storage, the key "the_key" maps to the value "the_value"
                    match key {
                        "the_key" => to_json_binary("the_value").map_err(|e| e.to_string()),
                        _ => to_json_binary("").map_err(|e| e.to_string()),
                    }
                })
                .build();
}

Items and Maps

The MockQuerierBuilder also provides a with_items and with_maps function. These functions allow you to easily mock Item and Map datastores.

Abstract Querier

The easiest and best way to start using the querier is to use the AbstractMockQuerierBuilder::mocked_account_querier_builder() method. This method sets up a mock querier with an initial Abstract Account.

Integration Testing

Integration testing your contract with Abstract involves deploying your contract and any of its dependencies to a mock environment where Abstract is deployed. To make this as easy as possible we’ve created a abstract-client package that you can use to deploy Abstract and any of your modules to a mock environment. We will cover this client in the next section.

But first we need to cover some basics.

Cw-orchestrator Mock environment

Most of our Abstract tests use cw-orchestrator’s Mock struct that is backed by a cw-multi-test::App which you might be familiar with.

The Mock struct provides a simulation of the CosmWasm environment, enabling testing of contract functionalities.

Info

cw-orchestrator is a CosmWasm scripting tool that we developed to improve the speed at which we can test and deploy our applications. We recommend reading the cw-orchestrator documentation if you are not yet familiar with it.

Local Daemon Testing

Once you have confirmed that your module works as expected you can spin up a local node and deploy Abstract + your app onto the chain. You can do this by running the local_daemon example, which uses a locally running juno daemon to deploy to. At this point you can also test your front-end with the contracts.

Info

Testing your application on a local daemon is difficult if it depends on other protocols, and those protocols don’t make use of cw-orchestrator as there is no easy way to deploy them to the local daemon.

Abstract Client

As previously mentioned you can use our abstract-client package to interact with any instance of Abstract. For this example we’ll use the Mock environment for simplicity. However, the same functions can be used for any CwEnv.

You can read the abstract-client documentation for more information.

Example

#![allow(unused)]
fn main() {
    // Create environment
    let env: MockBech32 = MockBech32::new("mock");
    let sender: Addr = env.sender();

    // Build the client
    let client: AbstractClient<MockBech32> = AbstractClient::builder(env).build()?;
}

These three lines:

  • Created a mock environment to deploy to.
  • Deployed Abstract to that environment and returned a client.

You can then start using the client to do all sorts of things. For example, you can set and query balances easily.

#![allow(unused)]
fn main() {
    let coins = &[Coin::new(50, "eth"), Coin::new(20, "btc")];

    // Set a balance
    client.set_balance(&sender, coins)?;

    // Add to an address's balance
    client.add_balance(&sender, &[Coin::new(50, "eth")])?;

    // Query an address's balance
    let coin1_balance = client.query_balance(&sender, "eth")?;

    assert_eq!(coin1_balance.u128(), 100);
}

Then, you can use the client to create a Publisher to publish an App to the platform.

#![allow(unused)]
fn main() {
    // Create a publisher
    let publisher: Publisher<MockBech32> = client
        .publisher_builder(Namespace::from_id(TEST_MODULE_ID)?)
        .build()?;

    // Publish an app
    publisher.publish_app::<MockAppI<MockBech32>>()?;
}

Now that the App is published anyone can create an Account and install it!

#![allow(unused)]
fn main() {
    let account: Account<MockBech32> = client.account_builder().build()?;

    // Install an app
    let app: Application<MockBech32, MockAppI<MockBech32>> =
        account.install_app::<MockAppI<MockBech32>>(&MockInitMsg {}, &[])?;
}

Et voila! You’ve just deployed Abstract and an App to a mock environment. You can now start testing your module.

The Account object also has some useful helper methods:

#![allow(unused)]
fn main() {
    // Get account info
    let account_info: AccountInfo = account.info()?;
    // Get the owner
    let owner: Addr = account.owner()?;
    // Add or set balance
    account.add_balance(&[Coin::new(100, "btc")])?;
    // ...
}

You can explore more of its functions in the type’s documentation.

Your App Interface

The Application<_, MockAppI<_>> object returned from the install_app function is a wrapper around an Account that has an App installed on it (in this case MockAppI).

The MockAppI is a cw-orchestrator interface that exposes the contract’s functions as methods. This allows you to easily interact with your module directly or as a different address.

#![allow(unused)]
fn main() {
    // Install an app
    let app: Application<MockBech32, MockAppI<MockBech32>> =
        account.install_app::<MockAppI<MockBech32>>(&MockInitMsg {}, &[])?;
    // Call a function on the app
    app.do_something()?;

    // Call as someone else
    let manager: Addr = account.manager()?;
    app.call_as(&manager).do_something()?;

    // Query the app
    let something: MockQueryResponse = app.get_something()?;
}

Module Deployment

Deploying your module is an easy 3-step process: Module Uploading, Registration and Schema Linking. Let’s go over each step in detail.

This doc assumes you’re using the module app template, if you’re not we recommend looking at the relevant files in the template to set up your own deployment process.

Module Uploading

Uploading your module involves first compiling your module as a WASM binary and then uploading it to the network(s) you want your module to be available on. This will yield you a code_id that is a unique identifier for your module on the network.

Compiling your module

Once you have confirmed that your module works as expected you can spin up a local node and deploy Abstract + your app onto the chain. You need Docker installed for this step.

You can compile your module by running the following command:

$ just wasm
> Compiling to WASM...

The WASM optimizer uses a docker container to compile your module. If you don’t have docker installed you can install it from here.

This should result in an artifacts directory being created in your project root. Inside you will find a my_module.wasm file that is your module’s binary.

Publish your module

Before attempting to publish your app you need to add your mnemonic to the .env file. Don’t use a mnemonic that has mainnet funds for this. Make sure this account has funds. If you don’t have the deployment will fail. Get funds from respective chain faucets or ask for some test tokens on Abstract Discord.

Now you can go ahead and publish the module to the network(s) you want to make it available on. You can do this by running the following command:

$ just publish uni-6
> Deploying module...

This will use the module’s examples/publish.rs script to deploy the module to the uni-1 network. The resulting code-id of your contract should now be in the state.json file created for you. The script will also attempt to register the module on the Abstract Version Control, hence the mnemonic used in the script should be the same as the one you used to create the account and register the namespace.

JSON Schema Linking

To improve the user-experience for developers using your module we recommend linking your module’s JSON schema to the Abstract Version Control. This will allow developers (and you) to use the Abstract web app to interact with your module.

Warning

You need to install github cli for this step.

Follow these install instructions as per your operating system needs.

To link your module’s schema you can run the following command:

$ just publish-schemas <namespace> <name> <version>
> Publishing schemas...

Where you fill the <namespace>, <name> and <version> with the same values you used to register your module on the Abstract Version Control.

Module Installation

To install your module, go to the Abstract Account Dashboard, enter the dev-mode by clicking Enter Dev Mode on Action tab, go to your Account (or a new one) and click on the Modules tab. Here you will find a list of all the modules you have registered on the Abstract Version Control. Click on the Install button next to your module and select the network you want to install it on. This will open a modal with the following fields:

Dependencies

A dependency is a piece of software or library that a project needs in order to function properly. For example, if a software application is built using a particular framework or library, that framework or library is considered a dependency of the application. Dependency in code can be managed by the package manager. For example, in rust, we use Cargo.toml at the root of the project. In case of workspaces, dependencies are managed by parent project. Learn more about dependencies in rust before proceeding.

Your module might depend on some other module being enabled on the Account. Abstract allows you to address that module and perform actions on it through a dependency system. These dependencies are checked on-chain when you upgrade your modules.

Module Dependencies

In the Abstract SDK, modules have conditions that must be met before they can be installed. These conditions largely revolve around module dependencies and version requirements. When installing a module, the system will check its dependencies and ensure that they are installed and meet the version requirements specified by the module.

Here’s how the process of installing a module and checking module dependencies looks:

sequenceDiagram
    autonumber
    actor U as Owner
    participant M as Manager
    participant F as Module Factory
    participant Mo as Module
    participant P as Proxy

    U ->> M: Install Module
    M -->> F: Install Module
    opt App instantiate 
    F -->> Mo: Instantiate Module
    end
    M -->> Mo: Query Module Dependencies
    M -->> M: Assert Dependency Requirements
    M -->>+ M: Add Module as Dependent on its Dependencies
    M -->>+ P: Allowlist Module

Declaring Dependencies

To declare a dependency, we recommend creating a dependencies.rs file in your contract src directory. Say, for instance, your module depended on the DEX API with a version constraint of >=0.3.0. Your dependencies would look as follows:

#![allow(unused)]
fn main() {
use abstract_sdk::std::EXCHANGE;
use abstract_sdk::std::objects::dependency::StaticDependency;

const DEX_DEP: StaticDependency = StaticDependency::new(EXCHANGE, &[">=0.3.0"]);

/// Dependencies for the module

pub const BALANCER_DEPS: &[StaticDependency] = &[DEX_DEP];
}

Import these deps in your contract.rs where you have already referenced your entry point methods:

#![allow(unused)]
fn main() {
const APP: BalancerApp = BalancerApp::new(BALANCER, MODULE_VERSION, None)
.with_instantiate(handlers::instantiate_handler)
// ...
.with_dependencies(BALANCER_DEPS);
}

StaticDependency defines how the dependency is supposed to be imported and used. It contains id of the module and version of the module.

#![allow(unused)]
fn main() {
pub struct StaticDependency {
    pub id: ModuleId<'static>,
    pub version_req: &'static [&'static str],
}
}

version uses uses Semantic Versioning (SemVer) for its packages. You can specify dependencies using exact versions, version ranges, or other qualifiers to ensure compatibility of your modules.

Info

Make sure to keep an eye out for deprecating dependencies as well. Security updates are a must to update and some patches can be ignored.

Addressing other modules

If your module needs some modules to be enabled, it can add those as a dependency. You can then easily call messages on these modules by using the ModuleInterface trait as described in Dependency Execution Flow.

Under the hood the ID of the dependency module will be resolved on the Manager contract, returning the address of that module. The address is then used to call or query the dependency.

You can also query dependencies using the same trait or by performing a raw-query provided by the SDK.

Testing

Because the dependencies are parsed and unwrapped on-chain, you should have a sanity check on your dependencies, which can be as simple as:

#![allow(unused)]
fn main() {
#[cfg(test)]
mod tests {
    use semver::Comparator;
    use super::*;

    #[test]
    fn test_dependencies() {
        BALANCER_DEPS.iter().for_each(|dep| {
            dep.version_req.iter().for_each(|req| {
                Comparator::parse(req).unwrap();
            });
        });
    }
}
}

Module Metadata

Module metadata is a set of information that describes a module. This information is stored on-chain and can be accessed by anyone. The metadata includes the following fields:

Modules

Before you continue, make sure to learn about what modules are.

drawing

Currently, available modules to build with:

CosmWasm Staking

An Abstract Adapter module that handles staking and unbonding interactions with LP staking providers.

Naming Convention

In order to easily identify and relate contracts to on-chain addresses we follow the following conventions:

  • Staking AssetEntry: an AssetEntry of the token that is stakeable. For LP tokens this is formatted as {provider}/{asset_pair}.
    • Ex: osmosis/cosmoshub>atom,juno>juno
  • Staking AddressEntry: a ContractEntry that is formatted as {provider}:staking/{staking_asset_entry}
    • Ex: osmosis:staking/osmosis/cosmoshub>atom,juno>juno

CosmWasm Staking Adapter Module

The CosmWasm Staking Adapter Module provides a unified interface to interact with various protocols offering staking services to token holders. This can go from LP-staking to governance token locking. By abstracting the differences between various staking protocols, it allows developers to interact with any LP staking protocol using a standard interface, streamlining the development process and ensuring compatibility across various staking platforms.

Features

  • Stake: Deposit (and lock) assets inside a staking protocol
  • Unstake: Remove (and unlock) assets from staking protocol. In protocols with a locking period after unstaking, this simply triggers the unbonding process
  • Claim Rewards: Claims the rewards associated with locking your assets. In protocols with a locking period on rewad claim, this simply triggers the unbonding process
  • Claim: Claim matured unbonding claims (from unstake of Claim rewards)

Supported Staking Providers

The following Staking Providers are currently supported:

  • Osmosis (Osmosis)
  • Astroport (Neutron, Terra, Injective, Sei)
  • Kujira (Kujira)
  • Astrovault (Archway)
  • Wyndex (Juno)

If you would like to request support for an additional Staking Provider, please create a GitHub issue or reach out to us on Discord.

Installation

To use the CW-Staking Adapter Module in your Rust project, add the following dependency to your Cargo.toml:

[dependencies]
abstract-cw-staking = { git = "https://github.com/AbstractSDK/abstract.git", tag="v0.20.0", default-features = false }

Usage with the Abstract SDK

#![allow(unused)]
fn main() {
// Retrieve the adapter interface
use abstract_sdk::{AdapterInterface, core::objects::LpToken};
use abstract_cw_staking::{msg::StakingAction, msg::StakingExecuteMsg, CW_STAKING};
...

let provider = "osmosis".to_string();
let lp_asset = LpToken::new(provider, vec!["cosmoshub>atom".into(), "juno>juno".into()]));

let adapters = app.adapters(deps);  
   
let stake_msg = adapters.request(  
    CW_STAKING,  
    StakingExecuteMsg {
        provider,
        action: StakingAction::Stake {  
            assets: vec![AnsEntryConvertor::new(lp_asset).ans_asset()],  
            unbonding_period: None,
        },
    },
)
}

Why Use the Cw Staking Adapter?

Simplified Development

By using the Cw Staking Adapter, developers can bypass the intricacies of each individual Staking Provider. This means less time spent on understanding and integrating with each staking provider’s unique API, and more time focusing on building core functionalities.

Flexibility

Using Abstract adapters ensure that your application remains flexible. If a new Staking Provider or use-case emerges or if there are changes to an existing one, your application can easily adapt without undergoing major overhauls.

Use Cases

  • Rapid Prototyping: Quickly build and test applications on top of various staking providers without the need for multiple integrations.
  • Cross-Dex Applications: Build applications that leverage multiple staking providers simultaneously, offering users more options and better rates.
  • Future-Proofing: Ensure your application remains compatible with future staking solutions that emerge in the Cosmos ecosystem.

Documentation

  • CW-Staking Interface: For a detailed look at the cw-staking interface, refer to the Rust trait interface.
  • Adapters Documentation: Comprehensive information about adapters can be found in the official documentation.

Contributing

If you have suggestions, improvements, new Staking Providers, or want to contribute to the project, we welcome your input on GitHub.

Dex Adapter Module

The Dex Adapter Module provides a unified interface to interact with various decentralized exchanges (dexes) across the Cosmos ecosystem. By abstracting the differences between various dexes, it allows developers to interact with any dex using a standard interface, streamlining the development process and ensuring compatibility across various dex platforms.

Features

  • Swap: Exchange one asset for another.
  • Provide Liquidity: Add assets to a liquidity pool.
  • Withdraw Liquidity: Remove assets from a liquidity pool.
  • Simulate Swap: Predict the outcome of a swap without executing it, useful for previewing potential trades.
  • Provide Liquidity Symmetric: Add an equal value of two assets to a liquidity pool.
  • Custom Swap: Execute a swap with custom parameters, allowing for more advanced trading strategies.

Supported Dexes

The following Dexes are currently supported:

  • Osmosis (Osmosis)
  • Astroport (Neutron, Terra, Injective, Sei)
  • Kujira (Kujira)
  • Astrovault (Archway)
  • Wyndex (Juno)

If you would like to request support for an additional Dex, please create a GitHub issue or reach out to us on Discord.

Installation

To use the Dex Adapter Module in your Rust project, add the following dependency to your Cargo.toml:

[dependencies]
abstract-dex-adapter = { git = "https://github.com/AbstractSDK/abstract.git", tag="v0.18.0", default-features = false }

Usage with the Abstract SDK

To interact with a dex, you first need to retrieve the dex using the Dex Adapter. Here’s a basic example in Rust:

#![allow(unused)]
fn main() {
// Retrieve the dex
use abstract_dex_adapter::api::DexInterface;
...

let dex_name = "osmosis".to_string();
let offer_asset = OfferAsset::new("juno", 1000u128);
let ask_asset = AssetEntry::new("uusd");
let max_spread = Some(Decimal::percent(1));
let belief_price = Some(Decimal::percent(2));

let dex = app.dex(deps.as_ref(), dex_name);

let swap_msg = dex.swap(offer_asset, ask_asset, max_spread, belief_price);
}

Why Use the Dex Adapter?

Simplified Development

By using the Dex Adapter, developers can bypass the intricacies of each individual dex. This means less time spent on understanding and integrating with each dex’s unique API, and more time focusing on building core functionalities.

Flexibility

The Dex Adapter ensures that your application remains flexible. If a new dex emerges or if there are changes to an existing one, your application can easily adapt without undergoing major overhauls.

Use Cases

  • Rapid Prototyping: Quickly build and test applications on top of various dexes without the need for multiple integrations.
  • Cross-Dex Applications: Build applications that leverage multiple dexes simultaneously, offering users more options and better rates.
  • Future-Proofing: Ensure your application remains compatible with future dexes that emerge in the Cosmos ecosystem.

Documentation

Contributing

If you have suggestions, improvements, new dexes, or want to contribute to the project, we welcome your input on GitHub.

MoneyMarket Adapter Module

The MoneyMarket Adapter Module provides a unified interface to interact with various lending and borrowing markets (moneymarkets) across the Cosmos ecosystem. By abstracting the differences between various moneymarkets, it allows developers to interact with any moneymarket using a standard interface, streamlining the development process and ensuring compatibility across various moneymarket platforms.

Features

  • Swap: Exchange one asset for another.
  • Provide Liquidity: Add assets to a liquidity pool.
  • Withdraw Liquidity: Remove assets from a liquidity pool.
  • Simulate Swap: Predict the outcome of a swap without executing it, useful for previewing potential trades.
  • Provide Liquidity Symmetric: Add an equal value of two assets to a liquidity pool.
  • Custom Swap: Execute a swap with custom parameters, allowing for more advanced trading strategies.

Supported Lending Markets

The following lending markets are currently supported:

  • Mars (Osmosis)
  • Kujira Ghost (Kujira)
  • Cavern Protocol (Terra)

If you would like to request support for an additional lending market, please create a GitHub issue or reach out to us on Discord.

Installation

To use the MoneyMarket Adapter Module in your Rust project, add the following dependency to your Cargo.toml:

[dependencies]
abstract-money-market-adapter = { git = "https://github.com/AbstractSDK/abstract.git", tag="v0.21.1", default-features = false }

Usage with the Abstract SDK

To interact with a moneymarket, you first need to retrieve the moneymarket using the Moneymarket Api. Here’s a basic example in Rust:

#![allow(unused)]
fn main() {
// Retrieve the money_market
use abstract_money_market_adapter::api::MoneyMarketInterface;
...

let money_market_name = "mars".to_string();
let deposit_asset = OfferAsset::new("juno", 1000u128);

let money_market = app.money_market(deps.as_ref(), money_market_name);
let deposit_msg = money_market.deposit(deposit_asset);
}

Limitation

The Money Market adapter provides easy ways of interacting with Money Markets. However, some errors can appear without the adapter catching them:

  • The money market can have deposit limits enabled which may be crossed when using this adapter.
  • The money market may not have liquidity available to borrow funds.
  • The money market may not have liquidity available to withdraw deposited funds from
  • The user may not be able to withdraw collateral because they are borrowing too much funds.

All those errors and more have to be handled directly by the developers integrating this adapter.

Why Use the MoneyMarket Adapter?

Simplified Development

By using the Adapter, developers can bypass the intricacies of each individual platform. This means less time spent on understanding and integrating with each moneymarket’s unique API, and more time focusing on building core functionalities.

Flexibility

The MoneyMarket Adapter ensures that your application remains flexible. If a new moneymarket emerges or if there are changes to an existing one, your application can easily adapt without undergoing major overhauls.

Use Cases

  • Rapid Prototyping: Quickly build and test applications on top of various moneymarkets without the need for multiple integrations.
  • Cross-Dex Applications: Build applications that leverage multiple moneymarkets simultaneously, offering users more options and better rates.
  • Future-Proofing: Ensure your application remains compatible with future moneymarkets that emerge in the Cosmos ecosystem.

Documentation

  • Moneymarket Interface: For a detailed look at the moneymarket interface, refer to the Rust trait interface. #TODO, fix this will be broken

  • Adapters Documentation: Comprehensive information about adapters can be found in the official documentation.

Contributing

If you have suggestions, improvements, new moneymarkets, or want to contribute to the project, we welcome your input on GitHub.

Subscription App

Description

This app allows users to create subscriptions that other people can subscribe to. Users provide funds when they subscribe and those funds are used to pay for the subscription for as long as the funds don’t run out.

When a user does’n top-up their balance, an external call is made to the subscription contract to cancel the subscription. The admin can opt to add a cancellation hook that will be called when the subscription is canceled and which contains the addresses of the now ex-subscribers.

Features

The subscription app serves three primary functions:

  1. Empower businesses to unlock revenue streams with a cutting-edge subscription model.
  2. Streamline the allocation of earnings and native assets to your team of contributors, ensuring fair compensation.
  3. Enhance user engagement by rewarding active participants with native assets, fostering a vibrant community ecosystem.

Income

The income generated by our service can fluctuate as new subscribers join and existing ones depart. To ensure our system adapts to these changes in revenue, we’ve developed a method to monitor income closely. Traditional monthly settlements aren’t compatible with blockchain technology, so we’ve adopted a monthly payment approach instead. We calculate a ‘Time-Weighted Average’ of income, breaking it down to a per-second basis to get a clear picture of our earnings throughout the month. This process helps us average out the income over each month, allowing us to make informed decisions and adjustments to our infrastructure based on current financial performance.

Emissions

Protocol emissions play a crucial role in building a close-knit community of users and contributors for your product. The emissions functionality of this module makes it simple to tailor emission settings to suit your requirements. You set these parameters at the time you create the module, and they’re detailed within the ‘EmissionType’ structure, ensuring you have the flexibility to adjust how rewards are distributed within your community.

Contributions

The contribution feature in our contract is designed to directly reward users who help develop and enhance your product. Every contributor is recognized with specific ‘Compensation’ settings tailored to them. Here’s how it works:

  • The system’s total revenue is distributed between the organization (DAO) and its contributors, as outlined in the ‘ContributionConfig.’
  • Optionally, token emissions to contributor (and users) are dynamically set based on the protocol’s income. This means if the demand or income decreases, token distributions increase, and they decrease when demand or income goes up.

This approach ensures that those who invest their time and effort into the product are fairly compensated, fostering a motivated community committed to the product’s growth.

Documentation

Contributing

If you have suggestions, improvements or want to contribute to the project, we welcome your input on GitHub.

Community

Check out the following places for support, discussions & feedback:

Use Cases

Welcome to the Use Cases section of the Abstract documentation. This part of our guide is designed to show you the breadth and depth of possibilities that Abstract unlocks in the world of blockchain development.

As you navigate through this section, you will discover a variety of applications where Abstract’s unique approach to modular development and perpetual rewarding system can truly shine. We will explore real-life scenarios across different domains, such as Decentralized Application Development, Open Source Contribution, Decentralized Finance, and Educational Use. For each application, we’ll present concrete examples to illustrate how Abstract’s principles and technology have been used to drive value and innovation.

The journey through these use cases will provide you with a deeper understanding of Abstract’s potential and how its distinctive approach can revolutionize the way you develop on the blockchain. By the end of this section, we hope you’ll be inspired to consider new ways in which you could leverage Abstract in your own projects.

Decentralized Application Development

Abstract’s modular design allows developers to leverage pre-built functionalities, minimizing redundant work and accelerating the creation process. With Abstract, developers simply choose the modules they need—user authentication, data storage, payment processing—and integrate them effortlessly. Meanwhile, the platform’s blockchain nature enhances security, providing users with a safer, transparent experience. Plus, Abstract’s usage-based rewards mean that every use of a module generates income for its creator, promoting a cycle of continuous improvement and fair compensation.

Case Study

Open Source Contribution

Open source contribution is no longer a thankless job with Abstract. The platform has revolutionized the way open source developers are compensated, ensuring they are rewarded every time their code is used. Abstract’s unique model, powered by blockchain and tokenomics, ensures perpetual rewards based on the usage of their work.

Rather than the traditional one-off donations or sponsorships, Abstract brings a sustainable, fair, and motivating environment. The more your module is used, the more you earn. This directly ties your effort with your reward and incentivizes the production of quality work. It’s an open-source world where every contribution counts, and every use of your module is a vote of confidence and a token of appreciation.

Case Study

CronCat, built as an Abstract SDK module, is a decentralized scheduling system for blockchain transactions, designed to automate and schedule tasks for any contract within a blockchain environment. It provides a general-purpose, fully autonomous network enabling scheduled function calls for blockchain contract execution.

Decentralized Finance

Abstract simplifies the creation of DeFi applications, empowering developers to extend financial services to anyone with internet access. With its modular architecture, Abstract allows developers to create, share, and reuse DeFi modules, reducing development time, effort, and cost.

In the Abstract ecosystem, you can seamlessly integrate pre-existing DeFi modules into your applications, streamlining the process and boosting your development speed. Need a lending protocol or an AMM (Automated Market Maker) feature? Simply find a module, plug it into your application, and let Abstract do the heavy lifting.

Moreover, as every module is openly available on the platform, developers across the globe are continuously contributing to and refining the DeFi tools at your disposal. It’s never been easier to take part in the DeFi revolution and bring financial services to the unbanked and underbanked, all thanks to Abstract.

Case Study

  • Equilibrium: Auto-rebalancing protocol for weighted portfolios of Cosmos assets.
  • 4t2 Finance: Yield Aggregator for IBC-enabled Chains.

Educational Use

As an open, modular blockchain platform, Abstract is not just a tool for development but also a fantastic learning resource for budding developers keen to delve into the world of blockchain, modular architecture, and decentralized governance.

For blockchain enthusiasts, Abstract offers a real-world application of blockchain technology. By interacting with Abstract’s tokenomics, developers can understand how blockchain can be used to create secure, transparent, and decentralized systems, from DeFi applications to governance protocols.

The modular architecture of Abstract allows developers to explore how complex applications can be built from reusable, interchangeable modules. By experimenting with the platform’s modules, users can understand how to design, implement, and integrate modules into larger systems effectively.

Moreover, Abstract’s decentralized governance model offers invaluable insights into how decentralized systems can be managed and maintained. Through participating in governance with the ACT token, developers can learn about consensus mechanisms, voting systems, and the challenges and solutions involved in decentralized decision-making.

In essence, Abstract provides an all-in-one educational platform for any developer seeking to deepen their understanding of these critical areas in today’s tech landscape.

Case Study

There’s no better way to grasp the power and potential of Abstract than by diving in and exploring it firsthand. Whether you’re a seasoned developer, an open-source contributor, a DeFi enthusiast, or a curious learner, Abstract opens up a world of possibilities for you to discover. Start creating modules, contributing to the open-source community, building DeFi applications, or simply learning about the fascinating domains of blockchain, modular architecture, and decentralized governance. The journey with Abstract is certain to enrich your development skills, broaden your understanding, and potentially pave the way for you to create lasting value in the tech world.

Equilibrium

Equilibrium, dubbed as “The Cosmos Rebalancer” and awarded at HackWasm 2022, operates an auto-rebalancing protocol to facilitate creation of weighted portfolios of Cosmos assets, with portfolio allocations auto-adjusted per market fluctuations. The protocol is built using the Abstract SDK as a foundation as well as the CronCat protocol, and aims to boost liquidity within the Atom Economic Zone. Equilibrium’s contracts are highly composable, audited for security, and enable innovative financial products on the Neutron blockchain. This initiative seeks to align with Neutron’s core values and enhance its ecosystem by attracting investments, liquidity, and maximizing Miner Extractable Value (MEV) opportunities.

For more details about Equilibrium, please visit the official website.

4t2 Finance

FortyTwo, winner of the Cosmoverse 2023 pitch contest, aims to simplify access to the Cosmos ecosystem, acting as an entry point and yield aggregator for all IBC-enabled chains. It addresses Cosmos’ complexity by providing a unified user interface, optimized liquidity, and portfolio tracking, among other features. Through FortyTwo, users can interact with cross-chain DeFi and NFTs, manage their portfolios, and find optimal places to swap or earn on their crypto assets.

FortyTwo is built on the Abstract SDK.

For more details about FortyTwo, please visit the official website.

Frequently Asked Questions (FAQ)

  1. What is Abstract?

Abstract is a CosmWasm development platform designed to empower developers to craft secure and dynamic applications effortlessly. It boasts a modular architecture and provides an exhaustive range of tools, streamlining the development process and catalyzing the innovation of solutions in the blockchain space.

  1. Who can use Abstract?

There are two faces to Abstract:

  • For developers who want to build any CosmWasm-based application quickly and securely, leveraging the security and modularity of the Abstract framework.
  • For project ideators who want to setup their applications quickly and get their MVP out the door ASAP. Create an Abstract Account and install modules available in the marketplace to expose application functionality.
  1. How does Abstract differ from other blockchain platforms?

While there are other blockchain frameworks available, Abstract stands out due to its unique combination of a modular architecture, CosmWasm integration, and comprehensive developer tools, all aimed at simplifying and enhancing the development experience.

  1. How can I get started with Abstract?

To get started with Abstract, check out getting started! You will find comprehensive guides, tutorials, and resources to help you understand the platform’s features and functionality. Additionally, you can join our developer community on Discord to connect with like-minded developers and seek assistance if needed.

  1. Can I contribute to the Abstract ecosystem?

Absolutely! Abstract values community contributions and welcomes developers to contribute to the growth of CosmWasm. The best ways for you to contribute are by creating modules (see the getting started docs), sharing your insights and knowledge, participating in discussions, and collaborating on some of our open-source projects. Check out the Contributing page to learn more about how you can get involved.

  1. What are the costs associated with using Abstract?

Abstract offers various tiers, free and paid depending on your needs. For a detailed breakdown of costs, it’s best to visit our plans page or contact the Abstract team for specific pricing details.

  1. How does Abstract ensure the security of financial applications?

The marketplace on which all modules are registered and installed requires that each module be audited and conform to our security standards. Additionally, the modular architecture allows developers to leverage pre-built functionalities and best practices, reducing the risk of vulnerabilities. We are partnering with Oak Security to ensure every module is up to spec.

  1. How can I stay updated with Abstract’s latest developments?

Follow us on X @AbstractSDK to stay in the loop with our latest advancements!

  1. What about cw-orchestrator?

cw-orchestrator is a CosmWasm scripting, testing, and deployment tool designed to simplify interactions with CosmWasm smart contracts. By providing a set of macros that generate type-safe interfaces for your contracts, it not only enhances the code’s readability and maintainability but also reduces testing and deployment overhead. Check it out!

  1. Where can I seek support if I face issues?

The Abstract community is active and welcoming. If you’re encountering issues or have questions, you can join our developer community on Discord or browse the platform’s documentation for detailed guides and answers.

Abstract In 5 Minutes

Adair

A pitch of the Abstract Money CosmWasm application framework. A quick overview of the advanced features of the developer components and their relevance in an interchain ecosystem.

An Overview of the Abstract Platform - You Don’t Need To Know

Howard

Explore the transformative potential of abstraction, focusing on account and chain abstraction within the Web3 and Cosmos ecosystems. We’ll delve into how these concepts simplify blockchain interactions and enhance interoperability, while also touching on the importance of Web2 powered auth systems in bridging the authentication gap.

Abstract SDK - Quadratic Funding Demo

Adair

Cw-Orchestrator - The Best Developer Tooling in Cosmos

Kayanski

Why and How to Build on Abstract

Howard

Learn about the different components of Abstract and what it means to build applications on a chain-agnostic framework.

When All You Have is Cosmos, Everything Looks Like a Chain - The Fat Interface Thesis

Adair

An overview of the migration from the Fat Protocol Thesis to the Fat Application Thesis, and finally the Fat Interface Thesis (same as FPT). Identifies the key components in realizing true interchain applications without the users being aware of the technology behind them.

Releases

Release notes for the official Abstract SDK releases. Each release note will tell you what’s new in each version, and will also describe any backwards-incompatible changes made in that version.

Active Stable Version: 0.21.0 (20 February, 2024)

All releases:

v0.x.x

[Unreleased] - yyyy-mm-dd

Added

  • state.json now included in binary in release mode, allowing using binaries on a different environment than it’s been built.
  • module_instantiate2_address_raw for AbstractClient, allowing to install a different version than the dependency version.
  • Added helper functions assert_registered and is_registered to the ANS client API.

Changed

  • Renamed account_id to expected_account_id for abstract_client::AccountBuilder for clarity
  • Namespace claiming on mainnet is now permissioned.

Removed

  • unused custom_swap of DexCommand

[0.21.0] - 2024-02-20

Added

  • Added a .execute method on the AuthZ API to execute CosmosMsg types on behalf of a granter.
  • Add IBC helpers to account client.
  • Abstract Client builder: register dexes on ANS
  • .sub_accounts method on Account for getting Abstract Client Sub Accounts
  • Publish adapter method of Abstract Client Publisher now returns Adapter object
  • Added a .account_from method on the AbstractClient for retrieving Accounts.
  • Creating Sub Account from AbstractClient Account builder.
  • Installing apps and adapters for AbstractClient Account builder
  • Attaching funds to account creation on AbstractClient Account builder
  • Added unchecked_account_id method on version control.
  • Ability to provide expected local AccountId
  • Reinstallation of the same version of an app is now disabled
  • .authorize_on_adapters method on Application for authorizing application on adapters
  • Added method to assign expected .account_id for Abstract Client Account builder
  • .next_local_account_id for AbstractClient to query next local account sequence
  • .module_instantiate2_address for AbstractClient to get predicted address

Changed

  • Updated UsageFee api to use Address, instead of Api + unchecked address
  • Tests now use MockBech32 due to use of instantiate2.

Removed

Fixed

  • Added a validation on account_id method on version control.
  • Creating sub-account from account factory is restricted. Use Create Sub Account method of the manager instead

[0.20.0] - 2024-01-24

Added

  • AppDeployer and AdapterDeployer now take a DeployStrategy field.
  • Astrovault integrated into dex and cw-staking adapters
  • AuthZ API added
  • Interchain Abstract Accounts can now be created!
  • Added snapshot tests
  • Method query_account_owner() for Apps Admin object
  • Query registered_dexes for AbstractNameServiceClient
  • Query top_level_owner for manager and apps(as base query)
  • Support of ConcentratedLiquidity pool type for swaps. Stake/unstake currently not supported
  • Account namespace is unclaimed after Renounce
  • Resolve trait for cw-orch AnsHost interface

Changed

  • is_module_installed moved from Manager to Account.
  • account_id() method of AccountRegistry is now exposed.
  • Allow module-id to be passed in as a valid authorized address when allowing new addresses on adapter contracts.
  • BaseInstantiateMsg is now removed from install app API, now only ModuleMsg should be provided.
  • Modules, Manager and Proxy are now instantiated via instantiate2 message.
  • FeeGrant API updated.
  • Bump cw-orch to v0.18.
  • Top level account owner now has admin privileges on the apps and adapters
  • Multiple AbstractAccounts now don’t overlap
  • Top level account owner can now claim pending sub-accounts directly
  • Clearable helper type was added to the messages where clearing optional state could be useful
  • Only incremental version migration of modules allowed (0.10 -> 0.11 is allowed but 0.10 -> 0.12 not because it skips 0.11)
  • Module tag_response and custom_tag_response no longer require Response as an argument as well as renamed to response and custom_response respectively.
  • Having sub accounts will prevent you from Renounce
  • Version Control Namespace query now doesn’t return an error when namespace is unclaimed
  • NamespaceResponse type updated to be able to represent claimed and unclaimed namespace

Removed

  • DepositMsgs removed (now deposit() returns Vec<CosmosMsg>)
  • Abstract removed from the fields where it’s redundant
  • InstantiateMsg is now removed from the install_adapter API
  • Removed wasm_smart_query helper, since it’s accessible from Querier object
  • Removed Adapter base Remove action

Fixed

  • Namespace registration fee fixed
  • Version Control smart query now returns Version Control config instead of factory address
  • Sub accounts now unregister themselves on owning manager if renounced

[0.19.0] - 2023-09-26

Added

  • Install modules on account or Sub-account creation.
  • Manager stores his sub-accounts and sub-accounts can register or unregister in case of ownership change.
  • Query on module factory to see how much funds needs to be attached for installing modules.
  • Version control on instantiation to the Apps alongside with registry traits.
  • Instantiation funds added to module configuration, allowing modules to perform external setup calls.
  • An adapter_msg_types similar to app_msg_types. This can be used to easily define the top-level entrypoint messages.

Changed

  • Updated fetch_data arguments of CwStakingCommand
  • StakingInfoResponse now returns staking target(which is either contract address or pool id) instead of always staking contract address.
  • Owner of the sub-accounts now Proxy, allowing modules to interact with sub-accounts.
  • Install modules replaced install module method on module factory to reduce gas consumption for multi-install cases.
  • Modified the account id structure. Each account is now identified with a unique ID and a trace. This is a requirement for Abstract IBC.
  • Register Module(and Add Module) will now accept list of items, which reduces gas for multi-module install
  • Removed the CustomSwap option on the dex adapter.
  • Stake methods on cw-staking adapter now accept list, allowing users to do multi-stake/unstake/etc.
  • Added must_use attribute on abstract sdk methods
  • Renamed abstract-(dex/staking)-adapter-traits to abstract-(dex/staking)-standard

Fixed

  • Partially fixed cw-staking for Osmosis.
  • Manager governance now changes only after new “owner” claimed ownership.
  • Fixed and separated cw-staking and dex adapters for kujira.
  • ExecOnModule calls now forward any provided funds to the module that is called.
  • Manager queries of standalone module versions will now return version of the contract from the Version Control storage instead of error

[0.17.2] - 2023-07-27

Added

  • Neutron + Archway to registry

Changed

Fixed

[0.17.1] - 2023-07-26

Added

  • Ability to set admin to native contracts during instantiation
  • Query handler for module data
  • Added neutron

Changed

  • Address of App/Adapter returned and set by default.

Fixed

[0.17.0] - 2023-07-05

Added

  • Ability to add module metadata.
  • Ability to set an install fee for modules.
  • Account interaction helpers

Changed

  • Removed the ability to claim multiple namespaces.
  • It is now possible to replace a module code-id/address on testnets.

Fixed

  • Adapter execution from the manager with a provided proxy address is now allowed.

[0.7.0] - 2023-02-15

Added

Changed

  • Errors now need to implement From<AbstractError> and From<AbstractSdkError>

Fixed

[0.7.0] - 2023-02-01

Added

Changed

  • Version Control Modules / ModuleList

Fixed

[0.5.2] - 2023-01-10

Added

Changed

Fixed

  • Fixed abstract-interface publishing

[0.5.0] - 2022-01-08

Added

Changed

Fixed

  • Fixed wasming with write_api error in the abstract-adapter and abstract-app

[0.5.0] - 2022-01-08

Added

Module Factory

  • unit testing

Ans Host

  • Config query

Abstract SDK

  • Better querying of app and adapter directly vs message construction

Changed

  • PoolId is now renamed to PoolAddress to avoid confusion with the Abstract Pool Id (and because it can be resolved to an address / id)

Removed

  • construct_staking_entry from ContractEntry, which had previously violated the SRP.

Fixed

Abstract Glossary

These are some definitions used in our documentation:

Abstract

A framework designed to simplify the development of decentralized applications in the Cosmos ecosystem. It offers tools and infrastructure for composable smart-contract applications.

Abstract Account

A unique entity within the Abstract framework that can have modules installed onto it, enabling various functionalities. It consists of a Manager and a Proxy contract.

Account

Short for Abstract Account.

Abstract Account Console

A web-based interface that provides functionalities like account management, module management, name service, dev tools, and delegations.

Abstract APIs

Interfaces provided by Abstract to facilitate interactions between the frontend and the on-chain framework.

Abstract Base

The foundational layer of the Abstract framework, upon which other functionalities and modules are built.

Abstract Modules

Pre-built functionalities that can be installed onto an Abstract Account. They come in three types: App, Adapter, and Standalone.

Abstract Name Service (ANS)

An on-chain store that provides chain-agnostic action execution and dynamic address resolution.

Abstract SDK

A toolbox for developers to create composable smart-contract APIs in the Abstract ecosystem. It provides a set of tools and utilities to facilitate the creation and interaction of smart contracts.

Abstract-Testing

A package that provides testing utilities for CosmWasm contracts, focusing on mocking and querying functionalities.

Abstract.js

A JavaScript library designed to facilitate interactions with the on-chain Abstract framework.

Account Abstraction

A concept where the Abstract Account acts as a layer abstracting the complexities of blockchain interactions, allowing for a more user-friendly experience.

Account Factory

A contract that facilitates the creation and management of Abstract Accounts.

Account Ownership

The concept that defines who has control and access rights over an Abstract Account. This can be a single entity ( Monarchy) or multiple entities (Multisig).

Adapter

A type of Abstract Module that acts as an intermediary, translating and routing messages between Apps and external services or protocols.

API Objects

Rust structs in the Abstract SDK that expose specific smart-contract functionalities. They can be used if a contract implements the required features/api traits.

App

A type of Abstract Module designed to enable specific features or transform Abstract Accounts into standalone products.

Cosmos

A decentralized network of independent, scalable, and interoperable blockchains. The Cosmos ecosystem is built on a set of modular, adaptable, and interchangeable tools, with the Cosmos SDK being its foundational framework. Cosmos aims to create an “Internet of Blockchains” where different blockchains can communicate and transact with each other seamlessly through the Inter-Blockchain Communication (IBC) protocol.

CosmWasm

A smart contract platform built for the Cosmos ecosystem. Within the Abstract framework, CosmWasm serves as the underlying smart contract platform that powers the modular and composable functionalities of Abstract Modules. It allows developers to write secure and interoperable smart contracts in Rust, which can then be integrated into the Abstract ecosystem. By leveraging CosmWasm, Abstract ensures that its modules and applications are both scalable and compatible with the broader Cosmos ecosystem.

CW-Orchestrator

CW-Orchestrator is a scripting tool specifically designed to streamline interactions with, testing and deployment of CosmWasm smart contracts.

IBC-Host

A module that facilitates Inter-Blockchain Communication (IBC) within the Abstract framework, allowing for cross-chain interactions.

Integration Testing

Testing that involves deploying the contract and its dependencies to a mock environment to ensure they work together correctly.

JSON Schema Linking

Linking a module’s JSON schema to the Abstract Version Control to improve user experience for developers using the module.

Manager Contract

A contract within an Abstract Account responsible for managing the account’s modules and permissions.

Migration Update

A process within the Abstract framework that allows for the updating or upgrading of modules without compromising the state or data.

Mock Querier

A tool provided by the abstract-testing package to mock Smart and Raw queries for unit testing.

Module Factory

A contract that allows the installation and management of Abstract Modules via the Account Manager.

Module Installation

The process of adding a module to an Abstract Account, specifying its parameters, and initializing it on a specific network.

Module Uploading

The process of compiling a module as a WASM binary and then uploading it to the desired network(s).

Monarchy

A type of account ownership where a single entity has full control over an account.

Move Update

A process that allows for the migration of an Abstract Account from one blockchain to another within the Cosmos ecosystem.

Multisig

A type of account ownership where multiple entities have control over an account, and a predefined number of them must agree on actions taken.

Namespace

A unique publishing domain for Abstract modules, associated with an Abstract Account. It’s used to uniquely identify and monetize modules.

Proxy Contract

A contract within an Abstract Account that handles interactions with external contracts and services.

Raw Queries

Simple database key-value lookups without the computational aspect of smart queries.

Rust

A systems programming language that focuses on performance, reliability, and productivity. Rust offers memory safety guarantees by using a borrow checker to validate references. It’s known for its “zero-cost abstractions,” meaning developers can write high-level code without sacrificing performance. Rust has gained popularity for blockchain and smart contract development due to its safety features and efficient performance.

Smart Queries

Queries that contain a message in their request and often involve computation on the queried contract.

Version Control

A contract that acts as a registry for all modules and accounts within the Abstract platform.

Contributing to Abstract SDK

Thank you for considering to contribute to the Abstract SDK project! We appreciate your support and welcome contributions to help improve this multi-environment CosmWasm smart-contract scripting library. This document provides guidelines and instructions on how to contribute to the project effectively.

Table of Contents

Getting Started

To get started with contributing to the Abstract SDK project, you should first familiarize yourself with the repository structure and the codebase. Please read the project’s README to understand the purpose, features, and usage of the Abstract SDK library as well as its documentation.

How to Contribute

There are multiple ways to contribute to the Abstract SDK project, including reporting bugs, suggesting enhancements, and submitting code contributions.

Reporting Bugs

If you encounter any bugs or issues while using the Abstract SDK library, please report them by creating a new issue in the issue tracker. When reporting a bug, please provide the following information:

  • A clear and descriptive title
  • A detailed description of the issue, including steps to reproduce it
  • Any relevant logs, error messages, or screenshots
  • Information about your environment, such as the OS, software versions, and hardware specifications

Suggesting Enhancements

We welcome suggestions for new features or improvements to the existing functionality of the Abstract SDK library. To suggest an enhancement, create a new issue in the issue tracker with the following information:

  • A clear and descriptive title
  • A detailed explanation of the proposed enhancement, including its benefits and potential use cases
  • If applicable, any examples or mockups of the proposed feature

Code Contributions

To contribute code to the Abstract SDK project, please follow these steps:

  1. Fork the repository to your own GitHub account.
  2. Clone your fork to your local machine.
  3. Create a new branch for your changes using the git checkout -b feature/your-feature-name command.
  4. Make your changes and commit them with a clear and concise commit message.
  5. Push your branch to your fork on GitHub.
  6. Create a new pull request against the main branch of the Abstract SDK repository.

Pull Requests

When submitting a pull request, please make sure that your code follows the Style Guide and that all tests pass. Please provide a detailed description of your changes, including the motivation for the changes and any potential impact on the project. This will help maintainers review your pull request more effectively.

Style Guide

The Abstract SDK project follows the Rust coding style and conventions. Please ensure that your code adheres to these guidelines to maintain consistency and readability throughout the codebase.

  • Use proper indentation (4 spaces) and consistent formatting (cargo fmt).
  • Write descriptive variable and function names.
  • Use comments to explain complex or non-obvious code.
  • Follow the Rust API Guidelines for API design.
  • Add documentation for public functions, types, and modules.
  • Write doc tests for public functions and methods.

Community

To join the Abstract SDK community, please join the Abstract Discord server and the #Abstract SDK channel. You can also follow the project on X and GitHub.