Coder Social home page Coder Social logo

cw-nibiru's Introduction

NibiruChain/cw-nibiru

Smart contract sandbox for Nibiru Chain.

⚡ NibiruChain/cw-nibiru
├── 📂 artifacts         # compiled .wasm smart contracts for cw-nibiru
├── 📂 contracts         # Smart contracts for Nibiru Chain
    └── 📂 nibi-stargate # Example contract using nibiru-std for CosmosMsg::Stargate
    └── 📂 incentives    # Generalized incentives over time for locked tokens
    └── 📂 lockup        # For locking and unlocking tokens like LP tokens
    └── 📂 pricefeed     # CosmWasm prototype of the (now deprecated) x/pricefeed module.
    └── 📂 core-cw3-flex-msig # CW3-flex-multisig with stargate enabled.
    └── 📂 core-shifter       # Calls peg shift and depth shift in x/perp.
    └── 📂 core-controller    # Calls other admin calls from Nibiru foundation.
    └── 📂 core-token-vesting # Token linear vesting contracts with optional cliffs.
    └── 📂 core-token-vesting-v2 # Improved version of core-token-vesting-v2.
├── 📂 nibiru-std      # Nibiru Chain standard library for smart contracts
    └── 📦 proto       # Types and traits for QueryRequest::Stargate and CosmosMsg::Stargate
         └──           #   Includes constructors for Cosmos, IBC, and Nibiru. 
    └── 📦 bindings    # For sending CosmosMsg::Custom msgs on Nibiru (soon deprecated).
├── 📂 packages        # Other Rust packages
    └── 📦 bash-rs     # Easily run bash from Rust. Used for writing testable and maintainable scripts.
    └── 📦 nibi-dev    # Dev tooling package for Nibiru. 
    └── 📦 nibiru-macro  # Implements procedural macros for the "nibiru-macro" package. 
├── Cargo.toml
├── Cargo.lock
└── README.md

Hacking

Install just to run project-specific commands.

cargo install just

You can view the list of available development commands with just -ls.

Ref: github.com/casey/just

cw-nibiru's People

Contributors

dependabot[bot] avatar fdymylja avatar jgimeno avatar k-yang avatar matthiasmatt avatar onikonychev avatar unique-divine avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

cw-nibiru's Issues

epic: linear vesting smart contract for investors, advisors, and other contributors

Summary

The token agreements defined in the
tokenomics will be implemented
via a CosmWasm smart contract. The feature demands (1) a secure and
configurable way to vest tokens linearly over time and (2) an interface for
claiming vested tokens.

Sprint 1 - Initial Draft

  • 2023-07-16: Add MVP to the cw-nibiru repo. | @jgimeno
  • Peer audit on initial version | #52
  • Full test coverage of core business logic
  • feat: vesting from cliffs with different start times.

Sprint 2 - Rehearsal

  • Practice setting up the contracts with an SDK group, CW group, or multisig.
  • Automate the setup on a fresh local chain so that it can run as a CI test.
  • (Maybe) Code4rena or Confio audit?

Make VM errors more descriptive in the perp binding contract

Context

Here's an example error raised from the bindings-perp contract when I queried
the reserves in Go using a pair that wasn't defined in the genesis.

Error calling the VM: Error executing Wasm: Wasmer runtime error: RuntimeError: Aborted: panicked at 'called `Result::unwrap()` on an `Err` value: GenericErr { msg: "Querier contract error: codespace: undefined, code: 1" }', contracts/bindings-perp/src/binding.rs:74:24: query wasm contract failed

The VM error tells me that an error was raised, but it doesn't say what went
wrong. Instead of simply using unwrap, the contract should be more descriptive.

Logs from TestSuite/TestQueryReserves:

  querier_test.go:59:
  Error Trace:    /home/realu/warpath/NibiruChain/nibiru/x/wasm/binding/querier_test.go:59
                                          /home/realu/warpath/NibiruChain/nibiru/x/wasm/binding/querier_test.go:153
  Error:          Received unexpected error:

    github.com/CosmWasm/wasmd/x/wasm/keeper.Keeper.QuerySmart
      /home/realu/go/pkg/mod/github.com/!cosm!wasm/[email protected]/x/wasm/keeper/keeper.go:718
    github.com/NibiruChain/nibiru/x/wasm/binding_test.DoCustomBindingQuery
      /home/realu/warpath/NibiruChain/nibiru/x/wasm/binding/querier_test.go:56
    github.com/NibiruChain/nibiru/x/wasm/binding_test.(*QuerierTestSuite).TestQueryReserves
      /home/realu/warpath/NibiruChain/nibiru/x/wasm/binding/querier_test.go:153
    reflect.Value.call
      /usr/local/go/src/reflect/value.go:584
    reflect.Value.Call
      /usr/local/go/src/reflect/value.go:368
    github.com/stretchr/testify/suite.Run.func1
      /home/realu/go/pkg/mod/github.com/stretchr/[email protected]/suite/suite.go:197
    Error calling the VM: Error executing Wasm: Wasmer runtime
    error: RuntimeError: Aborted: panicked at 'called
    `Result::unwrap()` on an `Err` value: GenericErr { msg:
    "Querier contract error: codespace: undefined, code: 1" }',
    contracts/bindings-perp/src/binding.rs:74:24: query wasm
    contract failed

ci: add workflow to verify contracts build to .wasm bytecode

Tasks

  • Req 1: Use unoptimized builds
  • Req 2: These build tests should only run when things change.

Req 1: Use unoptimized builds

I ran some performance benchmarks to compare times when building for the Wasm target with and without release optimization. On average (on my local machine), it was about 23% faster to build with cargo wasm-debug than to build with cargo wasm.

cargo wasm-debug := cargo build --target wasm32-unknown-unknown
cargo wasm       := cargo build --release --target wasm32-unknown-unknown

This test should use the non-release builds since they're faster and the resulting bytecode from these CI runs won't be published.

Req 2: These build tests should only run when things change.

  • If no smart contract Rust code or dependencies are changed, nothing should run, and the GitHub action should pass.
  • If only 2 smart contracts change, for example, only those two should run.
  • The action should only fail when something runs and has an error.

Related

ci: manually callable workflow to build `.wasm` binaries using `cosmwasm/rust-optimizer`

Desired Dev X

Suppose that my machine doesn't have the right architecture to generate Wasm bytecode intended for production. This could be Windows without WSL or a Darwin (MacOS) architecture that could result in nondeterminism.

As a workaround, there should be an easy way me to:

  1. Push Rust code for contracts that I'm certain will compile to a branch
  2. Start a pull request for that branch with the changes
  3. Manually trigger or request a repo owner to trigger a workflow that generates the Wasm bytecode (for production) and then publishes it as an artifact for that branch

Then, I can download the artifacts and checksums to include in the pull request.

epic(ci): tag-wise publishing for gh releases

Intro

Create a GitHub action appropriate for a Rust monorepo.

The setup used in the CosmWasm/cw-plus repo seems close to what we're looking for, but there are better-managed monorepos we can take cues from.

  • Rust code: Crates are expected to be on crates.io, so they aren't published with release assets. Because of crates have their own release, we don't need to try to manage everything through tags.
  • Release Assets: Instead of releasing crate-wise, releases are done tag-wise and include compiled Wasm bytecode for smart contracts along with schema.json files and other important generated assets.
  • Versioning: The tag/release versions do not follow strict semver rules because the contracts have different purposes and aren't necessarily versioned in sync.
    .

Core contracts

Contracts like "token-vesting", "nibi-stargate", "shifter", or ones for the Go bindings can be grouped together as "core contracts" and have grouped releases. This can help keep the versions more semnatic without coupling them too tightly to unrelated code.

Future smart contracts that become core or essential to the protocol can be kept here as well.

Completion Checklist

  • Create an initial manual release for the "core contracts" to identify what steps need to be included in the automation.
  • Decide on a scheme that makes sense based on the practices of MystenLabs/sui and aptos-labs/aptos-core. Aptos and Solana have releases that can have a scope, which seems to work well. Node changes can have a release. CLI changes can have a release, and packages can have a release, all in an independent and semver-compliant manner
  • As part of the publishing workflow:
    • Automate wasm bytecode generation
    • Automate schema generation
    • Add a manually testable version to scripts and the justfile.
  • Document this process in the repo somewhere in markdown

More on Versioning

The Cosmos-SDK repo has a clever convention for managing many dependencies in tandem by prefixing tags with a scope. For instance, tags for separate packages of cosmossdk.io are prefixed.

image

spec: Template - CosmWasm bindings for a Cosmos-SDK module

Write docs to answer the following questions:

  • Q: What are CosmWasm module bindings?
  • Q: And, what are bindings in general?
  • Q: What pieces make up the architecture?
  • Q: How can binding messages be added to Nibiru and other CosmWasm-based blockchains? (Both queries and transaction messages)

feat(bindings-perp): implement migration message

The current contract implementation allows potentially many accounts to operate a single position opened and controlled by the smart contract.

As of right now, there's no way to claim the funds, and there's no way to migrate to a new version of the contract.

To migrate, the contract should:

  • Take the current balance of the contract and send it to a new address.

Eventually, we should extend migrate to go iterate through each position and close it.

  • Check if there are any positions open and close them before sending away the contract balance during migrate.

feat: epic: Add convenient functions for building `StargateMsg` transactions and queries

Modules to Prioritize

Tx msgs

  • tokenfactory tx msgs
  • perp tx msgs
  • spot tx msgs
  • tokenfactory queries

Queries

  • perp queries
  • spot queries
  • oracle queries
  • epochs queries

Rust types are available here:

pub mod nibiru {
pub mod devgas {
include!("nibiru.devgas.v1.rs");
}
pub mod epochs {
include!("nibiru.epochs.v1.rs");
}
pub mod genmsg {
include!("nibiru.genmsg.v1.rs");
}
pub mod inflation {
include!("nibiru.inflation.v1.rs");
}
pub mod oracle {
include!("nibiru.oracle.v1.rs");
}
pub mod perp {
include!("nibiru.perp.v2.rs");
}
pub mod spot {
include!("nibiru.spot.v1.rs");
}
pub mod sudo {
include!("nibiru.sudo.v1.rs");
}
pub mod tokenfactory {
include!("nibiru.tokenfactory.v1.rs");
}
}

feat(scripts): Flexible TypeScript code generation command for smart contract types

Summary

Provide a simplified abstraction around CosmWasm/ts-codegen. This should be usable from the top-level justfile.

  • Make a command that runs ts-codegen for everything to an output dir like dist.
  • ci: Add a manually runnable workflow to publish TypeScript code intended for app.nibiru.fi.

Intent / Motivation

  • Dev X and Reduced Complexity: Simplifying the interactions with ts-codegen will help eliminate the need to remember or input intricate command specifics.

  • Unified Output Directory: Centralizing generated code into a directory like dist fosters organization and ensures uniformity across the repo.

  • Better Publishing: A publishing workflow for the TypeScript code will simplify the process of sharing or distributing the generated code, reducing manual steps and potential errors.

Basic Usage for Getting Started

Install

npm install -g @cosmwasm/ts-codegen

Generating a client

# Template: Using the "client" plugin
cosmwasm-ts-codegen generate \
          --plugin client \
          --schema [path-to-schema-dir] \
          --out [path-to-ts-out-dir] \
          --name [contract-crate-name] \
          --no-bundle

# Example: Using the "client" plugin
cosmwasm-ts-codegen generate \
          --plugin client \
          --schema ./schema \
          --out ./ts \
          --name SG721 \
          --no-bundle

Generally, everything we need is some variation on cosmwasm-ts-codegen generate

bug: CosmWasm Decimal is too small for squared reserves

Heisenberg - 2023-08-09

There's an issue with the shifter contract logic. The maximum number
representable by the CosmWasm Decimal type is
340282366920938463463.374607431768211455 (~3.4e20), which leads to base
reserves and quote reserves of 18446744073.709551615000000000, far too small
for our perps markets.

For example, when I do:

nibid tx wasm execute \
nibi14hj2tavq8fpesdwxxcu44rty3hh90vhujrvcmstl4zr3txmfvw9ssa9gcs \
'{"depth_shift":{"pair":"ubtc:unusd","depth_mult":"1600000000000000000000000000"}}' \
--from validator \
--yes

I get an error

failed to execute message; message index: 0: Error parsing into type shifter::msgs::ExecuteMsg: Error parsing decimal '1600000000000000000000000000': Generic error: Value too big: execute wasm contract failed

A possible fix here would be to have the shifter contract logic operate with
sqrt_k instead of k, which increases our order of magnitude of 1e10.

Other Options

  • Option 1: Inputing Sqrt K is a good idea, as it gives another 10 digits.
  • Option 2: We can use integers only and let 1 correspond to the OneDec. This
    also gives us a bigger range.
  • Option 3: Add "pow10" field (u8) for the execute msg. It could multiply the
    input value by "10 to the pow10" and offer us a bigger range of decimals.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.