feat: multiple deposit prices (#6608)

* added reduced pricing handling logic

* admin methods for setting the whitelist of reduced price accounts

* updated client traits

* query to get all whitelisted accounts

* query for getting detailed deposit statistics

* fixes

* set initial whitelisted accounts in the migration

* stop transferring tokens to the holding account after redemption

* stop gateways from creating redemption multisig proposals

* make sure credential-proxy uses reduced deposits when available

* cargo fmt

* update deposit handler to allow EITHER default price or reduced price

this will allow non-breaking upgrades of NS and credential proxy

* removed use of unstable rust features

* rebuilt contract schema

* correct license timestamp
This commit is contained in:
Jędrzej Stuczyński
2026-03-26 16:02:19 +00:00
committed by GitHub
parent 82ace6d27b
commit 6581ebf235
38 changed files with 2529 additions and 1060 deletions
@@ -34,7 +34,7 @@ where
let signing_key = ed25519::PrivateKey::new(&mut rng);
let expiration = expiration.unwrap_or_else(ecash_default_expiration_date);
let deposit_amount = client.get_required_deposit_amount().await?;
let deposit_amount = client.get_default_deposit_amount().await?;
info!("we'll need to deposit {deposit_amount} to obtain the ticketbook");
let result = client
.make_ticketbook_deposit(
@@ -8,6 +8,7 @@ use crate::nyxd::CosmWasmClient;
use async_trait::async_trait;
use cosmwasm_std::Coin;
use nym_ecash_contract_common::deposit::LatestDepositResponse;
use nym_ecash_contract_common::deposit_statistics::DepositsStatistics;
use nym_ecash_contract_common::msg::QueryMsg as EcashQueryMsg;
use serde::Deserialize;
@@ -17,6 +18,9 @@ pub use nym_ecash_contract_common::blacklist::{
pub use nym_ecash_contract_common::deposit::{
Deposit, DepositData, DepositId, DepositResponse, PagedDepositsResponse,
};
pub use nym_ecash_contract_common::reduced_deposit::{
WhitelistedAccount, WhitelistedAccountsResponse,
};
#[cfg_attr(target_arch = "wasm32", async_trait(?Send))]
#[cfg_attr(not(target_arch = "wasm32"), async_trait)]
@@ -42,8 +46,18 @@ pub trait EcashQueryClient {
.await
}
async fn get_required_deposit_amount(&self) -> Result<Coin, NyxdError> {
self.query_ecash_contract(EcashQueryMsg::GetRequiredDepositAmount {})
async fn get_default_deposit_amount(&self) -> Result<Coin, NyxdError> {
self.query_ecash_contract(EcashQueryMsg::GetDefaultDepositAmount {})
.await
}
async fn get_reduced_deposit_amount(&self, address: String) -> Result<Option<Coin>, NyxdError> {
self.query_ecash_contract(EcashQueryMsg::GetReducedDepositAmount { address })
.await
}
async fn get_all_whitelisted_accounts(&self) -> Result<WhitelistedAccountsResponse, NyxdError> {
self.query_ecash_contract(EcashQueryMsg::GetAllWhitelistedAccounts {})
.await
}
@@ -65,6 +79,11 @@ pub trait EcashQueryClient {
self.query_ecash_contract(EcashQueryMsg::GetDepositsPaged { start_after, limit })
.await
}
async fn get_deposits_statistics(&self) -> Result<DepositsStatistics, NyxdError> {
self.query_ecash_contract(EcashQueryMsg::GetDepositsStatistics {})
.await
}
}
#[cfg_attr(target_arch = "wasm32", async_trait(?Send))]
@@ -122,10 +141,17 @@ mod tests {
EcashQueryMsg::GetDepositsPaged { limit, start_after } => {
client.get_deposits_paged(start_after, limit).ignore()
}
EcashQueryMsg::GetRequiredDepositAmount {} => {
client.get_required_deposit_amount().ignore()
EcashQueryMsg::GetDefaultDepositAmount {} => {
client.get_default_deposit_amount().ignore()
}
EcashQueryMsg::GetReducedDepositAmount { address } => {
client.get_reduced_deposit_amount(address).ignore()
}
EcashQueryMsg::GetAllWhitelistedAccounts {} => {
client.get_all_whitelisted_accounts().ignore()
}
EcashQueryMsg::GetLatestDeposit {} => client.get_latest_deposit().ignore(),
EcashQueryMsg::GetDepositsStatistics {} => client.get_deposits_statistics().ignore(),
};
}
}
@@ -62,13 +62,47 @@ pub trait EcashSigningClient {
new_deposit: Coin,
fee: Option<Fee>,
) -> Result<ExecuteResult, NyxdError> {
let req = EcashExecuteMsg::UpdateDepositValue {
let req = EcashExecuteMsg::UpdateDefaultDepositValue {
new_deposit: new_deposit.into(),
};
self.execute_ecash_contract(fee, req, "Ecash::UpdateDepositValue".to_string(), vec![])
.await
}
async fn set_reduced_deposit_price(
&self,
address: String,
deposit: Coin,
fee: Option<Fee>,
) -> Result<ExecuteResult, NyxdError> {
let req = EcashExecuteMsg::SetReducedDepositPrice {
address,
deposit: deposit.into(),
};
self.execute_ecash_contract(
fee,
req,
"Ecash::SetReducedDepositPrice".to_string(),
vec![],
)
.await
}
async fn remove_reduced_deposit_price(
&self,
address: String,
fee: Option<Fee>,
) -> Result<ExecuteResult, NyxdError> {
let req = EcashExecuteMsg::RemoveReducedDepositPrice { address };
self.execute_ecash_contract(
fee,
req,
"Ecash::RemoveReducedDepositPrice".to_string(),
vec![],
)
.await
}
async fn propose_for_blacklist(
&self,
public_key: String,
@@ -141,9 +175,15 @@ mod tests {
.ignore(),
ExecuteMsg::RedeemTickets { .. } => unimplemented!(), // no redeem tickets method for the client
ExecuteMsg::UpdateAdmin { admin } => client.update_admin(admin, None).ignore(),
ExecuteMsg::UpdateDepositValue { new_deposit } => client
ExecuteMsg::UpdateDefaultDepositValue { new_deposit } => client
.update_deposit_value(new_deposit.into(), None)
.ignore(),
ExecuteMsg::SetReducedDepositPrice { address, deposit } => client
.set_reduced_deposit_price(address, deposit.into(), None)
.ignore(),
ExecuteMsg::RemoveReducedDepositPrice { address } => {
client.remove_reduced_deposit_price(address, None).ignore()
}
};
}
}
@@ -6,6 +6,13 @@ use cosmwasm_std::Coin;
#[cw_serde]
pub struct PoolCounters {
/// Represents the total amount of funds deposited into the contract.
pub total_deposited: Coin,
/// Represents the total amount of funds redeemed from the contract that got transferred into the holding account.
pub total_redeemed: Coin,
/// Represents the total amount of tickets requested to be redeemed from the contract and get moved into the holding account,
/// after that functionality got disabled.
pub tickets_requested_and_not_redeemed: u64,
}
@@ -0,0 +1,38 @@
// Copyright 2026 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0
use cosmwasm_schema::cw_serde;
use cosmwasm_std::Coin;
use std::collections::HashMap;
/// Aggregate statistics about all deposits made through the ecash contract.
#[cw_serde]
pub struct DepositsStatistics {
/// Total number of deposits ever made (at any price tier),
/// derived from the deposit id counter.
pub total_deposits_made: u32,
/// Total value of all deposits ever made (at any price tier),
/// sourced from `PoolCounters::total_deposited`.
pub total_deposited: Coin,
/// Number of deposits made at the default (non-reduced) price.
pub total_deposits_made_with_default_price: u32,
/// Total value deposited at the default price.
pub total_deposited_with_default_price: Coin,
/// Number of deposits made at any custom (reduced) price, summed across all whitelisted accounts.
pub total_deposits_made_with_custom_price: u32,
/// Total value deposited at custom prices, summed across all whitelisted accounts.
pub total_deposited_with_custom_price: Coin,
/// Per-account breakdown of deposit counts for whitelisted addresses.
// note: we use String for addressing due to serialisation incompatibility
pub deposits_made_with_custom_price: HashMap<String, u32>,
/// Per-account breakdown of deposited amounts for whitelisted addresses.
// note: we use String for addressing due to serialisation incompatibility
pub deposited_with_custom_price: HashMap<String, Coin>,
}
@@ -65,4 +65,26 @@ pub enum EcashContractError {
#[error("the account blacklisting hasn't been fully implemented yet")]
UnimplementedBlacklisting,
#[error("reduced deposit must use the same denom as the default deposit (expected '{expected}', got '{got}')")]
InvalidReducedDepositDenom { expected: String, got: String },
#[error(
"reduced deposit amount ({reduced}) must be strictly less than the default ({default})"
)]
ReducedDepositNotReduced {
reduced: cosmwasm_std::Uint128,
default: cosmwasm_std::Uint128,
},
#[error("address '{address}' does not have a custom reduced deposit price set")]
NoReducedDepositPrice { address: String },
#[error(
"deposit amount ({amount}) must be at least the ticket book size ({ticket_book_size})"
)]
DepositBelowTicketBookSize {
amount: cosmwasm_std::Uint128,
ticket_book_size: u64,
},
}
@@ -4,10 +4,12 @@
pub mod blacklist;
pub mod counters;
pub mod deposit;
pub mod deposit_statistics;
pub mod error;
pub mod event_attributes;
pub mod events;
pub mod msg;
pub mod redeem_credential;
pub mod reduced_deposit;
pub use error::EcashContractError;
@@ -9,6 +9,10 @@ use crate::blacklist::{BlacklistedAccountResponse, PagedBlacklistedAccountRespon
#[cfg(feature = "schema")]
use crate::deposit::{DepositResponse, LatestDepositResponse, PagedDepositsResponse};
#[cfg(feature = "schema")]
use crate::deposit_statistics::DepositsStatistics;
#[cfg(feature = "schema")]
use crate::reduced_deposit::WhitelistedAccountsResponse;
#[cfg(feature = "schema")]
use cosmwasm_schema::QueryResponses;
#[cw_serde]
@@ -42,10 +46,25 @@ pub enum ExecuteMsg {
admin: String,
},
UpdateDepositValue {
#[serde(alias = "update_deposit_value")]
UpdateDefaultDepositValue {
new_deposit: Coin,
},
/// Set (or overwrite) a reduced deposit price for a specific address.
/// Only callable by the contract admin.
SetReducedDepositPrice {
address: String,
deposit: Coin,
},
/// Remove the reduced deposit price for a specific address, reverting them to
/// the default price. Returns an error if the address has no custom price set.
/// Only callable by the contract admin.
RemoveReducedDepositPrice {
address: String,
},
// TODO: properly implement
ProposeToBlacklist {
public_key: String,
@@ -68,7 +87,15 @@ pub enum QueryMsg {
},
#[cfg_attr(feature = "schema", returns(Coin))]
GetRequiredDepositAmount {},
#[serde(alias = "get_required_deposit_amount")]
#[serde(alias = "GetRequiredDepositAmount")]
GetDefaultDepositAmount {},
#[cfg_attr(feature = "schema", returns(Option<Coin>))]
GetReducedDepositAmount { address: String },
#[cfg_attr(feature = "schema", returns(WhitelistedAccountsResponse))]
GetAllWhitelistedAccounts {},
#[cfg_attr(feature = "schema", returns(DepositResponse))]
GetDeposit { deposit_id: u32 },
@@ -81,7 +108,22 @@ pub enum QueryMsg {
limit: Option<u32>,
start_after: Option<u32>,
},
#[cfg_attr(feature = "schema", returns(DepositsStatistics))]
GetDepositsStatistics {},
}
#[cw_serde]
pub struct MigrateMsg {}
pub struct MigrateMsg {
/// Initial set of whitelisted accounts with their reduced deposit prices.
/// Each entry is validated and stored during migration.
pub initial_whitelist: Vec<WhitelistedDeposit>,
}
/// An address and its reduced deposit price, used when seeding the whitelist
/// via migration.
#[cw_serde]
pub struct WhitelistedDeposit {
pub address: String,
pub deposit: Coin,
}
@@ -0,0 +1,16 @@
// Copyright 2026 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0
use cosmwasm_schema::cw_serde;
use cosmwasm_std::{Addr, Coin};
#[cw_serde]
pub struct WhitelistedAccount {
pub address: Addr,
pub deposit: Coin,
}
#[cw_serde]
pub struct WhitelistedAccountsResponse {
pub whitelisted_accounts: Vec<WhitelistedAccount>,
}
@@ -6,7 +6,7 @@ use crate::helpers::LockTimer;
use nym_ecash_contract_common::msg::ExecuteMsg;
use nym_validator_client::nyxd::contract_traits::NymContractsProvider;
use nym_validator_client::nyxd::cosmwasm_client::types::ExecuteResult;
use nym_validator_client::nyxd::{Coin, Config, CosmWasmClient, NyxdClient};
use nym_validator_client::nyxd::{AccountId, Coin, Config, CosmWasmClient, NyxdClient};
use nym_validator_client::{DirectSigningHttpRpcNyxdClient, nyxd};
use std::ops::Deref;
use std::sync::Arc;
@@ -50,6 +50,10 @@ impl ChainClient {
Ok(ChainClient(Arc::new(RwLock::new(client))))
}
pub async fn address(&self) -> AccountId {
self.0.read().await.address()
}
pub async fn query_chain(&self) -> ChainReadPermit<'_> {
let _acquire_timer = LockTimer::new("acquire chain query permit");
self.0.read().await
@@ -8,6 +8,7 @@ use nym_validator_client::nyxd::contract_traits::EcashQueryClient;
use std::sync::Arc;
use time::OffsetDateTime;
use tokio::sync::RwLock;
use tracing::{info, warn};
pub struct CachedDeposit {
valid_until: OffsetDateTime,
@@ -56,13 +57,29 @@ impl RequiredDepositCache {
// update cache
drop(read_guard);
let address = chain_client.address().await;
info!("checking deposit required by {address}");
let mut write_guard = self.inner.write().await;
let deposit_amount = chain_client
.query_chain()
.await
.get_required_deposit_amount()
let read_permit = chain_client.query_chain().await;
let reduced = read_permit
.get_reduced_deposit_amount(address.to_string())
.await?;
let deposit_amount = match reduced {
Some(reduced) => {
info!("we're permitted to use reduced price");
reduced
}
None => {
warn!(
"using default deposit value {address} is not whitelisted for price reduction"
);
read_permit.get_default_deposit_amount().await?
}
};
let nym_coin: Coin = deposit_amount.into();
write_guard.update(nym_coin.clone());
@@ -3,25 +3,19 @@
use crate::Error;
use crate::ecash::error::EcashTicketError;
use crate::ecash::helpers::for_each_api_concurrent;
use crate::ecash::state::SharedState;
use cosmwasm_std::Fraction;
use cw_utils::ThresholdResponse;
use futures::channel::mpsc::UnboundedReceiver;
use futures::{Stream, StreamExt};
use nym_api_requests::constants::MIN_BATCH_REDEMPTION_DELAY;
use nym_api_requests::ecash::models::{BatchRedeemTicketsBody, VerifyEcashTicketBody};
use nym_api_requests::ecash::models::VerifyEcashTicketBody;
use nym_credentials_interface::Bandwidth;
use nym_credentials_interface::{ClientTicket, TicketType};
use nym_validator_client::EcashApiClient;
use nym_validator_client::coconut::EcashApiError;
use nym_validator_client::nym_api::{EpochId, NymApiClientExt};
use nym_validator_client::nym_api::NymApiClientExt;
use nym_validator_client::nyxd::AccountId;
use nym_validator_client::nyxd::contract_traits::{
EcashSigningClient, MultisigQueryClient, MultisigSigningClient, PagedMultisigQueryClient,
};
use nym_validator_client::nyxd::cosmwasm_client::ContractResponseData;
use nym_validator_client::nyxd::cw3::Status;
use nym_validator_client::nyxd::contract_traits::MultisigQueryClient;
use si_scale::helpers::bibytes2;
use std::collections::{HashMap, HashSet};
use std::ops::Deref;
@@ -31,22 +25,6 @@ use tokio::sync::{Mutex, RwLockReadGuard};
use tokio::time::{Duration, Instant, interval_at};
use tracing::{debug, error, info, instrument, trace, warn};
enum ProposalResult {
Executed,
Rejected,
Pending,
}
impl ProposalResult {
fn is_pending(&self) -> bool {
matches!(self, ProposalResult::Pending)
}
fn is_rejected(&self) -> bool {
matches!(self, ProposalResult::Rejected)
}
}
struct PendingVerification {
ticket: ClientTicket,
@@ -68,43 +46,6 @@ impl PendingVerification {
}
}
struct PendingRedemptionVote {
proposal_id: u64,
digest: Vec<u8>,
included_serial_numbers: Vec<Vec<u8>>,
epoch_id: EpochId,
// vec of node ids of apis that haven't sent a valid response
pending: Vec<u64>,
}
impl PendingRedemptionVote {
fn new(
proposal_id: u64,
digest: Vec<u8>,
included_serial_numbers: Vec<Vec<u8>>,
epoch_id: EpochId,
pending: Vec<u64>,
) -> Self {
PendingRedemptionVote {
proposal_id,
digest,
included_serial_numbers,
epoch_id,
pending,
}
}
fn to_request_body(&self, gateway_cosmos_addr: AccountId) -> BatchRedeemTicketsBody {
BatchRedeemTicketsBody::new(
self.digest.clone(),
self.proposal_id,
self.included_serial_numbers.clone(),
gateway_cosmos_addr,
)
}
}
pub struct CredentialHandlerConfig {
/// Specifies the multiplier for revoking a malformed/double-spent ticket
/// (if it has to go all the way to the nym-api for verification)
@@ -132,7 +73,6 @@ pub struct CredentialHandler {
ticket_receiver: UnboundedReceiver<ClientTicket>,
shared_state: SharedState,
pending_tickets: Vec<PendingVerification>,
pending_redemptions: Vec<PendingRedemptionVote>,
}
impl CredentialHandler {
@@ -184,75 +124,6 @@ impl CredentialHandler {
Ok(pending)
}
async fn rebuild_pending_votes(
shared_state: &SharedState,
) -> Result<Vec<PendingRedemptionVote>, EcashTicketError> {
// 1. get all tickets that were not fully verified
let unverified = shared_state.storage.get_all_unresolved_proposals().await?;
let mut pending = Vec::with_capacity(unverified.len());
let epoch_id = shared_state.current_epoch_id().await?;
let apis = shared_state
.api_clients(epoch_id)
.await?
.iter()
.map(|s| (s.cosmos_address.to_string(), s.node_id))
.collect::<Vec<_>>();
for proposal_id in unverified {
// get all of the votes
let votes = shared_state
.start_query()
.await
.get_all_votes(proposal_id as u64)
.await
.map_err(EcashTicketError::chain_query_failure)?
.into_iter()
.map(|v| v.voter)
.collect::<HashSet<_>>();
let mut missing_votes = Vec::new();
// see who hasn't voted
for (api_address, api_id) in &apis {
// for each signer, check if they have actually voted; if not, that's the missing guy
if !votes.contains(api_address) {
missing_votes.push(*api_id)
}
}
// attempt to rebuild SN and digest from the proposal info + storage data
let proposal_info = shared_state
.start_query()
.await
.query_proposal(proposal_id as u64)
.await
.map_err(EcashTicketError::chain_query_failure)?;
let tickets = shared_state
.storage
.get_all_proposed_tickets_with_sn(proposal_id as u32)
.await?;
let digest =
BatchRedeemTicketsBody::make_digest(tickets.iter().map(|t| &t.serial_number));
let encoded_digest = bs58::encode(&digest).into_string();
if encoded_digest != proposal_info.description {
error!("the lost proposal {proposal_id} does not have a matching digest!");
continue;
}
pending.push(PendingRedemptionVote {
proposal_id: proposal_id as u64,
digest,
included_serial_numbers: tickets.into_iter().map(|t| t.serial_number).collect(),
epoch_id,
pending: missing_votes,
})
}
Ok(pending)
}
pub(crate) async fn new(
config: CredentialHandlerConfig,
ticket_receiver: UnboundedReceiver<ClientTicket>,
@@ -276,51 +147,15 @@ impl CredentialHandler {
// on startup read pending credentials and api responses from the storage
let pending_tickets = Self::rebuild_pending_tickets(&shared_state).await?;
// on startup read pending proposals from the storage
// then reconstruct the votes by querying the multisig contract for votes on those proposals
// digest from the description and count from the message
let pending_redemptions = Self::rebuild_pending_votes(&shared_state).await?;
Ok(CredentialHandler {
config,
multisig_threshold,
ticket_receiver,
shared_state,
pending_tickets,
pending_redemptions,
})
}
// the argument is temporary as we'll be reading from the storage
async fn create_redemption_proposal(
&self,
commitment: &[u8],
number_of_tickets: u16,
) -> Result<u64, EcashTicketError> {
let res = self
.shared_state
.start_tx()
.await
.request_ticket_redemption(
bs58::encode(commitment).into_string(),
number_of_tickets,
None,
)
.await
.map_err(|source| EcashTicketError::RedemptionProposalCreationFailure { source })?;
// that one is quite tricky because proposal exists on chain, but we didn't get the id...
// but it should be quite impossible to ever reach this unless we make breaking changes
let proposal_id = res
.parse_singleton_u64_contract_data()
.inspect_err(|err| error!("reached seemingly impossible error! could not recover the redemption proposal id: {err}"))
.map_err(|source| EcashTicketError::ProposalIdParsingFailure { source })?;
info!("created redemption proposal {proposal_id} to redeem {number_of_tickets} tickets");
Ok(proposal_id)
}
/// Attempt to send ticket verification request to the provided ecash verifier.
async fn verify_ticket(
&self,
@@ -522,42 +357,7 @@ impl CredentialHandler {
async fn resolve_pending(&mut self) -> Result<(), EcashTicketError> {
let mut still_failing = Vec::new();
// 1. attempt to resolve all pending proposals
while let Some(mut pending) = self.pending_redemptions.pop() {
match self.try_resolve_pending_proposal(&mut pending, None).await {
Ok(resolution) => {
if resolution.is_pending() {
warn!(
"still failed to reach quorum for proposal {}. apis: {:?} haven't responded. we'll retry later",
pending.proposal_id, pending.pending
);
still_failing.push(pending);
} else {
self.shared_state
.storage
.clear_post_proposal_data(
pending.proposal_id as u32,
OffsetDateTime::now_utc(),
resolution.is_rejected(),
)
.await?;
}
}
Err(err) => {
error!(
"experienced internal error when attempting to resolve pending proposal: {err}"
);
// make sure to update internal state to not lose any data
self.pending_redemptions.push(pending);
self.pending_redemptions.append(&mut still_failing);
return Err(err);
}
}
}
let mut still_failing = Vec::new();
// 2. attempt to verify the remaining tickets
// 1. attempt to verify the remaining tickets
while let Some(mut pending) = self.pending_tickets.pop() {
// possible optimisation: if there's a lot of pending tickets, pre-emptively grab locks for api_clients
match self
@@ -595,362 +395,14 @@ impl CredentialHandler {
Ok(())
}
/// Attempt to send batch redemption request to the provided ecash verifier.
async fn redeem_tickets(
&self,
proposal_id: u64,
request: &BatchRedeemTicketsBody,
client: &EcashApiClient,
) -> Result<bool, EcashTicketError> {
match client.api_client.batch_redeem_ecash_tickets(request).await {
Ok(res) => {
let accepted = if res.proposal_accepted {
trace!("{client} has accepted proposal {proposal_id}");
true
} else {
warn!("{client} has rejected proposal {proposal_id}");
false
};
Ok(accepted)
}
Err(err) => {
error!(
"failed to send proposal {proposal_id} for redemption vote to ecash signer '{client}': {err}. if we don't reach quorum, we'll retry later"
);
Ok(false)
}
}
}
async fn try_execute_proposal(&self, proposal_id: u64) -> Result<(), EcashTicketError> {
self.shared_state
.start_tx()
.await
.execute_proposal(proposal_id, None)
.await
.map_err(
|source| EcashTicketError::RedemptionProposalExecutionFailure {
proposal_id,
source,
},
)?;
Ok(())
}
async fn get_proposal_status(&self, proposal_id: u64) -> Result<Status, EcashTicketError> {
Ok(self
.shared_state
.start_query()
.await
.query_proposal(proposal_id)
.await
.map_err(EcashTicketError::chain_query_failure)?
.status)
}
async fn try_finalize_proposal(
&self,
proposal_id: u64,
) -> Result<ProposalResult, EcashTicketError> {
match self.get_proposal_status(proposal_id).await? {
Status::Pending => {
// the voting hasn't even begun!
error!("impossible case! the proposal {proposal_id} is still pending");
Ok(ProposalResult::Pending)
}
Status::Open => {
debug!("proposal {proposal_id} is still open and needs more votes");
Ok(ProposalResult::Pending)
}
Status::Rejected => {
warn!("proposal {proposal_id} has been rejected");
Ok(ProposalResult::Rejected)
}
Status::Passed => {
info!(
"proposal {proposal_id} has already been passed - we just need to execute it"
);
self.try_execute_proposal(proposal_id).await?;
info!("executed proposal {proposal_id}");
Ok(ProposalResult::Executed)
}
Status::Executed => {
info!("proposal {proposal_id} has already been executed - nothing to do!");
Ok(ProposalResult::Executed)
}
}
}
async fn try_resolve_pending_proposal(
&self,
pending: &mut PendingRedemptionVote,
api_clients: Option<RwLockReadGuard<'_, Vec<EcashApiClient>>>,
) -> Result<ProposalResult, EcashTicketError> {
let proposal_id = pending.proposal_id;
info!(
"attempting to resolve pending redemption proposal {proposal_id} to redeem {} tickets",
pending.included_serial_numbers.len()
);
// check if the proposal still needs more votes from the apis
let result = self.try_finalize_proposal(proposal_id).await?;
if !result.is_pending() {
return Ok(result);
}
let api_clients = match api_clients {
Some(clients) => clients,
None => self.shared_state.api_clients(pending.epoch_id).await?,
};
let redemption_request = pending.to_request_body(self.shared_state.address.clone());
// TODO: optimisation: tell other apis they can purge our tickets even if they haven't voted
let total = api_clients.len();
let api_failures = Mutex::new(Vec::new());
let rejected = AtomicUsize::new(0);
for_each_api_concurrent(&api_clients, &pending.pending, |ecash_client| async {
// errors are only returned on hard, storage, failures
match self
.redeem_tickets(pending.proposal_id, &redemption_request, ecash_client)
.await
{
Err(err) => {
error!("internal failure. could not proceed with ticket redemption: {err}");
api_failures.lock().await.push(ecash_client.node_id);
}
Ok(false) => {
rejected.fetch_add(1, Ordering::SeqCst);
}
_ => {}
}
})
.await;
let api_failures = api_failures.into_inner();
let num_failures = api_failures.len();
pending.pending = api_failures;
let rejected = rejected.into_inner();
let rejected_ratio = rejected as f32 / total as f32;
let rejected_perc = rejected_ratio * 100.;
if rejected_ratio >= (1. - self.multisig_threshold) {
error!(
"{rejected_perc:.2}% of signers rejected proposal {proposal_id}. we won't be able to execute it"
);
// no need to query the chain as with so many rejections it's impossible it has passed.
return Ok(ProposalResult::Rejected);
}
let accepted_ratio = (total - rejected - num_failures) as f32 / total as f32;
let accepted_perc = accepted_ratio * 100.;
match accepted_ratio {
n if n < self.multisig_threshold => {
error!(
"less than 2/3 of signers ({accepted_perc:.2}%) accepted proposal {proposal_id}. we're not yet be able to execute it to get funds out"
);
return Ok(ProposalResult::Pending);
}
n if n < self.config.minimum_api_quorum => {
warn!(
"the system seems to be a bit unstable: less than 80%, but more than 67% of signers ({accepted_perc:.2}%) accepted proposal {proposal_id}"
);
}
_ => {
trace!("{accepted_perc:.2}% of signers accepted proposal {proposal_id}");
}
}
// attempt to execute the proposal if it reached the required threshold
self.try_finalize_proposal(proposal_id).await
}
async fn maybe_redeem_tickets(&mut self) -> Result<(), EcashTicketError> {
if !self.pending_tickets.is_empty() {
return Err(EcashTicketError::PendingTickets);
}
let latest_stored = self.shared_state.storage.latest_proposal().await?;
// check if we have already created the proposal but crashed before persisting it in the db
//
// if we have some persisted proposals in storage, try to see if there's anything more recent on chain
// (i.e. the missing proposal)
// if not (i.e. this would have been our first) check the latest page of proposals.
// while this is not ideal, realistically speaking we probably crashed few minutes ago
// and worst case scenario we'll just recreate the proposal instead
//
// LIMITATION: if MULTIPLE proposals got created in between, well. though luck.
let latest_on_chain = if let Some(latest_stored) = &latest_stored {
// those are sorted in ASCENDING way
self.shared_state
.proposals_since(latest_stored.proposal_id as u64)
.await?
.pop()
} else {
// but those are DESCENDING
self.shared_state
.last_proposal_page()
.await?
.first()
.cloned()
};
let now = OffsetDateTime::now_utc();
let prior_proposal = match (&latest_stored, latest_on_chain) {
(None, None) => {
// we haven't created any proposals before
trace!("this could be our first redemption proposal");
None
}
(Some(stored), None) => {
if stored.created_at + MIN_BATCH_REDEMPTION_DELAY > now {
trace!("too soon to create new redemption proposal");
return Ok(());
}
None
}
(_, Some(on_chain)) => {
warn!(
"we seem to have crashed after creating proposal, but before persisting it onto disk!"
);
Some(on_chain)
}
};
// technically we could have been just caching all of those serial numbers as we verify tickets,
// but given how infrequently we call this, there's no point in wasting this memory
let verified_tickets = self
.shared_state
.storage
.get_all_verified_tickets_with_sn()
.await?;
// TODO: somehow simplify that nasty nested if
if verified_tickets.len() < self.config.minimum_redemption_tickets {
// bypass the number of tickets check if we're about to lose our rewards due to expiration
if let Some(latest_stored) = latest_stored {
if latest_stored.created_at + self.config.maximum_time_between_redemption < now {
{}
} else {
debug!(
"we only have {} verified tickets. there's no point in creating a redemption request yet. (we need at least {} (configurable))",
verified_tickets.len(),
self.config.minimum_redemption_tickets
);
return Ok(());
}
} else {
// first proposal
debug!(
"we only have {} verified tickets. there's no point in creating a redemption request yet. (we need at least {} (configurable))",
verified_tickets.len(),
self.config.minimum_redemption_tickets
);
return Ok(());
}
}
// this should have been ensured when querying
assert!(verified_tickets.len() <= u16::MAX as usize);
let digest =
BatchRedeemTicketsBody::make_digest(verified_tickets.iter().map(|t| &t.serial_number));
let encoded_digest = bs58::encode(&digest).into_string();
let prior_proposal_id = if let Some(prior_proposal) = prior_proposal {
if prior_proposal.description == encoded_digest {
info!("we have already created proposal for those tickets");
Some(prior_proposal.id)
} else {
warn!(
"our missed proposal seem to have been for different tickets - abandoning it"
);
None
}
} else {
None
};
// if the proposal has already existed on chain, do use it. otherwise create a new one
let proposal_id = if let Some(prior) = prior_proposal_id {
prior
} else {
self.create_redemption_proposal(&digest, verified_tickets.len() as u16)
.await?
};
if proposal_id > u32::MAX as u64 {
// realistically will we ever reach it? no.
panic!(
"we have created more than {} proposals. we can't handle that.",
u32::MAX
)
}
self.shared_state
.storage
.insert_redemption_proposal(
&verified_tickets,
proposal_id as u32,
OffsetDateTime::now_utc(),
)
.await?;
let current_epoch = self.shared_state.current_epoch_id().await?;
let api_clients = self.shared_state.api_clients(current_epoch).await?;
let ids = api_clients.iter().map(|c| c.node_id).collect();
let mut pending = PendingRedemptionVote::new(
proposal_id,
digest,
verified_tickets
.into_iter()
.map(|t| t.serial_number)
.collect(),
current_epoch,
ids,
);
let resolution = self
.try_resolve_pending_proposal(&mut pending, Some(api_clients))
.await?;
if resolution.is_pending() {
warn!(
"failed to reach quorum for proposal {proposal_id}. apis: {:?} haven't responded. we'll retry later",
pending.pending
);
self.pending_redemptions.push(pending);
} else {
self.shared_state
.storage
.clear_post_proposal_data(
proposal_id as u32,
OffsetDateTime::now_utc(),
resolution.is_rejected(),
)
.await?;
}
Ok(())
}
async fn periodic_operations(&mut self) -> Result<(), EcashTicketError> {
trace!(
"attempting to resolve all pending operations -> tickets that are waiting for verification and possibly redemption"
"attempting to resolve all pending operations -> tickets that are waiting for verification"
);
// 1. retry all operations that have failed in the past: verification requests and pending redemption
// retry the pending verification requests that have failed before
self.resolve_pending().await?;
// 2. if applicable, attempt to redeem all newly verified tickets
self.maybe_redeem_tickets().await?;
Ok(())
}
@@ -7,7 +7,7 @@ use std::future::Future;
use std::ops::Deref;
use tokio::sync::RwLockReadGuard;
pub(crate) fn apis_stream<'a>(
pub fn apis_stream<'a>(
// if needed we could make this argument more generic to accept either locks or iterators, etc.
all_clients: &'a RwLockReadGuard<'a, Vec<EcashApiClient>>,
filter_by_id: &'a [u64],
@@ -22,7 +22,7 @@ pub(crate) fn apis_stream<'a>(
)
}
pub(crate) async fn for_each_api_concurrent<'a, F, Fut>(
pub async fn for_each_api_concurrent<'a, F, Fut>(
all_clients: &'a RwLockReadGuard<'a, Vec<EcashApiClient>>,
filter_by_id: &'a [u64],
f: F,
@@ -20,7 +20,7 @@ use tracing::error;
pub mod credential_sender;
pub mod error;
mod helpers;
pub mod helpers;
mod state;
pub mod traits;
@@ -3,17 +3,12 @@
use crate::Error;
use crate::ecash::error::EcashTicketError;
use cosmwasm_std::{CosmosMsg, WasmMsg, from_json};
use nym_credentials_interface::VerificationKeyAuth;
use nym_ecash_contract_common::msg::ExecuteMsg;
use nym_gateway_storage::traits::BandwidthGatewayStorage;
use nym_validator_client::coconut::all_ecash_api_clients;
use nym_validator_client::nym_api::EpochId;
use nym_validator_client::nyxd::AccountId;
use nym_validator_client::nyxd::contract_traits::{
DkgQueryClient, MultisigQueryClient, NymContractsProvider,
};
use nym_validator_client::nyxd::cw3::ProposalResponse;
use nym_validator_client::nyxd::contract_traits::{DkgQueryClient, NymContractsProvider};
use nym_validator_client::{DirectSigningHttpRpcNyxdClient, EcashApiClient};
use std::collections::BTreeMap;
use std::ops::Deref;
@@ -77,53 +72,6 @@ impl SharedState {
Ok(this)
}
fn created_redemption_proposal(&self, proposal: &ProposalResponse) -> bool {
let Some(msg) = proposal.msgs.first() else {
return false;
};
let CosmosMsg::Wasm(WasmMsg::Execute { msg, .. }) = msg else {
return false;
};
let Ok(ExecuteMsg::RedeemTickets { gw, .. }) = from_json(msg) else {
return false;
};
gw == self.address.as_ref()
}
/// retrieve all redemption proposals made by this gateway since, but excluding, the provided id
pub(crate) async fn proposals_since(
&self,
proposal_id: u64,
) -> Result<Vec<ProposalResponse>, EcashTicketError> {
Ok(self
.start_query()
.await
.list_proposals(Some(proposal_id), None)
.await
.map_err(EcashTicketError::chain_query_failure)?
.proposals
.into_iter()
.filter(|p| self.created_redemption_proposal(p))
.collect())
}
/// retrieve all redemption proposals made by this gateway that are available on the last page of the query
pub(crate) async fn last_proposal_page(
&self,
) -> Result<Vec<ProposalResponse>, EcashTicketError> {
Ok(self
.start_query()
.await
.reverse_proposals(None, None)
.await
.map_err(EcashTicketError::chain_query_failure)?
.proposals
.into_iter()
.filter(|p| self.created_redemption_proposal(p))
.collect())
}
async fn set_epoch_data(
&self,
epoch_id: EpochId,
@@ -240,24 +188,6 @@ impl SharedState {
data.get(&epoch_id).map(|d| &d.master_key).unwrap()
}))
}
pub(crate) async fn start_tx(&self) -> RwLockWriteGuard<'_, DirectSigningHttpRpcNyxdClient> {
self.nyxd_client.write().await
}
pub(crate) async fn start_query(&self) -> RwLockReadGuard<'_, DirectSigningHttpRpcNyxdClient> {
self.nyxd_client.read().await
}
pub(crate) async fn current_epoch_id(&self) -> Result<EpochId, EcashTicketError> {
Ok(self
.start_query()
.await
.get_current_epoch()
.await
.map_err(EcashTicketError::chain_query_failure)?
.epoch_id)
}
}
pub(crate) struct EpochState {
+20 -7
View File
@@ -709,7 +709,7 @@ dependencies = [
"nym-contracts-common",
"nym-contracts-common-testing",
"nym-group-contract-common",
"nym-multisig-contract-common",
"nym-multisig-contract-common 1.20.4 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
@@ -1258,7 +1258,7 @@ dependencies = [
"cw2",
"cw4",
"nym-contracts-common",
"nym-multisig-contract-common",
"nym-multisig-contract-common 1.20.4 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
@@ -1329,11 +1329,11 @@ dependencies = [
"cw3",
"cw4",
"nym-contracts-common",
"nym-contracts-common-testing",
"nym-crypto",
"nym-ecash-contract-common",
"nym-multisig-contract-common",
"nym-multisig-contract-common 1.20.4 (registry+https://github.com/rust-lang/crates.io-index)",
"nym-network-defaults",
"rand_chacha",
"schemars",
"semver",
"serde",
@@ -1344,8 +1344,6 @@ dependencies = [
[[package]]
name = "nym-ecash-contract-common"
version = "1.20.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d022e85291bf51877fbbf4688bc3762c605fdaee3b98c6407414f7c358bc5610"
dependencies = [
"bs58",
"cosmwasm-schema",
@@ -1353,7 +1351,7 @@ dependencies = [
"cw-controllers",
"cw-utils",
"cw2",
"nym-multisig-contract-common",
"nym-multisig-contract-common 1.20.4",
"thiserror 2.0.12",
]
@@ -1416,6 +1414,21 @@ dependencies = [
"time",
]
[[package]]
name = "nym-multisig-contract-common"
version = "1.20.4"
dependencies = [
"cosmwasm-schema",
"cosmwasm-std",
"cw-storage-plus",
"cw-utils",
"cw3",
"cw4",
"schemars",
"serde",
"thiserror 2.0.12",
]
[[package]]
name = "nym-multisig-contract-common"
version = "1.20.4"
+3
View File
@@ -96,3 +96,6 @@ unreachable = "deny"
# For local development, import via path instead of crates.io, e.g.
# [patch.crates-io]
# nym-coconut-dkg-common = { path = "../common/cosmwasm-smart-contracts/coconut-dkg" }
[patch.crates-io]
nym-ecash-contract-common = { path = "../common/cosmwasm-smart-contracts/ecash-contract" }
+5 -1
View File
@@ -39,8 +39,12 @@ nym-network-defaults = { workspace = true, default-features = false }
anyhow = { workspace = true }
sylvia = { workspace = true, features = ["mt"] }
nym-crypto = { workspace = true, features = ["rand", "asymmetric"] }
rand_chacha = "0.3"
cw-multi-test = { workspace = true }
nym-contracts-common-testing = { workspace = true }
[features]
schema-gen = ["nym-ecash-contract-common/schema"]
[lints]
workspace = true
+351 -19
View File
@@ -156,10 +156,10 @@
{
"type": "object",
"required": [
"update_deposit_value"
"update_default_deposit_value"
],
"properties": {
"update_deposit_value": {
"update_default_deposit_value": {
"type": "object",
"required": [
"new_deposit"
@@ -174,6 +174,54 @@
},
"additionalProperties": false
},
{
"description": "Set (or overwrite) a reduced deposit price for a specific address. Only callable by the contract admin.",
"type": "object",
"required": [
"set_reduced_deposit_price"
],
"properties": {
"set_reduced_deposit_price": {
"type": "object",
"required": [
"address",
"deposit"
],
"properties": {
"address": {
"type": "string"
},
"deposit": {
"$ref": "#/definitions/Coin"
}
},
"additionalProperties": false
}
},
"additionalProperties": false
},
{
"description": "Remove the reduced deposit price for a specific address, reverting them to the default price. Returns an error if the address has no custom price set. Only callable by the contract admin.",
"type": "object",
"required": [
"remove_reduced_deposit_price"
],
"properties": {
"remove_reduced_deposit_price": {
"type": "object",
"required": [
"address"
],
"properties": {
"address": {
"type": "string"
}
},
"additionalProperties": false
}
},
"additionalProperties": false
},
{
"type": "object",
"required": [
@@ -297,10 +345,44 @@
{
"type": "object",
"required": [
"get_required_deposit_amount"
"get_default_deposit_amount"
],
"properties": {
"get_required_deposit_amount": {
"get_default_deposit_amount": {
"type": "object",
"additionalProperties": false
}
},
"additionalProperties": false
},
{
"type": "object",
"required": [
"get_reduced_deposit_amount"
],
"properties": {
"get_reduced_deposit_amount": {
"type": "object",
"required": [
"address"
],
"properties": {
"address": {
"type": "string"
}
},
"additionalProperties": false
}
},
"additionalProperties": false
},
{
"type": "object",
"required": [
"get_all_whitelisted_accounts"
],
"properties": {
"get_all_whitelisted_accounts": {
"type": "object",
"additionalProperties": false
}
@@ -373,6 +455,19 @@
}
},
"additionalProperties": false
},
{
"type": "object",
"required": [
"get_deposits_statistics"
],
"properties": {
"get_deposits_statistics": {
"type": "object",
"additionalProperties": false
}
},
"additionalProperties": false
}
]
},
@@ -380,10 +475,120 @@
"$schema": "http://json-schema.org/draft-07/schema#",
"title": "MigrateMsg",
"type": "object",
"additionalProperties": false
"required": [
"initial_whitelist"
],
"properties": {
"initial_whitelist": {
"description": "Initial set of whitelisted accounts with their reduced deposit prices. Each entry is validated and stored during migration.",
"type": "array",
"items": {
"$ref": "#/definitions/WhitelistedDeposit"
}
}
},
"additionalProperties": false,
"definitions": {
"Coin": {
"type": "object",
"required": [
"amount",
"denom"
],
"properties": {
"amount": {
"$ref": "#/definitions/Uint128"
},
"denom": {
"type": "string"
}
},
"additionalProperties": false
},
"Uint128": {
"description": "A thin wrapper around u128 that is using strings for JSON encoding/decoding, such that the full u128 range can be used for clients that convert JSON numbers to floats, like JavaScript and jq.\n\n# Examples\n\nUse `from` to create instances of this and `u128` to get the value out:\n\n``` # use cosmwasm_std::Uint128; let a = Uint128::from(123u128); assert_eq!(a.u128(), 123);\n\nlet b = Uint128::from(42u64); assert_eq!(b.u128(), 42);\n\nlet c = Uint128::from(70u32); assert_eq!(c.u128(), 70); ```",
"type": "string"
},
"WhitelistedDeposit": {
"description": "An address and its reduced deposit price, used when seeding the whitelist via migration.",
"type": "object",
"required": [
"address",
"deposit"
],
"properties": {
"address": {
"type": "string"
},
"deposit": {
"$ref": "#/definitions/Coin"
}
},
"additionalProperties": false
}
}
},
"sudo": null,
"responses": {
"get_all_whitelisted_accounts": {
"$schema": "http://json-schema.org/draft-07/schema#",
"title": "WhitelistedAccountsResponse",
"type": "object",
"required": [
"whitelisted_accounts"
],
"properties": {
"whitelisted_accounts": {
"type": "array",
"items": {
"$ref": "#/definitions/WhitelistedAccount"
}
}
},
"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"
},
"Coin": {
"type": "object",
"required": [
"amount",
"denom"
],
"properties": {
"amount": {
"$ref": "#/definitions/Uint128"
},
"denom": {
"type": "string"
}
},
"additionalProperties": false
},
"Uint128": {
"description": "A thin wrapper around u128 that is using strings for JSON encoding/decoding, such that the full u128 range can be used for clients that convert JSON numbers to floats, like JavaScript and jq.\n\n# Examples\n\nUse `from` to create instances of this and `u128` to get the value out:\n\n``` # use cosmwasm_std::Uint128; let a = Uint128::from(123u128); assert_eq!(a.u128(), 123);\n\nlet b = Uint128::from(42u64); assert_eq!(b.u128(), 42);\n\nlet c = Uint128::from(70u32); assert_eq!(c.u128(), 70); ```",
"type": "string"
},
"WhitelistedAccount": {
"type": "object",
"required": [
"address",
"deposit"
],
"properties": {
"address": {
"$ref": "#/definitions/Addr"
},
"deposit": {
"$ref": "#/definitions/Coin"
}
},
"additionalProperties": false
}
}
},
"get_blacklist_paged": {
"$schema": "http://json-schema.org/draft-07/schema#",
"title": "PagedBlacklistedAccountResponse",
@@ -496,6 +701,30 @@
}
}
},
"get_default_deposit_amount": {
"$schema": "http://json-schema.org/draft-07/schema#",
"title": "Coin",
"type": "object",
"required": [
"amount",
"denom"
],
"properties": {
"amount": {
"$ref": "#/definitions/Uint128"
},
"denom": {
"type": "string"
}
},
"additionalProperties": false,
"definitions": {
"Uint128": {
"description": "A thin wrapper around u128 that is using strings for JSON encoding/decoding, such that the full u128 range can be used for clients that convert JSON numbers to floats, like JavaScript and jq.\n\n# Examples\n\nUse `from` to create instances of this and `u128` to get the value out:\n\n``` # use cosmwasm_std::Uint128; let a = Uint128::from(123u128); assert_eq!(a.u128(), 123);\n\nlet b = Uint128::from(42u64); assert_eq!(b.u128(), 42);\n\nlet c = Uint128::from(70u32); assert_eq!(c.u128(), 70); ```",
"type": "string"
}
}
},
"get_deposit": {
"$schema": "http://json-schema.org/draft-07/schema#",
"title": "DepositResponse",
@@ -594,6 +823,99 @@
}
}
},
"get_deposits_statistics": {
"$schema": "http://json-schema.org/draft-07/schema#",
"title": "DepositsStatistics",
"description": "Aggregate statistics about all deposits made through the ecash contract.",
"type": "object",
"required": [
"deposited_with_custom_price",
"deposits_made_with_custom_price",
"total_deposited",
"total_deposited_with_custom_price",
"total_deposited_with_default_price",
"total_deposits_made",
"total_deposits_made_with_custom_price",
"total_deposits_made_with_default_price"
],
"properties": {
"deposited_with_custom_price": {
"description": "Per-account breakdown of deposited amounts for whitelisted addresses.",
"type": "object",
"additionalProperties": false
},
"deposits_made_with_custom_price": {
"description": "Per-account breakdown of deposit counts for whitelisted addresses.",
"type": "object",
"additionalProperties": false
},
"total_deposited": {
"description": "Total value of all deposits ever made (at any price tier), sourced from `PoolCounters::total_deposited`.",
"allOf": [
{
"$ref": "#/definitions/Coin"
}
]
},
"total_deposited_with_custom_price": {
"description": "Total value deposited at custom prices, summed across all whitelisted accounts.",
"allOf": [
{
"$ref": "#/definitions/Coin"
}
]
},
"total_deposited_with_default_price": {
"description": "Total value deposited at the default price.",
"allOf": [
{
"$ref": "#/definitions/Coin"
}
]
},
"total_deposits_made": {
"description": "Total number of deposits ever made (at any price tier), derived from the deposit id counter.",
"type": "integer",
"format": "uint32",
"minimum": 0.0
},
"total_deposits_made_with_custom_price": {
"description": "Number of deposits made at any custom (reduced) price, summed across all whitelisted accounts.",
"type": "integer",
"format": "uint32",
"minimum": 0.0
},
"total_deposits_made_with_default_price": {
"description": "Number of deposits made at the default (non-reduced) price.",
"type": "integer",
"format": "uint32",
"minimum": 0.0
}
},
"additionalProperties": false,
"definitions": {
"Coin": {
"type": "object",
"required": [
"amount",
"denom"
],
"properties": {
"amount": {
"$ref": "#/definitions/Uint128"
},
"denom": {
"type": "string"
}
},
"additionalProperties": false
},
"Uint128": {
"description": "A thin wrapper around u128 that is using strings for JSON encoding/decoding, such that the full u128 range can be used for clients that convert JSON numbers to floats, like JavaScript and jq.\n\n# Examples\n\nUse `from` to create instances of this and `u128` to get the value out:\n\n``` # use cosmwasm_std::Uint128; let a = Uint128::from(123u128); assert_eq!(a.u128(), 123);\n\nlet b = Uint128::from(42u64); assert_eq!(b.u128(), 42);\n\nlet c = Uint128::from(70u32); assert_eq!(c.u128(), 70); ```",
"type": "string"
}
}
},
"get_latest_deposit": {
"$schema": "http://json-schema.org/draft-07/schema#",
"title": "LatestDepositResponse",
@@ -644,24 +966,34 @@
}
}
},
"get_required_deposit_amount": {
"get_reduced_deposit_amount": {
"$schema": "http://json-schema.org/draft-07/schema#",
"title": "Coin",
"type": "object",
"required": [
"amount",
"denom"
],
"properties": {
"amount": {
"$ref": "#/definitions/Uint128"
"title": "Nullable_Coin",
"anyOf": [
{
"$ref": "#/definitions/Coin"
},
"denom": {
"type": "string"
{
"type": "null"
}
},
"additionalProperties": false,
],
"definitions": {
"Coin": {
"type": "object",
"required": [
"amount",
"denom"
],
"properties": {
"amount": {
"$ref": "#/definitions/Uint128"
},
"denom": {
"type": "string"
}
},
"additionalProperties": false
},
"Uint128": {
"description": "A thin wrapper around u128 that is using strings for JSON encoding/decoding, such that the full u128 range can be used for clients that convert JSON numbers to floats, like JavaScript and jq.\n\n# Examples\n\nUse `from` to create instances of this and `u128` to get the value out:\n\n``` # use cosmwasm_std::Uint128; let a = Uint128::from(123u128); assert_eq!(a.u128(), 123);\n\nlet b = Uint128::from(42u64); assert_eq!(b.u128(), 42);\n\nlet c = Uint128::from(70u32); assert_eq!(c.u128(), 70); ```",
"type": "string"
+50 -2
View File
@@ -104,10 +104,10 @@
{
"type": "object",
"required": [
"update_deposit_value"
"update_default_deposit_value"
],
"properties": {
"update_deposit_value": {
"update_default_deposit_value": {
"type": "object",
"required": [
"new_deposit"
@@ -122,6 +122,54 @@
},
"additionalProperties": false
},
{
"description": "Set (or overwrite) a reduced deposit price for a specific address. Only callable by the contract admin.",
"type": "object",
"required": [
"set_reduced_deposit_price"
],
"properties": {
"set_reduced_deposit_price": {
"type": "object",
"required": [
"address",
"deposit"
],
"properties": {
"address": {
"type": "string"
},
"deposit": {
"$ref": "#/definitions/Coin"
}
},
"additionalProperties": false
}
},
"additionalProperties": false
},
{
"description": "Remove the reduced deposit price for a specific address, reverting them to the default price. Returns an error if the address has no custom price set. Only callable by the contract admin.",
"type": "object",
"required": [
"remove_reduced_deposit_price"
],
"properties": {
"remove_reduced_deposit_price": {
"type": "object",
"required": [
"address"
],
"properties": {
"address": {
"type": "string"
}
},
"additionalProperties": false
}
},
"additionalProperties": false
},
{
"type": "object",
"required": [
+52 -1
View File
@@ -2,5 +2,56 @@
"$schema": "http://json-schema.org/draft-07/schema#",
"title": "MigrateMsg",
"type": "object",
"additionalProperties": false
"required": [
"initial_whitelist"
],
"properties": {
"initial_whitelist": {
"description": "Initial set of whitelisted accounts with their reduced deposit prices. Each entry is validated and stored during migration.",
"type": "array",
"items": {
"$ref": "#/definitions/WhitelistedDeposit"
}
}
},
"additionalProperties": false,
"definitions": {
"Coin": {
"type": "object",
"required": [
"amount",
"denom"
],
"properties": {
"amount": {
"$ref": "#/definitions/Uint128"
},
"denom": {
"type": "string"
}
},
"additionalProperties": false
},
"Uint128": {
"description": "A thin wrapper around u128 that is using strings for JSON encoding/decoding, such that the full u128 range can be used for clients that convert JSON numbers to floats, like JavaScript and jq.\n\n# Examples\n\nUse `from` to create instances of this and `u128` to get the value out:\n\n``` # use cosmwasm_std::Uint128; let a = Uint128::from(123u128); assert_eq!(a.u128(), 123);\n\nlet b = Uint128::from(42u64); assert_eq!(b.u128(), 42);\n\nlet c = Uint128::from(70u32); assert_eq!(c.u128(), 70); ```",
"type": "string"
},
"WhitelistedDeposit": {
"description": "An address and its reduced deposit price, used when seeding the whitelist via migration.",
"type": "object",
"required": [
"address",
"deposit"
],
"properties": {
"address": {
"type": "string"
},
"deposit": {
"$ref": "#/definitions/Coin"
}
},
"additionalProperties": false
}
}
}
+49 -2
View File
@@ -55,10 +55,44 @@
{
"type": "object",
"required": [
"get_required_deposit_amount"
"get_default_deposit_amount"
],
"properties": {
"get_required_deposit_amount": {
"get_default_deposit_amount": {
"type": "object",
"additionalProperties": false
}
},
"additionalProperties": false
},
{
"type": "object",
"required": [
"get_reduced_deposit_amount"
],
"properties": {
"get_reduced_deposit_amount": {
"type": "object",
"required": [
"address"
],
"properties": {
"address": {
"type": "string"
}
},
"additionalProperties": false
}
},
"additionalProperties": false
},
{
"type": "object",
"required": [
"get_all_whitelisted_accounts"
],
"properties": {
"get_all_whitelisted_accounts": {
"type": "object",
"additionalProperties": false
}
@@ -131,6 +165,19 @@
}
},
"additionalProperties": false
},
{
"type": "object",
"required": [
"get_deposits_statistics"
],
"properties": {
"get_deposits_statistics": {
"type": "object",
"additionalProperties": false
}
},
"additionalProperties": false
}
]
}
@@ -0,0 +1,59 @@
{
"$schema": "http://json-schema.org/draft-07/schema#",
"title": "WhitelistedAccountsResponse",
"type": "object",
"required": [
"whitelisted_accounts"
],
"properties": {
"whitelisted_accounts": {
"type": "array",
"items": {
"$ref": "#/definitions/WhitelistedAccount"
}
}
},
"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"
},
"Coin": {
"type": "object",
"required": [
"amount",
"denom"
],
"properties": {
"amount": {
"$ref": "#/definitions/Uint128"
},
"denom": {
"type": "string"
}
},
"additionalProperties": false
},
"Uint128": {
"description": "A thin wrapper around u128 that is using strings for JSON encoding/decoding, such that the full u128 range can be used for clients that convert JSON numbers to floats, like JavaScript and jq.\n\n# Examples\n\nUse `from` to create instances of this and `u128` to get the value out:\n\n``` # use cosmwasm_std::Uint128; let a = Uint128::from(123u128); assert_eq!(a.u128(), 123);\n\nlet b = Uint128::from(42u64); assert_eq!(b.u128(), 42);\n\nlet c = Uint128::from(70u32); assert_eq!(c.u128(), 70); ```",
"type": "string"
},
"WhitelistedAccount": {
"type": "object",
"required": [
"address",
"deposit"
],
"properties": {
"address": {
"$ref": "#/definitions/Addr"
},
"deposit": {
"$ref": "#/definitions/Coin"
}
},
"additionalProperties": false
}
}
}
@@ -0,0 +1,24 @@
{
"$schema": "http://json-schema.org/draft-07/schema#",
"title": "Coin",
"type": "object",
"required": [
"amount",
"denom"
],
"properties": {
"amount": {
"$ref": "#/definitions/Uint128"
},
"denom": {
"type": "string"
}
},
"additionalProperties": false,
"definitions": {
"Uint128": {
"description": "A thin wrapper around u128 that is using strings for JSON encoding/decoding, such that the full u128 range can be used for clients that convert JSON numbers to floats, like JavaScript and jq.\n\n# Examples\n\nUse `from` to create instances of this and `u128` to get the value out:\n\n``` # use cosmwasm_std::Uint128; let a = Uint128::from(123u128); assert_eq!(a.u128(), 123);\n\nlet b = Uint128::from(42u64); assert_eq!(b.u128(), 42);\n\nlet c = Uint128::from(70u32); assert_eq!(c.u128(), 70); ```",
"type": "string"
}
}
}
@@ -0,0 +1,93 @@
{
"$schema": "http://json-schema.org/draft-07/schema#",
"title": "DepositsStatistics",
"description": "Aggregate statistics about all deposits made through the ecash contract.",
"type": "object",
"required": [
"deposited_with_custom_price",
"deposits_made_with_custom_price",
"total_deposited",
"total_deposited_with_custom_price",
"total_deposited_with_default_price",
"total_deposits_made",
"total_deposits_made_with_custom_price",
"total_deposits_made_with_default_price"
],
"properties": {
"deposited_with_custom_price": {
"description": "Per-account breakdown of deposited amounts for whitelisted addresses.",
"type": "object",
"additionalProperties": false
},
"deposits_made_with_custom_price": {
"description": "Per-account breakdown of deposit counts for whitelisted addresses.",
"type": "object",
"additionalProperties": false
},
"total_deposited": {
"description": "Total value of all deposits ever made (at any price tier), sourced from `PoolCounters::total_deposited`.",
"allOf": [
{
"$ref": "#/definitions/Coin"
}
]
},
"total_deposited_with_custom_price": {
"description": "Total value deposited at custom prices, summed across all whitelisted accounts.",
"allOf": [
{
"$ref": "#/definitions/Coin"
}
]
},
"total_deposited_with_default_price": {
"description": "Total value deposited at the default price.",
"allOf": [
{
"$ref": "#/definitions/Coin"
}
]
},
"total_deposits_made": {
"description": "Total number of deposits ever made (at any price tier), derived from the deposit id counter.",
"type": "integer",
"format": "uint32",
"minimum": 0.0
},
"total_deposits_made_with_custom_price": {
"description": "Number of deposits made at any custom (reduced) price, summed across all whitelisted accounts.",
"type": "integer",
"format": "uint32",
"minimum": 0.0
},
"total_deposits_made_with_default_price": {
"description": "Number of deposits made at the default (non-reduced) price.",
"type": "integer",
"format": "uint32",
"minimum": 0.0
}
},
"additionalProperties": false,
"definitions": {
"Coin": {
"type": "object",
"required": [
"amount",
"denom"
],
"properties": {
"amount": {
"$ref": "#/definitions/Uint128"
},
"denom": {
"type": "string"
}
},
"additionalProperties": false
},
"Uint128": {
"description": "A thin wrapper around u128 that is using strings for JSON encoding/decoding, such that the full u128 range can be used for clients that convert JSON numbers to floats, like JavaScript and jq.\n\n# Examples\n\nUse `from` to create instances of this and `u128` to get the value out:\n\n``` # use cosmwasm_std::Uint128; let a = Uint128::from(123u128); assert_eq!(a.u128(), 123);\n\nlet b = Uint128::from(42u64); assert_eq!(b.u128(), 42);\n\nlet c = Uint128::from(70u32); assert_eq!(c.u128(), 70); ```",
"type": "string"
}
}
}
@@ -0,0 +1,34 @@
{
"$schema": "http://json-schema.org/draft-07/schema#",
"title": "Nullable_Coin",
"anyOf": [
{
"$ref": "#/definitions/Coin"
},
{
"type": "null"
}
],
"definitions": {
"Coin": {
"type": "object",
"required": [
"amount",
"denom"
],
"properties": {
"amount": {
"$ref": "#/definitions/Uint128"
},
"denom": {
"type": "string"
}
},
"additionalProperties": false
},
"Uint128": {
"description": "A thin wrapper around u128 that is using strings for JSON encoding/decoding, such that the full u128 range can be used for clients that convert JSON numbers to floats, like JavaScript and jq.\n\n# Examples\n\nUse `from` to create instances of this and `u128` to get the value out:\n\n``` # use cosmwasm_std::Uint128; let a = Uint128::from(123u128); assert_eq!(a.u128(), 123);\n\nlet b = Uint128::from(42u64); assert_eq!(b.u128(), 42);\n\nlet c = Uint128::from(70u32); assert_eq!(c.u128(), 70); ```",
"type": "string"
}
}
}
+2 -195
View File
@@ -2,11 +2,9 @@
// SPDX-License-Identifier: Apache-2.0
use crate::contract::NymEcashContract;
use crate::helpers::{
create_batch_redemption_proposal, create_blacklist_proposal, Config, ProposalId,
};
use crate::helpers::{create_batch_redemption_proposal, create_blacklist_proposal, ProposalId};
use cosmwasm_schema::cw_serde;
use cosmwasm_std::{to_json_binary, Addr, Coin, Decimal, Deps, Storage, SubMsg, Uint128};
use cosmwasm_std::{to_json_binary, Addr, Deps, Storage, SubMsg};
use cw3::ProposalResponse;
use nym_ecash_contract_common::EcashContractError;
use nym_multisig_contract_common::msg::QueryMsg as MultisigQueryMsg;
@@ -33,28 +31,6 @@ impl NymEcashContract {
Ok(TICKETBOOK_SIZE)
}
pub(crate) fn tickets_redemption_amount(
&self,
storage: &dyn Storage,
config: &Config,
number_of_tickets: u16,
) -> Result<Coin, EcashContractError> {
let deposit_amount = config.deposit_amount.amount;
let ticketbook_size = Uint128::new(self.get_ticketbook_size(storage)? as u128);
let tickets = Uint128::new(number_of_tickets as u128);
// how many tickets from a ticketbook you redeemed
let book_ratio = Decimal::from_ratio(tickets, ticketbook_size);
// return = ticketbook_price * (tickets / ticketbook_size)
let return_amount = deposit_amount.mul_floor(book_ratio);
Ok(Coin {
denom: config.deposit_amount.denom.clone(),
amount: return_amount,
})
}
fn must_get_multisig_addr(&self, deps: Deps) -> Result<Addr, EcashContractError> {
// SAFETY: multisig admin MUST always be set on initialisation,
// if the call fails, we're in some weird UB land
@@ -117,172 +93,3 @@ impl NymEcashContract {
Ok(proposal_response)
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::support::tests::TestSetupSimple;
#[test]
fn ticket_redemption_amount() -> anyhow::Result<()> {
// make sure the ticketbook size hasn't changed so that our tests are still valid
assert_eq!(TICKETBOOK_SIZE, 50);
// ticketbook price of 100nym
let test = TestSetupSimple::new().with_deposit_amount(100_000_000);
let res =
test.contract()
.tickets_redemption_amount(test.deps().storage, &test.config(), 1)?;
assert_eq!(res.amount.u128(), 2_000_000);
let res =
test.contract()
.tickets_redemption_amount(test.deps().storage, &test.config(), 2)?;
assert_eq!(res.amount.u128(), 4_000_000);
let res =
test.contract()
.tickets_redemption_amount(test.deps().storage, &test.config(), 5)?;
assert_eq!(res.amount.u128(), 10_000_000);
let res =
test.contract()
.tickets_redemption_amount(test.deps().storage, &test.config(), 10)?;
assert_eq!(res.amount.u128(), 20_000_000);
let res =
test.contract()
.tickets_redemption_amount(test.deps().storage, &test.config(), 30)?;
assert_eq!(res.amount.u128(), 60_000_000);
let res =
test.contract()
.tickets_redemption_amount(test.deps().storage, &test.config(), 50)?;
assert_eq!(res.amount.u128(), 100_000_000);
let res =
test.contract()
.tickets_redemption_amount(test.deps().storage, &test.config(), 123)?;
assert_eq!(res.amount.u128(), 246_000_000);
// ticketbook price of 1.5unym per ticket
let test = TestSetupSimple::new().with_deposit_amount(75);
let res =
test.contract()
.tickets_redemption_amount(test.deps().storage, &test.config(), 1)?;
assert_eq!(res.amount.u128(), 1);
let res =
test.contract()
.tickets_redemption_amount(test.deps().storage, &test.config(), 2)?;
assert_eq!(res.amount.u128(), 3);
let res =
test.contract()
.tickets_redemption_amount(test.deps().storage, &test.config(), 5)?;
assert_eq!(res.amount.u128(), 7);
let res =
test.contract()
.tickets_redemption_amount(test.deps().storage, &test.config(), 10)?;
assert_eq!(res.amount.u128(), 15);
let res =
test.contract()
.tickets_redemption_amount(test.deps().storage, &test.config(), 30)?;
assert_eq!(res.amount.u128(), 45);
let res =
test.contract()
.tickets_redemption_amount(test.deps().storage, &test.config(), 50)?;
assert_eq!(res.amount.u128(), 75);
let res =
test.contract()
.tickets_redemption_amount(test.deps().storage, &test.config(), 123)?;
assert_eq!(res.amount.u128(), 184);
// ticketbook price of 1unym per ticket
let test = TestSetupSimple::new().with_deposit_amount(50);
let res =
test.contract()
.tickets_redemption_amount(test.deps().storage, &test.config(), 1)?;
assert_eq!(res.amount.u128(), 1);
let res =
test.contract()
.tickets_redemption_amount(test.deps().storage, &test.config(), 2)?;
assert_eq!(res.amount.u128(), 2);
let res =
test.contract()
.tickets_redemption_amount(test.deps().storage, &test.config(), 5)?;
assert_eq!(res.amount.u128(), 5);
let res =
test.contract()
.tickets_redemption_amount(test.deps().storage, &test.config(), 10)?;
assert_eq!(res.amount.u128(), 10);
let res =
test.contract()
.tickets_redemption_amount(test.deps().storage, &test.config(), 30)?;
assert_eq!(res.amount.u128(), 30);
let res =
test.contract()
.tickets_redemption_amount(test.deps().storage, &test.config(), 50)?;
assert_eq!(res.amount.u128(), 50);
let res =
test.contract()
.tickets_redemption_amount(test.deps().storage, &test.config(), 123)?;
assert_eq!(res.amount.u128(), 123);
// ticketbook price of 1unym in total
let test = TestSetupSimple::new().with_deposit_amount(1);
let res =
test.contract()
.tickets_redemption_amount(test.deps().storage, &test.config(), 1)?;
assert_eq!(res.amount.u128(), 0);
let res =
test.contract()
.tickets_redemption_amount(test.deps().storage, &test.config(), 2)?;
assert_eq!(res.amount.u128(), 0);
let res =
test.contract()
.tickets_redemption_amount(test.deps().storage, &test.config(), 5)?;
assert_eq!(res.amount.u128(), 0);
let res =
test.contract()
.tickets_redemption_amount(test.deps().storage, &test.config(), 10)?;
assert_eq!(res.amount.u128(), 0);
let res =
test.contract()
.tickets_redemption_amount(test.deps().storage, &test.config(), 30)?;
assert_eq!(res.amount.u128(), 0);
let res =
test.contract()
.tickets_redemption_amount(test.deps().storage, &test.config(), 50)?;
assert_eq!(res.amount.u128(), 1);
let res =
test.contract()
.tickets_redemption_amount(test.deps().storage, &test.config(), 123)?;
assert_eq!(res.amount.u128(), 2);
// ticketbook price of 0unym
let test = TestSetupSimple::new().with_deposit_amount(0);
let res =
test.contract()
.tickets_redemption_amount(test.deps().storage, &test.config(), 1)?;
assert_eq!(res.amount.u128(), 0);
let res =
test.contract()
.tickets_redemption_amount(test.deps().storage, &test.config(), 2)?;
assert_eq!(res.amount.u128(), 0);
let res =
test.contract()
.tickets_redemption_amount(test.deps().storage, &test.config(), 5)?;
assert_eq!(res.amount.u128(), 0);
let res =
test.contract()
.tickets_redemption_amount(test.deps().storage, &test.config(), 10)?;
assert_eq!(res.amount.u128(), 0);
let res =
test.contract()
.tickets_redemption_amount(test.deps().storage, &test.config(), 30)?;
assert_eq!(res.amount.u128(), 0);
let res =
test.contract()
.tickets_redemption_amount(test.deps().storage, &test.config(), 50)?;
assert_eq!(res.amount.u128(), 0);
let res =
test.contract()
.tickets_redemption_amount(test.deps().storage, &test.config(), 123)?;
assert_eq!(res.amount.u128(), 0);
Ok(())
}
}
+228 -24
View File
@@ -4,11 +4,12 @@
use crate::constants::{BLACKLIST_PROPOSAL_REPLY_ID, REDEMPTION_PROPOSAL_REPLY_ID};
use crate::contract::helpers::Invariants;
use crate::deposit::DepositStorage;
use crate::deposit_stats::DepositStatsStorage;
use crate::helpers::{
BlacklistKey, Config, MultisigReply, BLACKLIST_PAGE_DEFAULT_LIMIT, BLACKLIST_PAGE_MAX_LIMIT,
CONTRACT_NAME, CONTRACT_VERSION, DEPOSITS_PAGE_DEFAULT_LIMIT, DEPOSITS_PAGE_MAX_LIMIT,
};
use cosmwasm_std::{coin, BankMsg, Coin, Event, Order, Reply, Response, StdResult};
use cosmwasm_std::{coin, Addr, Coin, DepsMut, Event, Order, Reply, Response, StdResult};
use cw4::Cw4Contract;
use cw_controllers::Admin;
use cw_storage_plus::{Bound, Item, Map};
@@ -20,9 +21,12 @@ use nym_ecash_contract_common::counters::PoolCounters;
use nym_ecash_contract_common::deposit::{
DepositData, DepositResponse, LatestDepositResponse, PagedDepositsResponse,
};
use nym_ecash_contract_common::deposit_statistics::DepositsStatistics;
use nym_ecash_contract_common::events::{
DEPOSITED_FUNDS_EVENT_TYPE, DEPOSIT_ID, PROPOSAL_ID_ATTRIBUTE_NAME,
};
use nym_ecash_contract_common::msg::WhitelistedDeposit;
use nym_ecash_contract_common::reduced_deposit::{WhitelistedAccount, WhitelistedAccountsResponse};
use nym_ecash_contract_common::EcashContractError;
use nym_network_defaults::TICKETBOOK_SIZE;
use sylvia::ctx::{ExecCtx, InstantiateCtx, MigrateCtx, QueryCtx};
@@ -41,6 +45,13 @@ pub struct NymEcashContract {
pub(crate) pool_counters: Item<PoolCounters>,
pub(crate) expected_invariants: Item<Invariants>,
/// Information about the performed deposits
pub(crate) deposit_stats: DepositStatsStorage,
/// Map of approved addresses that are allowed to perform deposits using a reduced amount
/// as specified by the saved value.
pub(crate) reduced_deposits: Map<Addr, Coin>,
pub(crate) blacklist: Map<BlacklistKey, Blacklisting>,
pub(crate) deposits: DepositStorage,
@@ -58,6 +69,8 @@ impl NymEcashContract {
config: Item::new("config"),
pool_counters: Item::new("pool_counters"),
expected_invariants: Item::new("expected_invariants"),
deposit_stats: DepositStatsStorage::new(),
reduced_deposits: Map::new("reduced_deposits"),
blacklist: Map::new("blacklist"),
deposits: DepositStorage::new(),
}
@@ -72,6 +85,9 @@ impl NymEcashContract {
group_addr: String,
deposit_amount: Coin,
) -> Result<Response, EcashContractError> {
// all counters, deposits, etc. always use and always will use the same denom
let zero_coin = coin(0, &deposit_amount.denom);
let multisig_addr = ctx.deps.api.addr_validate(&multisig_addr)?;
let holding_account = ctx.deps.api.addr_validate(&holding_account)?;
let group_addr = Cw4Contract(ctx.deps.api.addr_validate(&group_addr).map_err(|_| {
@@ -96,8 +112,9 @@ impl NymEcashContract {
self.pool_counters.save(
ctx.deps.storage,
&PoolCounters {
total_deposited: coin(0, &deposit_amount.denom),
total_redeemed: coin(0, &deposit_amount.denom),
total_deposited: zero_coin.clone(),
total_redeemed: zero_coin.clone(),
tickets_requested_and_not_redeemed: 0,
},
)?;
@@ -110,6 +127,14 @@ impl NymEcashContract {
},
)?;
self.deposit_stats
.deposits_with_default_price
.save(ctx.deps.storage, &0)?;
self.deposit_stats
.deposits_with_default_price_amounts
.save(ctx.deps.storage, &zero_coin)?;
cw2::set_contract_version(ctx.deps.storage, CONTRACT_NAME, CONTRACT_VERSION)?;
set_build_information!(ctx.deps.storage)?;
@@ -161,12 +186,43 @@ impl NymEcashContract {
}
#[sv::msg(query)]
pub fn get_required_deposit_amount(&self, ctx: QueryCtx) -> StdResult<Coin> {
pub fn get_default_deposit_amount(&self, ctx: QueryCtx) -> StdResult<Coin> {
let deposit_amount = self.config.load(ctx.deps.storage)?.deposit_amount;
Ok(deposit_amount)
}
#[sv::msg(query)]
pub fn get_reduced_deposit_amount(
&self,
ctx: QueryCtx,
address: String,
) -> StdResult<Option<Coin>> {
let address = ctx.deps.api.addr_validate(&address)?;
let deposit_amount = self.reduced_deposits.may_load(ctx.deps.storage, address)?;
Ok(deposit_amount)
}
#[sv::msg(query)]
pub fn get_all_whitelisted_accounts(
&self,
ctx: QueryCtx,
) -> StdResult<WhitelistedAccountsResponse> {
let whitelisted_accounts = self
.reduced_deposits
.range(ctx.deps.storage, None, None, Order::Ascending)
.map(|item| {
let (address, deposit) = item?;
Ok(WhitelistedAccount { address, deposit })
})
.collect::<StdResult<Vec<_>>>()?;
Ok(WhitelistedAccountsResponse {
whitelisted_accounts,
})
}
#[sv::msg(query)]
pub fn get_deposit(
&self,
@@ -226,6 +282,40 @@ impl NymEcashContract {
})
}
#[sv::msg(query)]
pub fn get_deposits_statistics(
&self,
ctx: QueryCtx,
) -> Result<DepositsStatistics, EcashContractError> {
let storage = ctx.deps.storage;
let denom = &self.config.load(storage)?.deposit_amount.denom;
let total_deposits_made = self.deposits.total_deposits_made(storage)?;
let total_deposited = self.pool_counters.load(storage)?.total_deposited;
let total_deposits_made_with_default_price = self
.deposit_stats
.get_total_deposits_made_with_default_price(storage)?;
let total_deposited_with_default_price = self
.deposit_stats
.get_total_deposited_with_default_price(storage, denom)?;
let custom = self
.deposit_stats
.get_custom_price_deposits(storage, denom)?;
Ok(DepositsStatistics {
total_deposits_made,
total_deposited,
total_deposits_made_with_default_price,
total_deposited_with_default_price,
total_deposits_made_with_custom_price: custom.total_count,
total_deposited_with_custom_price: custom.total_amount,
deposits_made_with_custom_price: custom.per_account_count,
deposited_with_custom_price: custom.per_account_amount,
})
}
/*=====================
======EXECUTIONS=======
=====================*/
@@ -236,20 +326,48 @@ impl NymEcashContract {
ctx: ExecCtx,
identity_key: String,
) -> Result<Response, EcashContractError> {
let required_deposit = self.config.load(ctx.deps.storage)?.deposit_amount;
let default_deposit = self.config.load(ctx.deps.storage)?.deposit_amount;
let reduced_deposit = self
.reduced_deposits
.may_load(ctx.deps.storage, ctx.info.sender.clone())?;
let submitted = cw_utils::must_pay(&ctx.info, &required_deposit.denom)?;
let submitted = cw_utils::must_pay(&ctx.info, &default_deposit.denom)?;
let mut funds = ctx.info.funds;
if submitted != required_deposit.amount {
let mut funds = ctx.info.funds;
// Whitelisted accounts may deposit at either their reduced price or the
// default price. If the default price is sent, the deposit is treated as
// a regular (non-reduced) deposit for statistics purposes.
if submitted == default_deposit.amount {
self.deposit_stats
.new_default_deposit(ctx.deps.storage, &default_deposit)?;
} else if let Some(reduced_deposit) = reduced_deposit.as_ref() {
// can't do if let chaining due to outdated rustc used for building contracts
if reduced_deposit.amount == submitted {
self.deposit_stats.new_reduced_deposit(
ctx.deps.storage,
&ctx.info.sender,
reduced_deposit,
)?;
} else {
// we are allowed to send reduced amounts, but we sent the wrong amount
return Err(EcashContractError::WrongAmount {
// SAFETY: the call to `must_pay` ensured a single coin has been sent
#[allow(clippy::unwrap_used)]
received: funds.pop().unwrap(),
amount: reduced_deposit.clone(),
});
}
} else {
// we sent wrong amount of tokens
return Err(EcashContractError::WrongAmount {
// SAFETY: the call to `must_pay` ensured a single coin has been sent
#[allow(clippy::unwrap_used)]
received: funds.pop().unwrap(),
amount: required_deposit,
amount: default_deposit,
});
}
};
// global total needed when migrating to the nym pool contract
self.pool_counters
.update(ctx.deps.storage, |mut counters| -> StdResult<_> {
counters.total_deposited.amount += submitted;
@@ -285,6 +403,8 @@ impl NymEcashContract {
Ok(Response::new().add_submessage(msg))
}
/// Old legacy method for requesting ticket redemption by moving them into the holding accounts
/// currently only executed by legacy gateways
#[sv::msg(exec)]
pub fn redeem_tickets(
&self,
@@ -301,22 +421,15 @@ impl NymEcashContract {
self.multisig
.assert_admin(ctx.deps.as_ref(), &ctx.info.sender)?;
let config = self.config.load(ctx.deps.storage)?;
let to_return = self.tickets_redemption_amount(ctx.deps.storage, &config, n)?;
if to_return.amount.is_zero() {
return Ok(Response::new());
}
self.pool_counters
.update(ctx.deps.storage, |mut counters| -> StdResult<_> {
counters.total_redeemed.amount += to_return.amount;
counters.tickets_requested_and_not_redeemed += n as u64;
Ok(counters)
})?;
Ok(Response::new().add_message(BankMsg::Send {
to_address: config.holding_account.to_string(),
amount: vec![to_return],
}))
Ok(Response::new().add_event(
Event::new("ticket_redemption").add_attribute("moved_to_holding_account", "false"),
))
}
#[sv::msg(exec)]
@@ -334,7 +447,7 @@ impl NymEcashContract {
}
#[sv::msg(exec)]
pub fn update_deposit_value(
pub fn update_default_deposit_value(
&self,
ctx: ExecCtx,
new_deposit: Coin,
@@ -343,6 +456,14 @@ impl NymEcashContract {
self.contract_admin
.assert_admin(ctx.deps.as_ref(), &ctx.info.sender)?;
let ticket_book_size = self.get_ticketbook_size(ctx.deps.storage)?;
if new_deposit.amount < cosmwasm_std::Uint128::from(ticket_book_size) {
return Err(EcashContractError::DepositBelowTicketBookSize {
amount: new_deposit.amount,
ticket_book_size,
});
}
let deposit_str = new_deposit.to_string();
self.config
.update(ctx.deps.storage, |mut cfg| -> StdResult<_> {
@@ -352,6 +473,85 @@ impl NymEcashContract {
Ok(Response::new().add_attribute("updated_deposit", deposit_str))
}
pub(crate) fn add_reduced_deposit_address(
&self,
deps: DepsMut,
address: Addr,
deposit: &Coin,
) -> Result<(), EcashContractError> {
// the reduced price must be strictly less than the default to avoid
// accidentally misconfiguring an address to pay more than everyone else
let default = self.config.load(deps.storage)?.deposit_amount;
if deposit.denom != default.denom {
return Err(EcashContractError::InvalidReducedDepositDenom {
expected: default.denom,
got: deposit.denom.clone(),
});
}
if deposit.amount >= default.amount {
return Err(EcashContractError::ReducedDepositNotReduced {
reduced: deposit.amount,
default: default.amount,
});
}
let ticket_book_size = self.get_ticketbook_size(deps.storage)?;
if deposit.amount < cosmwasm_std::Uint128::from(ticket_book_size) {
return Err(EcashContractError::DepositBelowTicketBookSize {
amount: deposit.amount,
ticket_book_size,
});
}
self.reduced_deposits.save(deps.storage, address, deposit)?;
Ok(())
}
#[sv::msg(exec)]
pub fn set_reduced_deposit_price(
&self,
ctx: ExecCtx,
address: String,
deposit: Coin,
) -> Result<Response, EcashContractError> {
self.contract_admin
.assert_admin(ctx.deps.as_ref(), &ctx.info.sender)?;
let addr = ctx.deps.api.addr_validate(&address)?;
self.add_reduced_deposit_address(ctx.deps, addr.clone(), &deposit)?;
Ok(Response::new()
.add_attribute("action", "set_reduced_deposit_price")
.add_attribute("address", address)
.add_attribute("deposit", deposit.to_string()))
}
/// Removes the reduced deposit price for a given address, reverting them to
/// the default deposit amount. This is safe to call even if the address has
/// already deposited at the reduced price — their next deposit will simply
/// use the default price. Historical deposit statistics are not affected.
#[sv::msg(exec)]
pub fn remove_reduced_deposit_price(
&self,
ctx: ExecCtx,
address: String,
) -> Result<Response, EcashContractError> {
self.contract_admin
.assert_admin(ctx.deps.as_ref(), &ctx.info.sender)?;
let addr = ctx.deps.api.addr_validate(&address)?;
if !self.reduced_deposits.has(ctx.deps.storage, addr.clone()) {
return Err(EcashContractError::NoReducedDepositPrice { address });
}
self.reduced_deposits.remove(ctx.deps.storage, addr);
Ok(Response::new()
.add_attribute("action", "remove_reduced_deposit_price")
.add_attribute("address", address))
}
#[sv::msg(exec)]
pub fn propose_to_blacklist(
&self,
@@ -459,11 +659,15 @@ impl NymEcashContract {
=======MIGRATION=======
=====================*/
#[sv::msg(migrate)]
pub fn migrate(&self, ctx: MigrateCtx) -> Result<Response, EcashContractError> {
pub fn migrate(
&self,
ctx: MigrateCtx,
initial_whitelist: Vec<WhitelistedDeposit>,
) -> Result<Response, EcashContractError> {
set_build_information!(ctx.deps.storage)?;
cw2::ensure_from_older_version(ctx.deps.storage, CONTRACT_NAME, CONTRACT_VERSION)?;
queued_migrations::remove_redemption_gateway_share(ctx.deps)?;
queued_migrations::add_tiered_pricing(ctx.deps, initial_whitelist)?;
Ok(Response::new())
}
+293 -32
View File
@@ -1,42 +1,303 @@
// Copyright 2024 - Nym Technologies SA <contact@nymtech.net>
// Copyright 2026 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0
use crate::contract::NymEcashContract;
use crate::helpers::Config;
use cosmwasm_std::{Addr, Coin, Decimal, DepsMut};
use cw4::Cw4Contract;
use cw_storage_plus::Item;
use cosmwasm_std::DepsMut;
use nym_ecash_contract_common::msg::WhitelistedDeposit;
use nym_ecash_contract_common::EcashContractError;
use serde::{Deserialize, Serialize};
pub fn remove_redemption_gateway_share(deps: DepsMut) -> Result<(), EcashContractError> {
#[derive(Serialize, Deserialize)]
struct OldConfig {
group_addr: Cw4Contract,
holding_account: Addr,
pub fn add_tiered_pricing(
mut deps: DepsMut,
initial_whitelist: Vec<WhitelistedDeposit>,
) -> Result<(), EcashContractError> {
let contract = NymEcashContract::new();
redemption_gateway_share: Decimal,
deposit_amount: Coin,
// All the deposits made so far were performed with the default price.
let deposits_performed = contract.deposits.total_deposits_made(deps.storage)?;
let deposits_amounts = contract.pool_counters.load(deps.storage)?.total_deposited;
contract
.deposit_stats
.deposits_with_default_price
.save(deps.storage, &deposits_performed)?;
contract
.deposit_stats
.deposits_with_default_price_amounts
.save(deps.storage, &deposits_amounts)?;
// Seed the whitelist with the initial set of reduced deposit prices.
for whitelisted in initial_whitelist {
let addr = deps.api.addr_validate(&whitelisted.address)?;
contract.add_reduced_deposit_address(deps.branch(), addr, &whitelisted.deposit)?;
}
impl From<OldConfig> for Config {
fn from(config: OldConfig) -> Self {
Config {
group_addr: config.group_addr,
holding_account: config.holding_account,
deposit_amount: config.deposit_amount,
}
}
}
const OLD_CONFIG: Item<OldConfig> = Item::new("config");
let old_config = OLD_CONFIG.load(deps.storage)?;
let new_config = old_config.into();
NymEcashContract::new()
.config
.save(deps.storage, &new_config)?;
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use crate::contract::helpers::Invariants;
use crate::deposit::DepositStorage;
use crate::deposit_stats::DepositStatsStorage;
use crate::helpers::Config;
use cosmwasm_std::testing::{mock_dependencies, MockApi, MockQuerier};
use cosmwasm_std::{coin, Empty, MemoryStorage, OwnedDeps, Uint128};
use cw4::Cw4Contract;
use cw_storage_plus::Item;
use nym_ecash_contract_common::counters::PoolCounters;
const DENOM: &str = "unym";
const DEFAULT_DEPOSIT: u128 = 75_000_000;
const TICKET_BOOK_SIZE: u64 = 50;
/// Initialise the contract config and invariants so that whitelist
/// validation during migration has the values it needs.
fn save_config_and_invariants(
deps: &mut OwnedDeps<MemoryStorage, MockApi, MockQuerier<Empty>>,
) {
let contract = NymEcashContract::new();
let group_addr = deps.api.addr_make("group");
let holding_account = deps.api.addr_make("holding");
contract
.config
.save(
deps.as_mut().storage,
&Config {
group_addr: Cw4Contract(group_addr),
holding_account,
deposit_amount: coin(DEFAULT_DEPOSIT, DENOM),
},
)
.unwrap();
contract
.expected_invariants
.save(
deps.as_mut().storage,
&Invariants {
ticket_book_size: TICKET_BOOK_SIZE,
},
)
.unwrap();
}
fn save_pool_counters(storage: &mut dyn cosmwasm_std::Storage, total_deposited: u128) {
let pool_counters: Item<PoolCounters> = Item::new("pool_counters");
pool_counters
.save(
storage,
&PoolCounters {
total_deposited: coin(total_deposited, DENOM),
total_redeemed: coin(0, DENOM),
tickets_requested_and_not_redeemed: 0,
},
)
.unwrap();
}
#[test]
fn migration_with_no_prior_deposits_initialises_stats_to_zero() {
let mut deps = mock_dependencies();
// No deposit_id_counter saved — contract never had a deposit.
save_pool_counters(deps.as_mut().storage, 0);
add_tiered_pricing(deps.as_mut(), vec![]).unwrap();
let stats = DepositStatsStorage::new();
assert_eq!(
stats
.deposits_with_default_price
.load(deps.as_ref().storage)
.unwrap(),
0
);
assert_eq!(
stats
.deposits_with_default_price_amounts
.load(deps.as_ref().storage)
.unwrap(),
coin(0, DENOM)
);
}
#[test]
fn migration_with_prior_deposits_backfills_correct_count() {
let mut deps = mock_dependencies();
let n_deposits: u32 = 3;
let total: u128 = n_deposits as u128 * 75_000_000;
// Simulate n_deposits having been made: counter stores the next available id,
// which equals the number of deposits already performed.
let deposits = DepositStorage::new();
deposits
.deposit_id_counter
.save(deps.as_mut().storage, &n_deposits)
.unwrap();
save_pool_counters(deps.as_mut().storage, total);
add_tiered_pricing(deps.as_mut(), vec![]).unwrap();
let stats = DepositStatsStorage::new();
assert_eq!(
stats
.deposits_with_default_price
.load(deps.as_ref().storage)
.unwrap(),
n_deposits
);
assert_eq!(
stats
.deposits_with_default_price_amounts
.load(deps.as_ref().storage)
.unwrap(),
coin(total, DENOM)
);
}
#[test]
fn migration_with_single_deposit_backfills_count_of_one() {
let mut deps = mock_dependencies();
// After one deposit, next_id returns 0 and saves counter=1.
let deposits = DepositStorage::new();
deposits
.deposit_id_counter
.save(deps.as_mut().storage, &1u32)
.unwrap();
save_pool_counters(deps.as_mut().storage, 75_000_000);
add_tiered_pricing(deps.as_mut(), vec![]).unwrap();
let stats = DepositStatsStorage::new();
assert_eq!(
stats
.deposits_with_default_price
.load(deps.as_ref().storage)
.unwrap(),
1
);
}
#[test]
fn migration_stores_valid_whitelist_entries() {
let mut deps = mock_dependencies();
save_pool_counters(deps.as_mut().storage, 0);
save_config_and_invariants(&mut deps);
let addr1 = deps.api.addr_make("alice");
let addr2 = deps.api.addr_make("bob");
let whitelist = vec![
WhitelistedDeposit {
address: addr1.to_string(),
deposit: coin(10_000_000, DENOM),
},
WhitelistedDeposit {
address: addr2.to_string(),
deposit: coin(50_000_000, DENOM),
},
];
add_tiered_pricing(deps.as_mut(), whitelist).unwrap();
let contract = NymEcashContract::new();
assert_eq!(
contract
.reduced_deposits
.load(deps.as_ref().storage, addr1)
.unwrap(),
coin(10_000_000, DENOM)
);
assert_eq!(
contract
.reduced_deposits
.load(deps.as_ref().storage, addr2)
.unwrap(),
coin(50_000_000, DENOM)
);
}
#[test]
fn migration_rejects_wrong_denom() {
let mut deps = mock_dependencies();
save_pool_counters(deps.as_mut().storage, 0);
save_config_and_invariants(&mut deps);
let whitelist = vec![WhitelistedDeposit {
address: deps.api.addr_make("alice").to_string(),
deposit: coin(10_000_000, "uatom"),
}];
let err = add_tiered_pricing(deps.as_mut(), whitelist).unwrap_err();
assert_eq!(
err,
EcashContractError::InvalidReducedDepositDenom {
expected: DENOM.to_string(),
got: "uatom".to_string(),
}
);
}
#[test]
fn migration_rejects_amount_not_less_than_default() {
let mut deps = mock_dependencies();
save_pool_counters(deps.as_mut().storage, 0);
save_config_and_invariants(&mut deps);
// Equal to default — should fail
let whitelist = vec![WhitelistedDeposit {
address: deps.api.addr_make("alice").to_string(),
deposit: coin(DEFAULT_DEPOSIT, DENOM),
}];
let err = add_tiered_pricing(deps.as_mut(), whitelist).unwrap_err();
assert_eq!(
err,
EcashContractError::ReducedDepositNotReduced {
reduced: Uint128::new(DEFAULT_DEPOSIT),
default: Uint128::new(DEFAULT_DEPOSIT),
}
);
// Greater than default — should also fail
let whitelist = vec![WhitelistedDeposit {
address: deps.api.addr_make("alice").to_string(),
deposit: coin(DEFAULT_DEPOSIT + 1, DENOM),
}];
let err = add_tiered_pricing(deps.as_mut(), whitelist).unwrap_err();
assert_eq!(
err,
EcashContractError::ReducedDepositNotReduced {
reduced: Uint128::new(DEFAULT_DEPOSIT + 1),
default: Uint128::new(DEFAULT_DEPOSIT),
}
);
}
#[test]
fn migration_rejects_amount_below_ticket_book_size() {
let mut deps = mock_dependencies();
save_pool_counters(deps.as_mut().storage, 0);
save_config_and_invariants(&mut deps);
let whitelist = vec![WhitelistedDeposit {
address: deps.api.addr_make("alice").to_string(),
deposit: coin(TICKET_BOOK_SIZE as u128 - 1, DENOM),
}];
let err = add_tiered_pricing(deps.as_mut(), whitelist).unwrap_err();
assert_eq!(
err,
EcashContractError::DepositBelowTicketBookSize {
amount: Uint128::new(TICKET_BOOK_SIZE as u128 - 1),
ticket_book_size: TICKET_BOOK_SIZE,
}
);
}
}
+413 -7
View File
@@ -3,8 +3,8 @@
use crate::contract::NymEcashContract;
use cosmwasm_std::testing::{message_info, mock_dependencies, mock_env, MockApi, MockQuerier};
use cosmwasm_std::{coin, Addr, Empty, Env, MemoryStorage, OwnedDeps};
use sylvia::ctx::{InstantiateCtx, QueryCtx};
use cosmwasm_std::{coin, Addr, Empty, Env, MemoryStorage, MessageInfo, OwnedDeps};
use sylvia::ctx::{ExecCtx, InstantiateCtx, QueryCtx};
pub const TEST_DENOM: &str = "unym";
@@ -55,30 +55,48 @@ impl TestSetup {
pub fn query_ctx(&self) -> QueryCtx<'_> {
QueryCtx::from((self.deps.as_ref(), self.env.clone()))
}
pub fn exec_ctx(&mut self, sender: MessageInfo) -> ExecCtx<'_> {
ExecCtx::from((self.deps.as_mut(), self.env.clone(), sender))
}
pub fn admin_info(&self) -> MessageInfo {
let admin = self
.contract
.contract_admin
.get(self.deps.as_ref())
.unwrap()
.unwrap();
message_info(&admin, &[])
}
}
#[cfg(test)]
mod tests {
use super::*;
use cosmwasm_std::coin;
use nym_ecash_contract_common::deposit::Deposit;
use nym_ecash_contract_common::reduced_deposit::WhitelistedAccount;
use nym_ecash_contract_common::EcashContractError;
use sylvia::anyhow;
const CONTRACT: NymEcashContract = NymEcashContract::new();
#[test]
fn deposit_queries() -> anyhow::Result<()> {
let mut test = TestSetup::init();
// no deposit
let res = test.contract.get_deposit(test.query_ctx(), 42)?;
let res = CONTRACT.get_deposit(test.query_ctx(), 42)?;
assert!(res.deposit.is_none());
let deps = test.deps.as_mut();
let deposit_id = test.contract.deposits.save_deposit(
deps.storage,
let deposit_id = CONTRACT.deposits.save_deposit(
test.deps.as_mut().storage,
"GLdR2NRVZBiCoCbv4fNqt9wUJZAnNjGXHkx3TjVAUzrK".to_string(),
)?;
// deposit exists
let res = test.contract.get_deposit(test.query_ctx(), deposit_id)?;
let res = CONTRACT.get_deposit(test.query_ctx(), deposit_id)?;
let expected = Deposit {
bs58_encoded_ed25519_pubkey: "GLdR2NRVZBiCoCbv4fNqt9wUJZAnNjGXHkx3TjVAUzrK".to_string(),
};
@@ -87,4 +105,392 @@ mod tests {
Ok(())
}
#[test]
fn get_default_deposit_amount_returns_configured_value() -> anyhow::Result<()> {
let test = TestSetup::init();
let amount = CONTRACT.get_default_deposit_amount(test.query_ctx())?;
assert_eq!(amount, coin(75_000_000, TEST_DENOM));
Ok(())
}
#[test]
fn get_reduced_deposit_amount_returns_none_for_unlisted_address() -> anyhow::Result<()> {
let test = TestSetup::init();
let unknown = test.deps.api.addr_make("unknown");
let amount = CONTRACT.get_reduced_deposit_amount(test.query_ctx(), unknown.to_string())?;
assert!(amount.is_none());
Ok(())
}
#[test]
fn get_reduced_deposit_amount_returns_amount_for_whitelisted_address() -> anyhow::Result<()> {
let mut test = TestSetup::init();
let addr = test.deps.api.addr_make("whitelisted");
let reduced = coin(10_000_000, TEST_DENOM);
CONTRACT
.reduced_deposits
.save(test.deps.as_mut().storage, addr.clone(), &reduced)?;
let amount = CONTRACT.get_reduced_deposit_amount(test.query_ctx(), addr.to_string())?;
assert_eq!(amount, Some(reduced));
Ok(())
}
// --- get_all_whitelisted_accounts ---
#[test]
fn get_all_whitelisted_accounts_returns_empty_by_default() -> anyhow::Result<()> {
let test = TestSetup::init();
let res = CONTRACT.get_all_whitelisted_accounts(test.query_ctx())?;
assert!(res.whitelisted_accounts.is_empty());
Ok(())
}
#[test]
fn get_all_whitelisted_accounts_returns_all_entries() -> anyhow::Result<()> {
let mut test = TestSetup::init();
let alice = test.deps.api.addr_make("alice");
let bob = test.deps.api.addr_make("bob");
let admin = test.admin_info();
CONTRACT.set_reduced_deposit_price(
test.exec_ctx(admin),
alice.to_string(),
coin(10_000_000, TEST_DENOM),
)?;
let admin = test.admin_info();
CONTRACT.set_reduced_deposit_price(
test.exec_ctx(admin),
bob.to_string(),
coin(5_000_000, TEST_DENOM),
)?;
let res = CONTRACT.get_all_whitelisted_accounts(test.query_ctx())?;
assert_eq!(res.whitelisted_accounts.len(), 2);
assert!(res.whitelisted_accounts.contains(&WhitelistedAccount {
address: alice,
deposit: coin(10_000_000, TEST_DENOM),
}));
assert!(res.whitelisted_accounts.contains(&WhitelistedAccount {
address: bob,
deposit: coin(5_000_000, TEST_DENOM),
}));
Ok(())
}
// --- set_reduced_deposit_price ---
#[test]
fn set_reduced_deposit_price_requires_admin() -> anyhow::Result<()> {
let mut test = TestSetup::init();
let non_admin = test.deps.api.addr_make("non_admin");
let addr = test.deps.api.addr_make("alice");
let err = CONTRACT
.set_reduced_deposit_price(
test.exec_ctx(message_info(&non_admin, &[])),
addr.to_string(),
coin(10_000_000, TEST_DENOM),
)
.unwrap_err();
assert!(matches!(err, EcashContractError::Admin(_)));
Ok(())
}
#[test]
fn set_reduced_deposit_price_rejects_wrong_denom() -> anyhow::Result<()> {
let mut test = TestSetup::init();
let addr = test.deps.api.addr_make("alice");
let admin = test.admin_info();
let err = CONTRACT
.set_reduced_deposit_price(
test.exec_ctx(admin),
addr.to_string(),
coin(10_000_000, "uatom"),
)
.unwrap_err();
assert_eq!(
err,
EcashContractError::InvalidReducedDepositDenom {
expected: TEST_DENOM.to_string(),
got: "uatom".to_string(),
}
);
Ok(())
}
#[test]
fn set_reduced_deposit_price_rejects_amount_equal_to_default() -> anyhow::Result<()> {
let mut test = TestSetup::init();
let addr = test.deps.api.addr_make("alice");
let admin = test.admin_info();
let err = CONTRACT
.set_reduced_deposit_price(
test.exec_ctx(admin),
addr.to_string(),
coin(75_000_000, TEST_DENOM), // same as default
)
.unwrap_err();
assert!(matches!(
err,
EcashContractError::ReducedDepositNotReduced { .. }
));
Ok(())
}
#[test]
fn set_reduced_deposit_price_rejects_amount_above_default() -> anyhow::Result<()> {
let mut test = TestSetup::init();
let addr = test.deps.api.addr_make("alice");
let admin = test.admin_info();
let err = CONTRACT
.set_reduced_deposit_price(
test.exec_ctx(admin),
addr.to_string(),
coin(100_000_000, TEST_DENOM),
)
.unwrap_err();
assert!(matches!(
err,
EcashContractError::ReducedDepositNotReduced { .. }
));
Ok(())
}
#[test]
fn set_reduced_deposit_price_rejects_amount_below_ticket_book_size() -> anyhow::Result<()> {
let mut test = TestSetup::init();
let addr = test.deps.api.addr_make("alice");
let admin = test.admin_info();
let err = CONTRACT
.set_reduced_deposit_price(
test.exec_ctx(admin),
addr.to_string(),
coin(10, TEST_DENOM), // below ticket_book_size (50)
)
.unwrap_err();
assert!(matches!(
err,
EcashContractError::DepositBelowTicketBookSize { .. }
));
Ok(())
}
#[test]
fn set_reduced_deposit_price_stores_price() -> anyhow::Result<()> {
let mut test = TestSetup::init();
let addr = test.deps.api.addr_make("alice");
let reduced = coin(10_000_000, TEST_DENOM);
let admin = test.admin_info();
CONTRACT.set_reduced_deposit_price(
test.exec_ctx(admin),
addr.to_string(),
reduced.clone(),
)?;
let stored = CONTRACT.get_reduced_deposit_amount(test.query_ctx(), addr.to_string())?;
assert_eq!(stored, Some(reduced));
Ok(())
}
#[test]
fn set_reduced_deposit_price_overwrites_existing_price() -> anyhow::Result<()> {
let mut test = TestSetup::init();
let addr = test.deps.api.addr_make("alice");
let admin = test.admin_info();
CONTRACT.set_reduced_deposit_price(
test.exec_ctx(admin),
addr.to_string(),
coin(10_000_000, TEST_DENOM),
)?;
let admin = test.admin_info();
CONTRACT.set_reduced_deposit_price(
test.exec_ctx(admin),
addr.to_string(),
coin(5_000_000, TEST_DENOM),
)?;
let stored = CONTRACT.get_reduced_deposit_amount(test.query_ctx(), addr.to_string())?;
assert_eq!(stored, Some(coin(5_000_000, TEST_DENOM)));
Ok(())
}
// --- remove_reduced_deposit_price ---
#[test]
fn remove_reduced_deposit_price_requires_admin() -> anyhow::Result<()> {
let mut test = TestSetup::init();
let non_admin = test.deps.api.addr_make("non_admin");
let addr = test.deps.api.addr_make("alice");
let err = CONTRACT
.remove_reduced_deposit_price(
test.exec_ctx(message_info(&non_admin, &[])),
addr.to_string(),
)
.unwrap_err();
assert!(matches!(err, EcashContractError::Admin(_)));
Ok(())
}
#[test]
fn remove_reduced_deposit_price_clears_stored_price() -> anyhow::Result<()> {
let mut test = TestSetup::init();
let addr = test.deps.api.addr_make("alice");
let admin = test.admin_info();
CONTRACT.set_reduced_deposit_price(
test.exec_ctx(admin),
addr.to_string(),
coin(10_000_000, TEST_DENOM),
)?;
let admin = test.admin_info();
CONTRACT.remove_reduced_deposit_price(test.exec_ctx(admin), addr.to_string())?;
let stored = CONTRACT.get_reduced_deposit_amount(test.query_ctx(), addr.to_string())?;
assert!(stored.is_none());
Ok(())
}
#[test]
fn remove_reduced_deposit_price_errors_for_unlisted_address() -> anyhow::Result<()> {
let mut test = TestSetup::init();
let addr = test.deps.api.addr_make("alice");
let admin = test.admin_info();
let err = CONTRACT
.remove_reduced_deposit_price(test.exec_ctx(admin), addr.to_string())
.unwrap_err();
assert_eq!(
err,
EcashContractError::NoReducedDepositPrice {
address: addr.to_string()
}
);
Ok(())
}
// --- get_deposits_statistics ---
#[test]
fn get_deposits_statistics_returns_zeroes_after_init() -> anyhow::Result<()> {
let test = TestSetup::init();
let stats = CONTRACT.get_deposits_statistics(test.query_ctx())?;
assert_eq!(stats.total_deposits_made, 0);
assert_eq!(stats.total_deposited, coin(0, TEST_DENOM));
assert_eq!(stats.total_deposits_made_with_default_price, 0);
assert_eq!(
stats.total_deposited_with_default_price,
coin(0, TEST_DENOM)
);
assert_eq!(stats.total_deposits_made_with_custom_price, 0);
assert_eq!(stats.total_deposited_with_custom_price, coin(0, TEST_DENOM));
assert!(stats.deposits_made_with_custom_price.is_empty());
assert!(stats.deposited_with_custom_price.is_empty());
CONTRACT
.deposit_stats
.assert_counts_consistent(test.deps.as_ref().storage, stats.total_deposits_made);
Ok(())
}
#[test]
fn deposit_stats_invariant_holds_after_mixed_deposits() -> anyhow::Result<()> {
let mut test = TestSetup::init();
let alice = test.deps.api.addr_make("alice");
let bob = test.deps.api.addr_make("bob");
// whitelist alice
let admin = test.admin_info();
CONTRACT.set_reduced_deposit_price(
test.exec_ctx(admin),
alice.to_string(),
coin(10_000_000, TEST_DENOM),
)?;
// alice deposits at reduced price
let alice_info = message_info(&alice, &[coin(10_000_000, TEST_DENOM)]);
CONTRACT.deposit_ticket_book_funds(
test.exec_ctx(alice_info),
"GLdR2NRVZBiCoCbv4fNqt9wUJZAnNjGXHkx3TjVAUzrK".to_string(),
)?;
// bob deposits at default price
let bob_info = message_info(&bob, &[coin(75_000_000, TEST_DENOM)]);
CONTRACT.deposit_ticket_book_funds(
test.exec_ctx(bob_info),
"GLdR2NRVZBiCoCbv4fNqt9wUJZAnNjGXHkx3TjVAUzrK".to_string(),
)?;
// alice deposits again at reduced price
let alice_info = message_info(&alice, &[coin(10_000_000, TEST_DENOM)]);
CONTRACT.deposit_ticket_book_funds(
test.exec_ctx(alice_info),
"GLdR2NRVZBiCoCbv4fNqt9wUJZAnNjGXHkx3TjVAUzrK".to_string(),
)?;
// alice deposits at the default price — should be treated as a normal deposit
let alice_info = message_info(&alice, &[coin(75_000_000, TEST_DENOM)]);
CONTRACT.deposit_ticket_book_funds(
test.exec_ctx(alice_info),
"GLdR2NRVZBiCoCbv4fNqt9wUJZAnNjGXHkx3TjVAUzrK".to_string(),
)?;
let total = CONTRACT
.deposits
.total_deposits_made(test.deps.as_ref().storage)?;
assert_eq!(total, 4);
CONTRACT
.deposit_stats
.assert_counts_consistent(test.deps.as_ref().storage, total);
Ok(())
}
}
+26 -1
View File
@@ -29,6 +29,14 @@ impl DepositStorage {
.map_err(Into::into)
}
/// Returns the total number of deposits ever made.
///
/// The deposit id counter stores the next available id, which equals the
/// total count (first deposit gets id 0, counter becomes 1, and so on).
pub fn total_deposits_made(&self, storage: &dyn Storage) -> Result<u32, EcashContractError> {
Ok(self.deposit_id_counter.may_load(storage)?.unwrap_or(0))
}
fn next_id(&self, store: &mut dyn Storage) -> Result<DepositId, EcashContractError> {
let id: DepositId = self.deposit_id_counter.may_load(store)?.unwrap_or_default();
let next_id = id + 1;
@@ -115,8 +123,8 @@ impl StoredDeposits {
#[cfg(test)]
mod tests {
use super::*;
use crate::support::tests::test_rng;
use cosmwasm_std::testing::mock_dependencies;
use nym_contracts_common_testing::test_rng;
use nym_crypto::asymmetric::ed25519;
#[test]
@@ -142,6 +150,23 @@ mod tests {
Ok(())
}
#[test]
fn total_deposits_made_tracks_count() -> anyhow::Result<()> {
let mut deps = mock_dependencies();
let storage = DepositStorage::new();
assert_eq!(storage.total_deposits_made(deps.as_ref().storage)?, 0);
let _ = storage.next_id(deps.as_mut().storage)?;
assert_eq!(storage.total_deposits_made(deps.as_ref().storage)?, 1);
let _ = storage.next_id(deps.as_mut().storage)?;
let _ = storage.next_id(deps.as_mut().storage)?;
assert_eq!(storage.total_deposits_made(deps.as_ref().storage)?, 3);
Ok(())
}
#[test]
fn iterating_over_deposits() {
let mut deps = mock_dependencies();
+374
View File
@@ -0,0 +1,374 @@
// Copyright 2026 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: GPL-3.0-only
use cosmwasm_std::{coin, Addr, Coin, Order, StdResult, Storage};
use cw_storage_plus::{Item, Map};
use nym_ecash_contract_common::EcashContractError;
use std::collections::HashMap;
pub(crate) struct DepositStatsStorage {
/// Total deposits performed with the default price
pub(crate) deposits_with_default_price: Item<u32>,
/// Total amounts deposited with the default price
pub(crate) deposits_with_default_price_amounts: Item<Coin>,
/// Total deposits performed with a custom price by account
pub(crate) deposits_with_custom_price: Map<Addr, u32>,
/// Total amounts deposited with a custom price by account
pub(crate) deposits_with_custom_price_amounts: Map<Addr, Coin>,
}
impl DepositStatsStorage {
pub(crate) const fn new() -> Self {
Self {
deposits_with_default_price: Item::new("deposits_with_default_price"),
deposits_with_default_price_amounts: Item::new("deposits_with_default_price_amounts"),
deposits_with_custom_price: Map::new("deposits_with_custom_price"),
deposits_with_custom_price_amounts: Map::new("deposits_with_custom_price_amounts"),
}
}
pub(crate) fn new_default_deposit(
&self,
store: &mut dyn Storage,
deposited: &Coin,
) -> Result<(), EcashContractError> {
self.deposits_with_default_price
.update(store, |count| StdResult::Ok(count + 1))?;
self.deposits_with_default_price_amounts
.update(store, |amount| {
let mut updated = amount;
updated.amount += deposited.amount;
StdResult::Ok(updated)
})?;
Ok(())
}
pub(crate) fn new_reduced_deposit(
&self,
store: &mut dyn Storage,
sender: &Addr,
deposited: &Coin,
) -> Result<(), EcashContractError> {
self.deposits_with_custom_price
.update(store, sender.clone(), |count| {
StdResult::Ok(count.unwrap_or_default() + 1)
})?;
self.deposits_with_custom_price_amounts
.update(store, sender.clone(), |amount| {
let updated = match amount {
None => deposited.clone(),
Some(mut existing) => {
existing.amount += deposited.amount;
existing
}
};
StdResult::Ok(updated)
})?;
Ok(())
}
pub(crate) fn get_total_deposits_made_with_default_price(
&self,
store: &dyn Storage,
) -> StdResult<u32> {
Ok(self
.deposits_with_default_price
.may_load(store)?
.unwrap_or(0))
}
pub(crate) fn get_total_deposited_with_default_price(
&self,
store: &dyn Storage,
denom: &str,
) -> StdResult<Coin> {
Ok(self
.deposits_with_default_price_amounts
.may_load(store)?
.unwrap_or_else(|| coin(0, denom)))
}
pub(crate) fn get_custom_price_deposits(
&self,
store: &dyn Storage,
denom: &str,
) -> StdResult<CustomPriceDepositStats> {
let mut total_count = 0;
let mut total_amount = coin(0, denom);
let mut per_account_count = HashMap::new();
let mut per_account_amount = HashMap::new();
for item in self
.deposits_with_custom_price
.range(store, None, None, Order::Ascending)
{
let (addr, count) = item?;
total_count += count;
per_account_count.insert(addr.into_string(), count);
}
for item in
self.deposits_with_custom_price_amounts
.range(store, None, None, Order::Ascending)
{
let (addr, amount) = item?;
total_amount.amount += amount.amount;
per_account_amount.insert(addr.into_string(), amount);
}
Ok(CustomPriceDepositStats {
total_count,
total_amount,
per_account_count,
per_account_amount,
})
}
}
impl DepositStatsStorage {
/// Asserts that the per-tier deposit counts sum to the given total.
/// Only meaningful when all deposits go through the contract entry point
/// (not after raw storage writes that bypass bookkeeping).
#[cfg(test)]
pub(crate) fn assert_counts_consistent(&self, store: &dyn Storage, total_deposits_made: u32) {
let default_count = self
.get_total_deposits_made_with_default_price(store)
.unwrap();
let custom = self.get_custom_price_deposits(store, "unused").unwrap();
assert_eq!(
default_count + custom.total_count,
total_deposits_made,
"deposit stats invariant violated: default ({default_count}) + custom ({}) != total ({total_deposits_made})",
custom.total_count,
);
}
}
pub(crate) struct CustomPriceDepositStats {
pub(crate) total_count: u32,
pub(crate) total_amount: Coin,
pub(crate) per_account_count: HashMap<String, u32>,
pub(crate) per_account_amount: HashMap<String, Coin>,
}
#[cfg(test)]
mod tests {
use super::*;
use cosmwasm_std::coin;
use cosmwasm_std::testing::mock_dependencies;
const DENOM: &str = "unym";
const DEFAULT_AMOUNT: u128 = 75_000_000;
const REDUCED_AMOUNT: u128 = 10_000_000;
/// Mirror what `instantiate` does: zero-initialise the default-price counters.
/// The custom-price Maps need no initialisation (they start empty).
fn init_stats(storage: &mut dyn Storage) -> DepositStatsStorage {
let stats = DepositStatsStorage::new();
stats.deposits_with_default_price.save(storage, &0).unwrap();
stats
.deposits_with_default_price_amounts
.save(storage, &coin(0, DENOM))
.unwrap();
stats
}
#[test]
fn single_default_deposit_increments_count_and_amount() {
let mut deps = mock_dependencies();
let stats = init_stats(deps.as_mut().storage);
stats
.new_default_deposit(deps.as_mut().storage, &coin(DEFAULT_AMOUNT, DENOM))
.unwrap();
assert_eq!(
stats
.deposits_with_default_price
.load(deps.as_ref().storage)
.unwrap(),
1
);
assert_eq!(
stats
.deposits_with_default_price_amounts
.load(deps.as_ref().storage)
.unwrap(),
coin(DEFAULT_AMOUNT, DENOM)
);
}
#[test]
fn multiple_default_deposits_accumulate() {
let mut deps = mock_dependencies();
let stats = init_stats(deps.as_mut().storage);
for _ in 0..3 {
stats
.new_default_deposit(deps.as_mut().storage, &coin(DEFAULT_AMOUNT, DENOM))
.unwrap();
}
assert_eq!(
stats
.deposits_with_default_price
.load(deps.as_ref().storage)
.unwrap(),
3
);
assert_eq!(
stats
.deposits_with_default_price_amounts
.load(deps.as_ref().storage)
.unwrap(),
coin(DEFAULT_AMOUNT * 3, DENOM)
);
}
#[test]
fn single_reduced_deposit_is_tracked_per_address() {
let mut deps = mock_dependencies();
let stats = init_stats(deps.as_mut().storage);
let alice = deps.api.addr_make("alice");
stats
.new_reduced_deposit(deps.as_mut().storage, &alice, &coin(REDUCED_AMOUNT, DENOM))
.unwrap();
assert_eq!(
stats
.deposits_with_custom_price
.load(deps.as_ref().storage, alice.clone())
.unwrap(),
1
);
assert_eq!(
stats
.deposits_with_custom_price_amounts
.load(deps.as_ref().storage, alice.clone())
.unwrap(),
coin(REDUCED_AMOUNT, DENOM)
);
// default-price stats must be untouched
assert_eq!(
stats
.deposits_with_default_price
.load(deps.as_ref().storage)
.unwrap(),
0
);
}
#[test]
fn multiple_reduced_deposits_same_address_accumulate() {
let mut deps = mock_dependencies();
let stats = init_stats(deps.as_mut().storage);
let alice = deps.api.addr_make("alice");
for _ in 0..4 {
stats
.new_reduced_deposit(deps.as_mut().storage, &alice, &coin(REDUCED_AMOUNT, DENOM))
.unwrap();
}
assert_eq!(
stats
.deposits_with_custom_price
.load(deps.as_ref().storage, alice.clone())
.unwrap(),
4
);
assert_eq!(
stats
.deposits_with_custom_price_amounts
.load(deps.as_ref().storage, alice.clone())
.unwrap(),
coin(REDUCED_AMOUNT * 4, DENOM)
);
}
#[test]
fn reduced_deposits_for_different_addresses_tracked_independently() {
let mut deps = mock_dependencies();
let stats = init_stats(deps.as_mut().storage);
let alice = deps.api.addr_make("alice");
let bob = deps.api.addr_make("bob");
stats
.new_reduced_deposit(deps.as_mut().storage, &alice, &coin(REDUCED_AMOUNT, DENOM))
.unwrap();
stats
.new_reduced_deposit(deps.as_mut().storage, &alice, &coin(REDUCED_AMOUNT, DENOM))
.unwrap();
stats
.new_reduced_deposit(deps.as_mut().storage, &bob, &coin(5_000_000, DENOM))
.unwrap();
assert_eq!(
stats
.deposits_with_custom_price
.load(deps.as_ref().storage, alice.clone())
.unwrap(),
2
);
assert_eq!(
stats
.deposits_with_custom_price
.load(deps.as_ref().storage, bob.clone())
.unwrap(),
1
);
assert_eq!(
stats
.deposits_with_custom_price_amounts
.load(deps.as_ref().storage, alice)
.unwrap(),
coin(REDUCED_AMOUNT * 2, DENOM)
);
assert_eq!(
stats
.deposits_with_custom_price_amounts
.load(deps.as_ref().storage, bob)
.unwrap(),
coin(5_000_000, DENOM)
);
}
#[test]
fn default_and_reduced_stats_do_not_interfere() {
let mut deps = mock_dependencies();
let stats = init_stats(deps.as_mut().storage);
let alice = deps.api.addr_make("alice");
stats
.new_default_deposit(deps.as_mut().storage, &coin(DEFAULT_AMOUNT, DENOM))
.unwrap();
stats
.new_reduced_deposit(deps.as_mut().storage, &alice, &coin(REDUCED_AMOUNT, DENOM))
.unwrap();
stats
.new_default_deposit(deps.as_mut().storage, &coin(DEFAULT_AMOUNT, DENOM))
.unwrap();
assert_eq!(
stats
.deposits_with_default_price
.load(deps.as_ref().storage)
.unwrap(),
2
);
assert_eq!(
stats
.deposits_with_custom_price
.load(deps.as_ref().storage, alice)
.unwrap(),
1
);
}
}
+3
View File
@@ -22,6 +22,9 @@ pub(crate) const CONTRACT_VERSION: &str = env!("CARGO_PKG_VERSION");
pub struct Config {
pub group_addr: Cw4Contract,
pub holding_account: Addr,
/// Specifies the expected default deposit amount if the sender is not in the whitelisted set.
#[serde(alias = "default_deposit_amount")]
pub deposit_amount: Coin,
}
+1 -6
View File
@@ -1,15 +1,10 @@
// Copyright 2024 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0
#![warn(clippy::expect_used)]
#![warn(clippy::unwrap_used)]
#![warn(clippy::todo)]
#![warn(clippy::dbg_macro)]
mod constants;
pub mod contract;
mod deposit;
mod deposit_stats;
mod helpers;
#[cfg(test)]
pub mod multitest;
mod support;
+198
View File
@@ -10,6 +10,9 @@ use sylvia::{cw_multi_test::App as MtApp, multitest::App};
use crate::contract::sv::mt::{CodeId, NymEcashContractProxy};
const DENOM: &str = "unym";
const DEPOSIT_AMOUNT: u128 = 75_000_000;
#[test]
fn invalid_deposit() {
let owner = "owner".into_bech32();
@@ -73,3 +76,198 @@ fn invalid_deposit() {
EcashContractError::InvalidDeposit(PaymentError::MissingDenom(denom.to_string()))
);
}
#[test]
fn wrong_deposit_amount() {
let owner = "owner".into_bech32();
let mtapp = MtApp::new(|router, _, storage| {
router
.bank
.init_balance(storage, &owner, vec![Coin::new(1_000_000_000u128, DENOM)])
.unwrap()
});
let app = App::new(mtapp);
let code_id = CodeId::store_code(&app);
let contract = code_id
.instantiate(
MockApi::default().addr_make("holding_account").to_string(),
MockApi::default().addr_make("multisig_addr").to_string(),
MockApi::default().addr_make("group_addr").to_string(),
coin(DEPOSIT_AMOUNT, DENOM),
)
.call(&owner)
.unwrap();
let vk = "GLdR2NRVZBiCoCbv4fNqt9wUJZAnNjGXHkx3TjVAUzrK";
// too little
assert_eq!(
contract
.deposit_ticket_book_funds(vk.to_string())
.with_funds(&[coin(1_000_000u128, DENOM)])
.call(&owner)
.unwrap_err(),
EcashContractError::WrongAmount {
received: coin(1_000_000u128, DENOM),
amount: coin(DEPOSIT_AMOUNT, DENOM),
}
);
// too much
assert_eq!(
contract
.deposit_ticket_book_funds(vk.to_string())
.with_funds(&[coin(100_000_000u128, DENOM)])
.call(&owner)
.unwrap_err(),
EcashContractError::WrongAmount {
received: coin(100_000_000u128, DENOM),
amount: coin(DEPOSIT_AMOUNT, DENOM),
}
);
}
#[test]
fn correct_default_deposit_succeeds() {
let owner = "owner".into_bech32();
let mtapp = MtApp::new(|router, _, storage| {
router
.bank
.init_balance(storage, &owner, vec![Coin::new(1_000_000_000u128, DENOM)])
.unwrap()
});
let app = App::new(mtapp);
let code_id = CodeId::store_code(&app);
let contract = code_id
.instantiate(
MockApi::default().addr_make("holding_account").to_string(),
MockApi::default().addr_make("multisig_addr").to_string(),
MockApi::default().addr_make("group_addr").to_string(),
coin(DEPOSIT_AMOUNT, DENOM),
)
.call(&owner)
.unwrap();
let vk = "GLdR2NRVZBiCoCbv4fNqt9wUJZAnNjGXHkx3TjVAUzrK";
contract
.deposit_ticket_book_funds(vk.to_string())
.with_funds(&[coin(DEPOSIT_AMOUNT, DENOM)])
.call(&owner)
.unwrap();
}
#[test]
fn reduced_price_deposit_end_to_end() {
let owner = "owner".into_bech32();
let whitelisted = "whitelisted".into_bech32();
let non_whitelisted = "non_whitelisted".into_bech32();
let reduced_amount: u128 = 10_000_000;
let mtapp = MtApp::new(|router, _, storage| {
router
.bank
.init_balance(
storage,
&whitelisted,
vec![Coin::new(1_000_000_000u128, DENOM)],
)
.unwrap();
router
.bank
.init_balance(
storage,
&non_whitelisted,
vec![Coin::new(1_000_000_000u128, DENOM)],
)
.unwrap();
});
let app = App::new(mtapp);
let code_id = CodeId::store_code(&app);
let contract = code_id
.instantiate(
MockApi::default().addr_make("holding_account").to_string(),
MockApi::default().addr_make("multisig_addr").to_string(),
MockApi::default().addr_make("group_addr").to_string(),
coin(DEPOSIT_AMOUNT, DENOM),
)
.call(&owner)
.unwrap();
let vk = "GLdR2NRVZBiCoCbv4fNqt9wUJZAnNjGXHkx3TjVAUzrK";
// whitelist an address with a reduced price
contract
.set_reduced_deposit_price(whitelisted.to_string(), coin(reduced_amount, DENOM))
.call(&owner)
.unwrap();
// whitelisted address can deposit at the reduced price
contract
.deposit_ticket_book_funds(vk.to_string())
.with_funds(&[coin(reduced_amount, DENOM)])
.call(&whitelisted)
.unwrap();
// whitelisted address can also deposit at the default price —
// treated as a normal (non-reduced) deposit for statistics purposes
contract
.deposit_ticket_book_funds(vk.to_string())
.with_funds(&[coin(DEPOSIT_AMOUNT, DENOM)])
.call(&whitelisted)
.unwrap();
// whitelisted address is rejected when sending an amount that is
// neither the reduced nor the default price
assert_eq!(
contract
.deposit_ticket_book_funds(vk.to_string())
.with_funds(&[coin(50_000_000, DENOM)])
.call(&whitelisted)
.unwrap_err(),
EcashContractError::WrongAmount {
received: coin(50_000_000, DENOM),
amount: coin(reduced_amount, DENOM),
}
);
// non-whitelisted address is rejected at the reduced amount
assert_eq!(
contract
.deposit_ticket_book_funds(vk.to_string())
.with_funds(&[coin(reduced_amount, DENOM)])
.call(&non_whitelisted)
.unwrap_err(),
EcashContractError::WrongAmount {
received: coin(reduced_amount, DENOM),
amount: coin(DEPOSIT_AMOUNT, DENOM),
}
);
// non-whitelisted address succeeds at the default amount
contract
.deposit_ticket_book_funds(vk.to_string())
.with_funds(&[coin(DEPOSIT_AMOUNT, DENOM)])
.call(&non_whitelisted)
.unwrap();
let stats = contract.get_deposits_statistics().unwrap();
assert_eq!(stats.total_deposits_made, 3);
assert_eq!(
stats.total_deposited,
coin(reduced_amount + DEPOSIT_AMOUNT * 2, DENOM)
);
// whitelisted depositing at default price + non-whitelisted = 2 default deposits
assert_eq!(stats.total_deposits_made_with_default_price, 2);
assert_eq!(
stats.total_deposited_with_default_price,
coin(DEPOSIT_AMOUNT * 2, DENOM)
);
assert_eq!(stats.total_deposits_made_with_custom_price, 1);
assert_eq!(
stats.total_deposited_with_custom_price,
coin(reduced_amount, DENOM)
);
}
-5
View File
@@ -1,5 +0,0 @@
// Copyright 2024 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0
#[cfg(test)]
pub mod tests;
-104
View File
@@ -1,104 +0,0 @@
// Copyright 2024 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0
use crate::contract::NymEcashContract;
use crate::helpers::Config;
use cosmwasm_std::testing::{message_info, mock_dependencies, mock_env, MockApi, MockQuerier};
use cosmwasm_std::{coin, Addr, Deps, Empty, Env, MemoryStorage, MessageInfo, OwnedDeps};
use rand_chacha::rand_core::SeedableRng;
use rand_chacha::ChaCha20Rng;
use sylvia::ctx::{ExecCtx, InstantiateCtx, QueryCtx};
pub fn test_rng() -> ChaCha20Rng {
let dummy_seed = [42u8; 32];
ChaCha20Rng::from_seed(dummy_seed)
}
const CONTRACT: NymEcashContract = NymEcashContract::new();
const DENOM: &str = "unym";
#[allow(dead_code)]
pub struct TestSetupSimple {
pub deps: OwnedDeps<MemoryStorage, MockApi, MockQuerier<Empty>>,
pub env: Env,
pub rng: ChaCha20Rng,
pub owner: Addr,
pub holding_account: Addr,
pub multisig_contract: Addr,
pub group_contract: Addr,
}
impl TestSetupSimple {
pub fn new() -> Self {
let mut deps = mock_dependencies();
let env = mock_env();
let owner = deps.api.addr_make("owner");
let rng = test_rng();
let holding_account = deps.api.addr_make("holding_account");
let multisig_contract = deps.api.addr_make("multisig_contract");
let group_contract = deps.api.addr_make("group_contract");
let init_ctx =
InstantiateCtx::from((deps.as_mut(), env.clone(), message_info(&owner, &[])));
CONTRACT
.instantiate(
init_ctx,
holding_account.to_string(),
multisig_contract.to_string(),
group_contract.to_string(),
coin(75_000_000, DENOM.to_string()),
)
.unwrap();
TestSetupSimple {
deps,
env,
rng,
owner,
holding_account,
multisig_contract,
group_contract,
}
}
pub fn admin(&self) -> MessageInfo {
let admin = CONTRACT
.contract_admin
.get(self.deps.as_ref())
.unwrap()
.unwrap();
message_info(&admin, &[])
}
pub fn execute_ctx(&mut self, sender: MessageInfo) -> ExecCtx<'_> {
let env = self.env.clone();
ExecCtx::from((self.deps.as_mut(), env, sender))
}
#[allow(dead_code)]
pub fn query_ctx(&self) -> QueryCtx<'_> {
QueryCtx::from((self.deps.as_ref(), self.env.clone()))
}
pub fn contract(&self) -> NymEcashContract {
CONTRACT
}
pub fn deps(&self) -> Deps<'_> {
self.deps.as_ref()
}
pub fn config(&self) -> Config {
CONTRACT.config.load(self.deps().storage).unwrap()
}
pub fn with_deposit_amount(mut self, amount: u128) -> Self {
CONTRACT
.update_deposit_value(self.execute_ctx(self.admin()), coin(amount, DENOM))
.unwrap();
self
}
}
+12 -11
View File
@@ -2992,7 +2992,7 @@ dependencies = [
"once_cell",
"rand 0.9.2",
"ring",
"rustls 0.23.36",
"rustls 0.23.37",
"thiserror 2.0.12",
"tinyvec",
"tokio",
@@ -3017,7 +3017,7 @@ dependencies = [
"parking_lot",
"rand 0.9.2",
"resolv-conf",
"rustls 0.23.36",
"rustls 0.23.37",
"smallvec",
"thiserror 2.0.12",
"tokio",
@@ -3256,7 +3256,7 @@ dependencies = [
"http 1.3.1",
"hyper 1.8.1",
"hyper-util",
"rustls 0.23.36",
"rustls 0.23.37",
"rustls-pki-types",
"tokio",
"tokio-rustls 0.26.2",
@@ -4726,6 +4726,7 @@ dependencies = [
"nym-http-api-common",
"once_cell",
"reqwest 0.13.2",
"rustls 0.23.37",
"serde",
"serde_json",
"serde_plain",
@@ -6103,7 +6104,7 @@ dependencies = [
"quinn-proto",
"quinn-udp",
"rustc-hash",
"rustls 0.23.36",
"rustls 0.23.37",
"socket2 0.5.9",
"thiserror 2.0.12",
"tokio",
@@ -6123,7 +6124,7 @@ dependencies = [
"rand 0.9.2",
"ring",
"rustc-hash",
"rustls 0.23.36",
"rustls 0.23.37",
"rustls-pki-types",
"slab",
"thiserror 2.0.12",
@@ -6426,7 +6427,7 @@ dependencies = [
"percent-encoding",
"pin-project-lite",
"quinn",
"rustls 0.23.36",
"rustls 0.23.37",
"rustls-pemfile 2.2.0",
"rustls-pki-types",
"serde",
@@ -6469,7 +6470,7 @@ dependencies = [
"percent-encoding",
"pin-project-lite",
"quinn",
"rustls 0.23.36",
"rustls 0.23.37",
"rustls-pki-types",
"rustls-platform-verifier",
"serde",
@@ -6641,9 +6642,9 @@ dependencies = [
[[package]]
name = "rustls"
version = "0.23.36"
version = "0.23.37"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c665f33d38cea657d9614f766881e4d510e0eda4239891eea56b4cadcf01801b"
checksum = "758025cb5fccfd3bc2fd74708fd4682be41d99e5dff73c377c0646c6012c73a4"
dependencies = [
"aws-lc-rs",
"log",
@@ -6718,7 +6719,7 @@ dependencies = [
"jni",
"log",
"once_cell",
"rustls 0.23.36",
"rustls 0.23.37",
"rustls-native-certs 0.8.3",
"rustls-platform-verifier-android",
"rustls-webpki 0.103.9",
@@ -8291,7 +8292,7 @@ version = "0.26.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8e727b36a1a0e8b74c376ac2211e40c2c8af09fb4013c60d910495810f008e9b"
dependencies = [
"rustls 0.23.36",
"rustls 0.23.37",
"tokio",
]