Skip to content

Commit

Permalink
IBC Rate limiting contract (#2408)
Browse files Browse the repository at this point in the history
* added ibc-rate-limiting contract

* added cosmwasm workflow

* added doc comments

* added migration msg

* Update x/ibc-rate-limit/contracts/rate-limiter/src/msg.rs

Co-authored-by: Dev Ojha <ValarDragon@users.noreply.github.com>

* removed gitkeep

* COmments & questions

* workflow without test data checks and clippy fixes

* renames and code fixes

* reordered imports

* cargo fmt

* added danom tracking

* cleanup

* refactoring

* changes to the expiration logic so that balances are calculated based on the direction (as suggested by @ValarDragon)

* slightly slower but considerably cleanner

* cleanup attributes and removed redundancy when not testing

* update to edition 2021

* added comments explaining the tests

* removed .beaker

* unified gitignore

* removed second gitignore

* better doc comments

* spelling

* spelling

* added channel value cache

* leaving the attributes hard-coded until they can be properly configured in CI

* cleanup and reorganization

* lint

Co-authored-by: Dev Ojha <ValarDragon@users.noreply.github.com>
Co-authored-by: Dev Ojha <dojha@berkeley.edu>
  • Loading branch information
3 people authored Aug 23, 2022
1 parent 757c81f commit 4fde976
Show file tree
Hide file tree
Showing 18 changed files with 2,176 additions and 0 deletions.
108 changes: 108 additions & 0 deletions .github/workflows/contracts.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
name: Cosmwasm Contracts
on:
pull_request:
push:


jobs:
test:
name: Test Suite
runs-on: ubuntu-latest
strategy:
matrix:
contract: [{workdir: ./x/ibc-rate-limit/, output: testdata/rate_limiter.wasm, build: artifacts/rate_limiter-x86_64.wasm, name: rate_limiter}]

steps:
- name: Checkout sources
uses: actions/checkout@v2

- name: Install toolchain
uses: actions-rs/toolchain@v1
with:
toolchain: nightly
target: wasm32-unknown-unknown

- name: Add the wasm target
working-directory: ${{ matrix.contract.workdir }}
run: >
rustup target add wasm32-unknown-unknown;
- name: Build
working-directory: ${{ matrix.contract.workdir }}
run: >
cargo build --release --target wasm32-unknown-unknown
- name: Test
working-directory: ${{ matrix.contract.workdir }}
run: >
cargo test
- name: Set latest cw-optimizoor version
run: >
echo "CW_OPTIMIZOOR_VERSION=`cargo search cw-optimizoor -q | cut -d '"' -f 2`" >> $GITHUB_ENV
- name: Cache cw-optimizoor
id: cache-cw-optimizoor
uses: actions/cache@v3
env:
cache-name: cache-cw-optimizoor
with:
# cargo bin files are stored in `~/.cargo/bin/` on Linux/macOS
path: ~/.cargo/bin/cargo-cw-optimizoor
key: ${{ runner.os }}-build-${{ env.cache-name }}-${{ env.CW_OPTIMIZOOR_VERSION }}

- if: ${{ steps.cache-cw-optimizoor.outputs.cache-hit != 'true' }}
name: Install cw-optimizoor
continue-on-error: true
run: >
cargo install cw-optimizoor
- name: Optimize
working-directory: ${{ matrix.contract.workdir }}
run: >
cargo cw-optimizoor
- name: 'Upload optimized contract artifact'
uses: actions/upload-artifact@v3
with:
name: ${{ matrix.contract.name }}
path: ${{ matrix.contract.workdir }}${{ matrix.contract.build }}
retention-days: 1

# - name: Check Test Data
# working-directory: ${{ matrix.contract.workdir }}
# if: ${{ matrix.contract.output != null }}
# run: >
# diff ${{ matrix.contract.output }} ${{ matrix.contract.build }}


lints:
name: Cosmwasm Lints
runs-on: ubuntu-latest
strategy:
matrix:
workdir: [./x/ibc-rate-limit]

steps:
- name: Checkout sources
uses: actions/checkout@v2

- name: Install toolchain
uses: actions-rs/toolchain@v1
with:
profile: minimal
toolchain: nightly
override: true
components: rustfmt, clippy

- name: Format
working-directory: ${{ matrix.workdir }}
run: >
cargo fmt --all -- --check
- name: run cargo clippy
working-directory: ${{ matrix.workdir }}
run: >
cargo clippy -- -D warnings
21 changes: 21 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -206,4 +206,25 @@ tools-stamp
*.save.*

mutation_test_result.txt

# Rust ignores. Generated by Cargo
# will have compiled files and executables
debug/
target/

# Generated by rust-optimizer
artifacts/

# Remove Cargo.lock from gitignore if creating an executable, leave it for libraries
# More information here https://doc.rust-lang.org/cargo/guide/cargo-toml-vs-cargo-lock.html
Cargo.lock

# These are backup files generated by rustfmt
**/*.rs.bk

# MSVC Windows builds of rustc generate these, which store debugging information
*.pdb

# Ignores beaker state
.beaker
blocks.db
16 changes: 16 additions & 0 deletions x/ibc-rate-limit/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
[workspace]

members = [
'contracts/*',
]

[profile.release]
codegen-units = 1
debug = false
debug-assertions = false
incremental = false
lto = true
opt-level = 3
overflow-checks = true
panic = 'abort'
rpath = false
3 changes: 3 additions & 0 deletions x/ibc-rate-limit/contracts/rate-limiter/.cargo/config
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
[alias]
wasm = "build --release --target wasm32-unknown-unknown"
unit-test = "test --lib"
15 changes: 15 additions & 0 deletions x/ibc-rate-limit/contracts/rate-limiter/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
# Build results
/target

# Cargo+Git helper file (https://github.com/rust-lang/cargo/blob/0.44.1/src/cargo/sources/git/utils.rs#L320-L327)
.cargo-ok

# Text file backups
**/*.rs.bk

# macOS
.DS_Store

# IDEs
*.iml
.idea
56 changes: 56 additions & 0 deletions x/ibc-rate-limit/contracts/rate-limiter/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
[package]
name = "rate-limiter"
version = "0.1.0"
authors = ["Nicolas Lara <nicolaslara@gmail.com>"]
edition = "2021"

exclude = [
# Those files are rust-optimizer artifacts. You might want to commit them for convenience but they should not be part of the source code publication.
"contract.wasm",
"hash.txt",
]

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[lib]
crate-type = ["cdylib", "rlib"]

[profile.release]
opt-level = 3
debug = false
rpath = false
lto = true
debug-assertions = false
codegen-units = 1
panic = 'abort'
incremental = false
overflow-checks = true

[features]
# for more explicit tests, cargo test --features=backtraces
backtraces = ["cosmwasm-std/backtraces"]
# use library feature to disable all instantiate/execute/query exports
library = []
# Use the verbose responses feature if you want to include information about
# the remaining quotas in the SendPacket/RecvPacket responses
verbose_responses = []

[package.metadata.scripts]
optimize = """docker run --rm -v "$(pwd)":/code \
--mount type=volume,source="$(basename "$(pwd)")_cache",target=/code/target \
--mount type=volume,source=registry_cache,target=/usr/local/cargo/registry \
cosmwasm/rust-optimizer:0.12.6
"""

[dependencies]
cosmwasm-std = "1.0.0"
cosmwasm-storage = "1.0.0"
cw-storage-plus = "0.13.2"
cw2 = "0.13.2"
schemars = "0.8.8"
serde = { version = "1.0.137", default-features = false, features = ["derive"] }
thiserror = { version = "1.0.31" }

[dev-dependencies]
cosmwasm-schema = "1.0.0"
cw-multi-test = "0.13.2"
113 changes: 113 additions & 0 deletions x/ibc-rate-limit/contracts/rate-limiter/src/contract.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
#[cfg(not(feature = "library"))]
use cosmwasm_std::entry_point;
use cosmwasm_std::{Binary, Deps, DepsMut, Env, MessageInfo, Response, StdResult};
use cw2::set_contract_version;

use crate::error::ContractError;
use crate::msg::{ExecuteMsg, InstantiateMsg, MigrateMsg, QueryMsg, SudoMsg};
use crate::state::{FlowType, Path, GOVMODULE, IBCMODULE};
use crate::{execute, query, sudo};

// version info for migration info
const CONTRACT_NAME: &str = "crates.io:rate-limiter";
const CONTRACT_VERSION: &str = env!("CARGO_PKG_VERSION");

#[cfg_attr(not(feature = "library"), entry_point)]
pub fn instantiate(
deps: DepsMut,
env: Env,
_info: MessageInfo,
msg: InstantiateMsg,
) -> Result<Response, ContractError> {
set_contract_version(deps.storage, CONTRACT_NAME, CONTRACT_VERSION)?;
IBCMODULE.save(deps.storage, &msg.ibc_module)?;
GOVMODULE.save(deps.storage, &msg.gov_module)?;

execute::add_new_paths(deps, msg.paths, env.block.time)?;

Ok(Response::new()
.add_attribute("method", "instantiate")
.add_attribute("ibc_module", msg.ibc_module.to_string())
.add_attribute("gov_module", msg.gov_module.to_string()))
}

#[cfg_attr(not(feature = "library"), entry_point)]
pub fn execute(
deps: DepsMut,
env: Env,
info: MessageInfo,
msg: ExecuteMsg,
) -> Result<Response, ContractError> {
match msg {
ExecuteMsg::AddPath {
channel_id,
denom,
quotas,
} => execute::try_add_path(deps, info.sender, channel_id, denom, quotas, env.block.time),
ExecuteMsg::RemovePath { channel_id, denom } => {
execute::try_remove_path(deps, info.sender, channel_id, denom)
}
ExecuteMsg::ResetPathQuota {
channel_id,
denom,
quota_id,
} => execute::try_reset_path_quota(
deps,
info.sender,
channel_id,
denom,
quota_id,
env.block.time,
),
}
}

#[entry_point]
pub fn sudo(deps: DepsMut, env: Env, msg: SudoMsg) -> Result<Response, ContractError> {
match msg {
SudoMsg::SendPacket {
channel_id,
channel_value,
funds,
denom,
} => {
let path = Path::new(&channel_id, &denom);
sudo::try_transfer(
deps,
&path,
channel_value,
funds,
FlowType::Out,
env.block.time,
)
}
SudoMsg::RecvPacket {
channel_id,
channel_value,
funds,
denom,
} => {
let path = Path::new(&channel_id, &denom);
sudo::try_transfer(
deps,
&path,
channel_value,
funds,
FlowType::In,
env.block.time,
)
}
}
}

#[cfg_attr(not(feature = "library"), entry_point)]
pub fn query(deps: Deps, _env: Env, msg: QueryMsg) -> StdResult<Binary> {
match msg {
QueryMsg::GetQuotas { channel_id, denom } => query::get_quotas(deps, channel_id, denom),
}
}

#[cfg_attr(not(feature = "library"), entry_point)]
pub fn migrate(_deps: DepsMut, _env: Env, _msg: MigrateMsg) -> Result<Response, ContractError> {
unimplemented!()
}
Loading

0 comments on commit 4fde976

Please sign in to comment.