Skip to content

Commit

Permalink
Merge pull request #17 from archway-network/feature/missing_modules
Browse files Browse the repository at this point in the history
Feature/missing modules
  • Loading branch information
FloppyDisck authored Feb 5, 2025
2 parents c5fa98b + ecdce34 commit 6d077c7
Show file tree
Hide file tree
Showing 12 changed files with 834 additions and 352 deletions.
744 changes: 409 additions & 335 deletions Cargo.lock

Large diffs are not rendered by default.

5 changes: 4 additions & 1 deletion packages/chain/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,13 @@ wasm-sudo = ["test-tube/wasm-sudo"]
#test-tube = { version = "0.8.0" }
# Working on newest version
test-tube = { git = "https://github.com/osmosis-labs/test-tube.git", rev = "9688c23" }
archway-proto = { git = "https://github.com/archway-network/arch3.rs.git", branch = "fix/abstract-any-proto-encoding-fix" }
archway-proto = { version = "0.2.1" }
pbjson-types = "0.7.0"
prost-types = "0.13.3"
cosmwasm-std = { version = "2.1", features = ["stargate"] }
# Used for conversion for coin
cosmwasm-std-legacy = { version = "1.5.5", package = "cosmwasm-std" }

prost = "0.13.3"
serde = "1.0"
serde_json = "1.0"
Expand Down
6 changes: 6 additions & 0 deletions packages/chain/libarchway/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -480,5 +480,11 @@ func encodeBytesResultBytes(bytes []byte) *C.char {
return C.CString(result.EncodeResultFromOk(bytes))
}

func requireNoErr(err error) {
if err != nil {
panic(err)
}
}

// must define main for ffi build
func main() {}
46 changes: 36 additions & 10 deletions packages/chain/libarchway/testenv/setup.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,8 @@ import (
simtestutil "github.com/cosmos/cosmos-sdk/testutil/sims"
sdk "github.com/cosmos/cosmos-sdk/types"
banktestutil "github.com/cosmos/cosmos-sdk/x/bank/testutil"
distributiontypes "github.com/cosmos/cosmos-sdk/x/distribution/types"
minttypes "github.com/cosmos/cosmos-sdk/x/mint/types"
slashingtypes "github.com/cosmos/cosmos-sdk/x/slashing/types"
stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types"

Expand Down Expand Up @@ -75,16 +77,19 @@ func GenesisStateWithValSet(appInstance *app.ArchwayApp) (app.GenesisState, secp
pk, _ := cryptocodec.FromTmPubKeyInterface(val.PubKey)
pkAny, _ := codectypes.NewAnyWithValue(pk)
validator := stakingtypes.Validator{
OperatorAddress: sdk.ValAddress(val.Address).String(),
ConsensusPubkey: pkAny,
Jailed: false,
Status: stakingtypes.Bonded,
Tokens: bondAmt,
DelegatorShares: sdkmath.LegacyOneDec(),
Description: stakingtypes.Description{},
UnbondingHeight: int64(0),
UnbondingTime: time.Unix(0, 0).UTC(),
Commission: stakingtypes.NewCommission(sdkmath.LegacyZeroDec(), sdkmath.LegacyZeroDec(), sdkmath.LegacyZeroDec()),
OperatorAddress: sdk.ValAddress(val.Address).String(),
ConsensusPubkey: pkAny,
Jailed: false,
Status: stakingtypes.Bonded,
Tokens: bondAmt,
DelegatorShares: sdkmath.LegacyOneDec(),
Description: stakingtypes.Description{},
UnbondingHeight: int64(0),
UnbondingTime: time.Unix(0, 0).UTC(),
Commission: stakingtypes.NewCommission(sdkmath.LegacyNewDecWithPrec(5, 2), // 5% rate
sdkmath.LegacyNewDecWithPrec(20, 2), // 20% max rate
sdkmath.LegacyNewDecWithPrec(1, 2), // 1% max change rate
),
MinSelfDelegation: sdkmath.ZeroInt(),
}
validators = append(validators, validator)
Expand All @@ -101,6 +106,27 @@ func GenesisStateWithValSet(appInstance *app.ArchwayApp) (app.GenesisState, secp
stakingGenesis := stakingtypes.NewGenesisState(stakingtypes.DefaultParams(), validators, delegations)
genesisState[stakingtypes.ModuleName] = appInstance.AppCodec().MustMarshalJSON(stakingGenesis)

// Set rewards
mintGenesis := minttypes.NewGenesisState(minttypes.DefaultInitialMinter(), minttypes.DefaultParams())
mintGenesis.Params.MintDenom = "aarch"
mintGenesis.Params.InflationMin = sdkmath.LegacyNewDecWithPrec(7, 2) // 7%
mintGenesis.Params.InflationMax = sdkmath.LegacyNewDecWithPrec(20, 2) // 20%
mintGenesis.Params.InflationRateChange = sdkmath.LegacyNewDecWithPrec(13, 2) // 13%
mintGenesis.Params.GoalBonded = sdkmath.LegacyNewDecWithPrec(67, 2) // 67%
mintGenesis.Minter.Inflation = sdkmath.LegacyNewDecWithPrec(13, 2) // 13%
mintGenesis.Minter.AnnualProvisions = sdkmath.LegacyNewDec(0)
genesisState[minttypes.ModuleName] = appInstance.AppCodec().MustMarshalJSON(mintGenesis)

// Set distribution just in case
distributionGenesis := distributiontypes.DefaultGenesisState()
distributionGenesis.Params = distributiontypes.Params{
CommunityTax: sdkmath.LegacyNewDecWithPrec(2, 2), // 2%
BaseProposerReward: sdkmath.LegacyNewDecWithPrec(1, 2), // 1%
BonusProposerReward: sdkmath.LegacyNewDecWithPrec(4, 2), // 4%
WithdrawAddrEnabled: true,
}
genesisState[distributiontypes.ModuleName] = appInstance.AppCodec().MustMarshalJSON(distributionGenesis)

totalSupply := sdk.NewCoins()
for _, b := range balances {
// add genesis acc tokens to total supply
Expand Down
16 changes: 16 additions & 0 deletions packages/chain/src/coin_compat.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
use archway_proto::cosmos::base::v1beta1::Coin as ProtoCoin;
use cosmwasm_std::{Coin, Uint128};

pub fn from_legacy(coin: &cosmwasm_std_legacy::Coin) -> Coin {
Coin {
denom: coin.denom.clone(),
amount: Uint128::from(coin.amount.u128()),
}
}

pub fn to_proto(coin: &Coin) -> ProtoCoin {
ProtoCoin {
denom: coin.denom.clone(),
amount: coin.amount.to_string(),
}
}
96 changes: 91 additions & 5 deletions packages/chain/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,14 +1,17 @@
mod bindings;
mod coin_compat;
pub mod module;

pub use archway_proto;
use cosmrs::proto::tendermint::abci::ResponseFinalizeBlock;
pub use cosmwasm_std;
use std::ffi::CString;
use std::str::FromStr;

use crate::bindings::SkipBlock;
use base64::engine::general_purpose::STANDARD as BASE64_STANDARD;
use base64::Engine;
pub use coin_compat::*;
use cosmrs::Any;
use cosmwasm_std::Coin;
use prost::Message;
Expand Down Expand Up @@ -402,14 +405,15 @@ impl<'a> Runner<'a> for ArchwayApp {

#[cfg(test)]
mod tests {
use crate::module::{Authz, Distribution, Staking, Wasm};
use crate::{arch, to_proto, ArchwayApp};
use archway_proto::cosmos::distribution::v1beta1::MsgWithdrawDelegatorReward;
use archway_proto::cosmos::staking::v1beta1::{AuthorizationType, MsgDelegate};
use cosmwasm_schema::cw_serde;
use std::option::Option::None;

use cosmwasm_std::{coins, Coin};
use prost::Name;
use serde::Serialize;

use crate::module::Wasm;
use crate::{arch, ArchwayApp};
use std::option::Option::None;
use test_tube::account::Account;
use test_tube::module::Module;

Expand Down Expand Up @@ -641,6 +645,35 @@ mod tests {
assert!(admin_list.mutable);
}

#[test]
fn test_authz() {
let app = ArchwayApp::default();
let accounts = app.init_accounts(&[arch(100)], 2).unwrap();
let grantee = accounts.get(0).unwrap();
let granter = accounts.get(1).unwrap();

let authz = Authz::new(&app);
authz
.grant_generic(
&granter,
grantee.address(),
MsgWithdrawDelegatorReward::type_url(),
None,
)
.unwrap();

authz
.grant_stake(
&granter,
grantee.address(),
AuthorizationType::Delegate,
None,
None,
None,
)
.unwrap();
}

#[test]
fn test_block_skipping() {
let app = ArchwayApp::default();
Expand All @@ -655,4 +688,57 @@ mod tests {

assert_eq!(app.get_block_height(), 7i64);
}

#[test]
fn test_delegating() {
let app = ArchwayApp::default();
let staking = Staking::new(&app);

// let validator = app.get_first_validator_signing_account().unwrap();
let vals = staking.validators(None, None).unwrap();
let validator = vals.validators.first().unwrap().to_owned();
let validator_addr = validator.operator_address;
dbg!(&validator.delegator_shares);
let delegator = app.init_account(&[arch(100)]).unwrap();

let delegation = arch(10);
staking
.delegate(
MsgDelegate {
delegator_address: delegator.address(),
validator_address: validator_addr.clone(),
amount: Some(to_proto(&delegation)),
},
&delegator,
)
.unwrap();

let res = staking
.delegation(delegator.address(), validator_addr.clone())
.unwrap()
.delegation_response
.unwrap()
.balance
.unwrap()
.amount
.parse::<u128>()
.unwrap();
assert_eq!(res, delegation.amount.u128());

app.skip_blocks(1000);

let distribution = Distribution::new(&app);
let res = distribution
.delegation_rewards(delegator.address(), validator_addr)
.unwrap();
dbg!(&res);
let vals = staking
.validators(None, None)
.unwrap()
.validators
.first()
.unwrap()
.to_owned();
dbg!(&vals.delegator_shares);
}
}
127 changes: 127 additions & 0 deletions packages/chain/src/module/authz.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,127 @@
use archway_proto::cosmos::authz::v1beta1::{
GenericAuthorization, Grant, MsgExec, MsgExecResponse, MsgGrant, MsgGrantResponse,
};
use archway_proto::cosmos::bank::v1beta1::SendAuthorization;
use archway_proto::cosmos::staking::v1beta1::stake_authorization::Policy;
use archway_proto::cosmos::staking::v1beta1::{AuthorizationType, StakeAuthorization};
use archway_proto::tendermint::google::protobuf::{Any, Timestamp};
use cosmwasm_std::Coin;
use prost::Name;
use test_tube::cosmrs::tx::MessageExt;
use test_tube::{
fn_execute, Account, Module, Runner, RunnerError, RunnerExecuteResult, SigningAccount,
};

pub struct Authz<'a, R: Runner<'a>> {
runner: &'a R,
}

impl<'a, R: Runner<'a>> Module<'a, R> for Authz<'a, R> {
fn new(runner: &'a R) -> Self {
Self { runner }
}
}

impl<'a, R> Authz<'a, R>
where
R: Runner<'a>,
{
fn_execute! {
pub exec: MsgExec["/cosmos.authz.v1beta1.MsgExec"] => MsgExecResponse
}

fn_execute! {
pub _grant: MsgGrant["/cosmos.authz.v1beta1.MsgGrant"] => MsgGrantResponse
}

pub fn grant<T>(
&self,
signer: &SigningAccount,
grantee: impl Into<String>,
msg: T,
expiration: Option<Timestamp>,
) -> RunnerExecuteResult<MsgGrantResponse>
where
T: Name + MessageExt,
{
let granter = signer.address();
let msg = MsgGrant {
granter,
grantee: grantee.into(),
grant: Some(Grant {
authorization: Some(Any {
type_url: T::type_url(),
value: msg
.to_bytes()
.map_err(|e| RunnerError::EncodeError(e.into()))?,
}),
expiration,
}),
};
self._grant(msg, signer)
}

pub fn grant_generic(
&self,
signer: &SigningAccount,
grantee: impl Into<String>,
authorized_msg: String,
expiration: Option<Timestamp>,
) -> RunnerExecuteResult<MsgGrantResponse> {
self.grant(
signer,
grantee,
GenericAuthorization {
msg: authorized_msg,
},
expiration,
)
}

pub fn grant_stake(
&self,
signer: &SigningAccount,
grantee: impl Into<String>,
auth_type: AuthorizationType,
max_tokens: Option<Coin>,
validators: Option<Policy>,
expiration: Option<Timestamp>,
) -> RunnerExecuteResult<MsgGrantResponse> {
self.grant(
signer,
grantee,
StakeAuthorization {
max_tokens: max_tokens.map(|c| coin_to_proto_coin(&c)),
authorization_type: auth_type.into(),
validators,
},
expiration,
)
}

pub fn grant_send(
&self,
signer: &SigningAccount,
grantee: impl Into<String>,
allow_list: Vec<String>,
spend_limit: Vec<Coin>,
expiration: Option<Timestamp>,
) -> RunnerExecuteResult<MsgGrantResponse> {
self.grant(
signer,
grantee,
SendAuthorization {
spend_limit: spend_limit.iter().map(|c| coin_to_proto_coin(c)).collect(),
allow_list,
},
expiration,
)
}
}

fn coin_to_proto_coin(coin: &Coin) -> archway_proto::cosmos::base::v1beta1::Coin {
archway_proto::cosmos::base::v1beta1::Coin {
denom: coin.denom.clone(),
amount: coin.amount.to_string(),
}
}
13 changes: 12 additions & 1 deletion packages/chain/src/module/bank.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ use archway_proto::cosmos::bank::v1beta1::{
QueryBalanceRequest, QueryBalanceResponse, QueryDenomsMetadataRequest,
QueryDenomsMetadataResponse, QueryTotalSupplyRequest, QueryTotalSupplyResponse,
};
use test_tube::{fn_execute, fn_query, Module, Runner};
use test_tube::{fn_execute, fn_query, Module, Runner, RunnerResult};

pub struct Bank<'a, R: Runner<'a>> {
runner: &'a R,
Expand Down Expand Up @@ -38,4 +38,15 @@ where
fn_query! {
pub query_denoms_metadata ["/cosmos.bank.v1beta1.Query/DenomsMetadata"]: QueryDenomsMetadataRequest => QueryDenomsMetadataResponse
}

pub fn balance(
&self,
address: impl Into<String>,
denom: impl Into<String>,
) -> RunnerResult<QueryBalanceResponse> {
self.query_balance(&QueryBalanceRequest {
address: address.into(),
denom: denom.into(),
})
}
}
Loading

0 comments on commit 6d077c7

Please sign in to comment.