Skip to content

Commit

Permalink
chore: final refactor
Browse files Browse the repository at this point in the history
  • Loading branch information
kerber0x committed May 17, 2024
1 parent ca3db75 commit 6df2793
Show file tree
Hide file tree
Showing 9 changed files with 94 additions and 47 deletions.
32 changes: 22 additions & 10 deletions contracts/liquidity_hub/bonding-manager/schema/bonding-manager.json
Original file line number Diff line number Diff line change
Expand Up @@ -592,21 +592,12 @@
],
"properties": {
"bonded_assets": {
"description": "The total amount of bonded assets by the address.",
"description": "The assets that are bonded by the address.",
"type": "array",
"items": {
"$ref": "#/definitions/Coin"
}
},
"first_bonded_epoch_id": {
"description": "If Some, the epoch id at which the user/address bonded first time. None is used when this Response is used to check the bonded assets in the contract.",
"type": [
"integer",
"null"
],
"format": "uint64",
"minimum": 0.0
},
"total_bonded": {
"description": "The total amount of bonded tokens by the address. Bear in mind the bonded assets are considered to be equal for this purpose.",
"allOf": [
Expand Down Expand Up @@ -642,6 +633,7 @@
"claimable": {
"$schema": "http://json-schema.org/draft-07/schema#",
"title": "ClaimableRewardBucketsResponse",
"description": "Response for the Claimable query",
"type": "object",
"required": [
"reward_buckets"
Expand Down Expand Up @@ -1089,12 +1081,18 @@
},
"additionalProperties": false,
"definitions": {
"Addr": {
"description": "A human readable address.\n\nIn Cosmos, this is typically bech32 encoded. But for multi-chain smart contracts no assumptions should be made other than being UTF-8 encoded and of reasonable length.\n\nThis type represents a validated address. It can be created in the following ways 1. Use `Addr::unchecked(input)` 2. Use `let checked: Addr = deps.api.addr_validate(input)?` 3. Use `let checked: Addr = deps.api.addr_humanize(canonical_addr)?` 4. Deserialize from JSON. This must only be done from JSON that was validated before such as a contract's state. `Addr` must not be used in messages sent by the user because this would result in unvalidated instances.\n\nThis type is immutable. If you really need to mutate it (Really? Are you sure?), create a mutable copy using `let mut mutable = Addr::to_string()` and operate on that `String` instance.",
"type": "string"
},
"Bond": {
"type": "object",
"required": [
"asset",
"created_at_epoch",
"id",
"last_updated",
"receiver",
"weight"
],
"properties": {
Expand All @@ -1112,12 +1110,26 @@
"format": "uint64",
"minimum": 0.0
},
"id": {
"description": "The id of the bond.",
"type": "integer",
"format": "uint64",
"minimum": 0.0
},
"last_updated": {
"description": "The epoch id at which the bond was last time updated.",
"type": "integer",
"format": "uint64",
"minimum": 0.0
},
"receiver": {
"description": "The owner of the bond.",
"allOf": [
{
"$ref": "#/definitions/Addr"
}
]
},
"unbonded_at": {
"description": "The time at which the Bond was unbonded.",
"type": [
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,21 +9,12 @@
],
"properties": {
"bonded_assets": {
"description": "The total amount of bonded assets by the address.",
"description": "The assets that are bonded by the address.",
"type": "array",
"items": {
"$ref": "#/definitions/Coin"
}
},
"first_bonded_epoch_id": {
"description": "If Some, the epoch id at which the user/address bonded first time. None is used when this Response is used to check the bonded assets in the contract.",
"type": [
"integer",
"null"
],
"format": "uint64",
"minimum": 0.0
},
"total_bonded": {
"description": "The total amount of bonded tokens by the address. Bear in mind the bonded assets are considered to be equal for this purpose.",
"allOf": [
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
{
"$schema": "http://json-schema.org/draft-07/schema#",
"title": "ClaimableRewardBucketsResponse",
"description": "Response for the Claimable query",
"type": "object",
"required": [
"reward_buckets"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,12 +26,18 @@
},
"additionalProperties": false,
"definitions": {
"Addr": {
"description": "A human readable address.\n\nIn Cosmos, this is typically bech32 encoded. But for multi-chain smart contracts no assumptions should be made other than being UTF-8 encoded and of reasonable length.\n\nThis type represents a validated address. It can be created in the following ways 1. Use `Addr::unchecked(input)` 2. Use `let checked: Addr = deps.api.addr_validate(input)?` 3. Use `let checked: Addr = deps.api.addr_humanize(canonical_addr)?` 4. Deserialize from JSON. This must only be done from JSON that was validated before such as a contract's state. `Addr` must not be used in messages sent by the user because this would result in unvalidated instances.\n\nThis type is immutable. If you really need to mutate it (Really? Are you sure?), create a mutable copy using `let mut mutable = Addr::to_string()` and operate on that `String` instance.",
"type": "string"
},
"Bond": {
"type": "object",
"required": [
"asset",
"created_at_epoch",
"id",
"last_updated",
"receiver",
"weight"
],
"properties": {
Expand All @@ -49,12 +55,26 @@
"format": "uint64",
"minimum": 0.0
},
"id": {
"description": "The id of the bond.",
"type": "integer",
"format": "uint64",
"minimum": 0.0
},
"last_updated": {
"description": "The epoch id at which the bond was last time updated.",
"type": "integer",
"format": "uint64",
"minimum": 0.0
},
"receiver": {
"description": "The owner of the bond.",
"allOf": [
{
"$ref": "#/definitions/Addr"
}
]
},
"unbonded_at": {
"description": "The time at which the Bond was unbonded.",
"type": [
Expand Down
30 changes: 15 additions & 15 deletions contracts/liquidity_hub/bonding-manager/src/bonding/commands.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ pub(crate) fn bond(
&white_whale_std::epoch_manager::epoch_manager::QueryMsg::CurrentEpoch {},
)?;

let mut bonds_by_receiver = get_bonds_by_receiver(
let bonds_by_receiver = get_bonds_by_receiver(
deps.storage,
info.sender.to_string(),
Some(true),
Expand All @@ -40,7 +40,8 @@ pub(crate) fn bond(
)?;

let mut bond = if bonds_by_receiver.is_empty() {
// create bond id
// the user doesn't have any bonds of the given asset

let bond_id =
BOND_COUNTER.update::<_, StdError>(deps.storage, |current_id| Ok(current_id + 1u64))?;

Expand All @@ -56,16 +57,13 @@ pub(crate) fn bond(
..Bond::default()
}
} else {
// sanity check
ensure!(
bonds_by_receiver.len() == 1usize,
//todo change this error
ContractError::NothingToUnbond
ContractError::AssetMismatch

Check warning on line 63 in contracts/liquidity_hub/bonding-manager/src/bonding/commands.rs

View check run for this annotation

Codecov / codecov/patch

contracts/liquidity_hub/bonding-manager/src/bonding/commands.rs#L63

Added line #L63 was not covered by tests
);

//todo change this error
bonds_by_receiver
.pop()
.ok_or(ContractError::NothingToUnbond)?
bonds_by_receiver[0].clone()
};

// update bond values
Expand Down Expand Up @@ -110,7 +108,7 @@ pub(crate) fn unbond(
helpers::validate_claimed(&deps, &info)?;
helpers::validate_bonding_for_current_epoch(&deps)?;

let mut bonds_by_receiver = get_bonds_by_receiver(
let bonds_by_receiver = get_bonds_by_receiver(
deps.storage,
info.sender.to_string(),
Some(true),
Expand All @@ -121,17 +119,19 @@ pub(crate) fn unbond(

ensure!(
bonds_by_receiver.len() <= 1usize,
//todo change this error
ContractError::NothingToUnbond
ContractError::AssetMismatch

Check warning on line 122 in contracts/liquidity_hub/bonding-manager/src/bonding/commands.rs

View check run for this annotation

Codecov / codecov/patch

contracts/liquidity_hub/bonding-manager/src/bonding/commands.rs#L122

Added line #L122 was not covered by tests
);

if bonds_by_receiver.is_empty() {
Err(ContractError::NothingToUnbond)
} else {
//todo change this error
let mut unbond: Bond = bonds_by_receiver
.pop()
.ok_or(ContractError::NothingToUnbond)?;
// sanity check
ensure!(
bonds_by_receiver.len() == 1usize,
ContractError::AssetMismatch

Check warning on line 131 in contracts/liquidity_hub/bonding-manager/src/bonding/commands.rs

View check run for this annotation

Codecov / codecov/patch

contracts/liquidity_hub/bonding-manager/src/bonding/commands.rs#L131

Added line #L131 was not covered by tests
);

let mut unbond = bonds_by_receiver[0].clone();

// check if the address has enough bond
ensure!(
Expand Down
2 changes: 1 addition & 1 deletion contracts/liquidity_hub/bonding-manager/src/contract.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ pub fn instantiate(
CONFIG.save(deps.storage, &config)?;
cw_ownable::initialize_owner(deps.storage, deps.api, Some(info.sender.as_str()))?;

// Initialize the upcoming reward bucket
// Initialize the upcoming reward bucket and bond counter
UPCOMING_REWARD_BUCKET.save(deps.storage, &UpcomingRewardBucket::default())?;
BOND_COUNTER.save(deps.storage, &0)?;

Expand Down
1 change: 0 additions & 1 deletion contracts/liquidity_hub/bonding-manager/src/queries.rs
Original file line number Diff line number Diff line change
Expand Up @@ -166,7 +166,6 @@ pub fn query_claimable(
claimable_reward_buckets.retain(|bucket| !bucket.available.is_empty());
}

println!("here: {:?}", claimable_reward_buckets);
Ok(ClaimableRewardBucketsResponse {
reward_buckets: claimable_reward_buckets,
})
Expand Down
10 changes: 1 addition & 9 deletions contracts/liquidity_hub/bonding-manager/src/state.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,22 +16,16 @@ pub const BONDS: IndexedMap<u64, Bond, BondIndexes> = IndexedMap::new(
"bonds",
BondIndexes {
receiver: MultiIndex::new(|_pk, b| b.receiver.to_string(), "bonds", "bonds__receiver"),
asset_denom: MultiIndex::new(
|_pk, b| b.asset.denom.to_string(),
"bonds",
"bonds__asset_denom",
),
},
);

pub struct BondIndexes<'a> {
pub receiver: MultiIndex<'a, String, Bond, String>,
pub asset_denom: MultiIndex<'a, String, Bond, String>,
}

impl<'a> IndexList<Bond> for BondIndexes<'a> {
fn get_indexes(&'_ self) -> Box<dyn Iterator<Item = &'_ dyn Index<Bond>> + '_> {
let v: Vec<&dyn Index<Bond>> = vec![&self.receiver, &self.asset_denom];
let v: Vec<&dyn Index<Bond>> = vec![&self.receiver];
Box::new(v.into_iter())
}
}
Expand Down Expand Up @@ -137,8 +131,6 @@ pub fn get_bonds_by_receiver(
})
.collect::<StdResult<Vec<Bond>>>()?;

println!("bonds_by_receiver: {:?}", bonds_by_receiver);

if let Some(is_bonding) = is_bonding {
bonds_by_receiver.retain(|bond| bond.unbonded_at.is_none() == is_bonding);
}
Expand Down
34 changes: 33 additions & 1 deletion contracts/liquidity_hub/bonding-manager/src/tests/bond.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
use cosmwasm_std::{coin, coins};

use crate::tests::suite::TestingSuite;
use crate::ContractError;
use cosmwasm_std::{coin, coins};

#[test]
fn test_bond_unsuccessful() {
Expand Down Expand Up @@ -48,3 +49,34 @@ fn test_bond_unsuccessful() {
},
);
}

#[test]
fn test_same_bond_multiple_times() {
let mut suite = TestingSuite::default();
let creator = suite.senders[0].clone();

suite
.instantiate_default()
.add_one_day()
.create_new_epoch()
.bond(
creator.clone(),
&vec![coin(1_000u128, "bWHALE")],
|result| {
result.unwrap();
},
)
.bond(
creator.clone(),
&vec![coin(2_000u128, "bWHALE")],
|result| {
result.unwrap();
},
)
.query_bonded(Some(creator.clone().to_string()), |res| {
assert_eq!(
res.unwrap().1.bonded_assets,
vec![coin(3_000u128, "bWHALE")]
);
});
}

0 comments on commit 6df2793

Please sign in to comment.