Struct AssetListBase

Source
pub struct AssetListBase<T: AddressLike>(/* private fields */);
Expand description

Represents a list of fungible tokens, each with a known amount

Implementations§

Source§

impl AssetListBase<String>

Source

pub fn check( &self, api: &dyn Api, optional_whitelist: Option<&[&str]>, ) -> Result<AssetList, AssetError>

Validate data contained in an unchecked asset list instance, return a new checked asset list instance:

  • For CW20 tokens, assert the contract address is valid
  • For SDK coins, assert that the denom is included in a given whitelist; skip if the whitelist is not provided
use cosmwasm_std::{Addr, Api, StdResult};
use cw_asset::{Asset, AssetList, AssetListUnchecked, AssetUnchecked};

fn validate_assets(api: &dyn Api, list_unchecked: &AssetListUnchecked) {
    match list_unchecked.check(api, Some(&["uatom", "uluna"])) {
        Ok(list) => println!("asset list is valid: {}", list.to_string()),
        Err(err) => println!("asset list is invalid! reason: {}", err),
    }
}
Source§

impl AssetListBase<Addr>

Source

pub fn new() -> Self

Create a new, empty asset list

use cw_asset::AssetList;

let list = AssetList::new();
let len = list.len(); // should be zero
Source

pub fn to_vec(&self) -> Vec<Asset>

Return a copy of the underlying vector

use cw_asset::{Asset, AssetList};

let list =
    AssetList::from(vec![Asset::native("uluna", 12345u128), Asset::native("uusd", 67890u128)]);

let vec: Vec<Asset> = list.to_vec();
Source

pub fn len(&self) -> usize

Return length of the asset list

use cw_asset::{Asset, AssetList};

let list =
    AssetList::from(vec![Asset::native("uluna", 12345u128), Asset::native("uusd", 67890u128)]);

let len = list.len(); // should be two
Source

pub fn is_empty(&self) -> bool

Return whether the asset list is empty

use cw_asset::{Asset, AssetList};

let mut list = AssetList::from(vec![Asset::native("uluna", 12345u128)]);
let is_empty = list.is_empty(); // should be `false`

list.deduct(&Asset::native("uluna", 12345u128)).unwrap();
let is_empty = list.is_empty(); // should be `true`
Source

pub fn find(&self, info: &AssetInfo) -> Option<&Asset>

Find an asset in the list that matches the provided asset info

Return Some(&asset) if found, where &asset is a reference to the asset found; None if not found.

A case where is method is useful is to find how much asset the user sent along with a message:

use cosmwasm_std::MessageInfo;
use cw_asset::{AssetInfo, AssetList};

fn find_uusd_received_amount(info: &MessageInfo) {
    let list = AssetList::from(&info.funds);
    match list.find(&AssetInfo::native("uusd")) {
        Some(asset) => println!("received {} uusd", asset.amount),
        None => println!("did not receive any uusd"),
    }
}
Source

pub fn apply<F: FnMut(&mut Asset)>(&mut self, f: F) -> &mut Self

Apply a mutation on each of the asset

An example case where this is useful is to scale the amount of each asset in the list by a certain factor:

use cw_asset::{Asset, AssetInfo, AssetList};

let mut list =
    AssetList::from(vec![Asset::native("uluna", 12345u128), Asset::native("uusd", 67890u128)]);

let list_halved = list.apply(|a| a.amount = a.amount.multiply_ratio(1u128, 2u128));
Source

pub fn purge(&mut self) -> &mut Self

Removes all assets in the list that has zero amount

use cw_asset::{Asset, AssetList};

let mut list =
    AssetList::from(vec![Asset::native("uluna", 12345u128), Asset::native("uusd", 0u128)]);
let mut len = list.len(); // should be two

list.purge();
len = list.len(); // should be one
Source

pub fn add(&mut self, asset_to_add: &Asset) -> Result<&mut Self, AssetError>

Add a new asset to the list

If asset of the same kind already exists in the list, then increment its amount; if not, append to the end of the list.

NOTE: purge is automatically performed following the addition, so adding an asset with zero amount has no effect.

use cw_asset::{Asset, AssetInfo, AssetList};

let mut list = AssetList::from(vec![
    Asset::native("uluna", 12345u128),
]);

list.add(&Asset::native("uusd", 67890u128));
let mut len = list.len();  // should be two

list.add(&Asset::native("uluna", 11111u128));
len = list.len();  // should still be two

let uluna_amount = list
    .find(&AssetInfo::native("uluna"))
    .unwrap()
    .amount;  // should have increased to 23456
Source

pub fn add_many( &mut self, assets_to_add: &AssetList, ) -> Result<&mut Self, AssetError>

Add multiple new assets to the list

use cw_asset::{Asset, AssetInfo, AssetList};

let mut list = AssetList::from(vec![
    Asset::native("uluna", 12345u128),
]);

list.add_many(&AssetList::from(vec![
    Asset::native("uusd", 67890u128),
    Asset::native("uluna", 11111u128),
]));

let uusd_amount = list
    .find(&AssetInfo::native("uusd"))
    .unwrap()
    .amount;  // should be 67890

let uluna_amount = list
    .find(&AssetInfo::native("uluna"))
    .unwrap()
    .amount;  // should have increased to 23456
Source

pub fn deduct( &mut self, asset_to_deduct: &Asset, ) -> Result<&mut Self, AssetError>

Deduct an asset from the list

The asset of the same kind and equal or greater amount must already exist in the list. If so, deduct the amount from the asset; ifnot, throw an error.

NOTE: purge is automatically performed following the addition. Therefore, if an asset’s amount is reduced to zero, it will be removed from the list.

use cw_asset::{Asset, AssetInfo, AssetList};

let mut list = AssetList::from(vec![
    Asset::native("uluna", 12345u128),
]);

list.deduct(&Asset::native("uluna", 10000u128)).unwrap();

let uluna_amount = list
    .find(&AssetInfo::native("uluna"))
    .unwrap()
    .amount;  // should have reduced to 2345

list.deduct(&Asset::native("uluna", 2345u128));

let len = list.len();  // should be zero, as uluna is purged from the list
Source

pub fn deduct_many( &mut self, assets_to_deduct: &AssetList, ) -> Result<&mut Self, AssetError>

Deduct multiple assets from the list

use cw_asset::{Asset, AssetInfo, AssetList};

let mut list = AssetList::from(vec![
    Asset::native("uluna", 12345u128),
    Asset::native("uusd", 67890u128),
]);

list.deduct_many(&AssetList::from(vec![
    Asset::native("uluna", 2345u128),
    Asset::native("uusd", 67890u128),
])).unwrap();

let uluna_amount = list
    .find(&AssetInfo::native("uluna"))
    .unwrap()
    .amount;  // should have reduced to 2345

let len = list.len();  // should be zero, as uusd is purged from the list
Source

pub fn transfer_msgs<A: Into<String> + Clone>( &self, to: A, ) -> Result<Vec<CosmosMsg>, AssetError>

Generate a transfer messages for every asset in the list

use cosmwasm_std::{Addr, Response};
use cw_asset::{AssetError, AssetList};

fn transfer_assets(list: &AssetList, recipient_addr: &Addr) -> Result<Response, AssetError> {
    let msgs = list.transfer_msgs(recipient_addr)?;

    Ok(Response::new().add_messages(msgs).add_attribute("assets_sent", list.to_string()))
}

Trait Implementations§

Source§

impl<T: Clone + AddressLike> Clone for AssetListBase<T>

Source§

fn clone(&self) -> AssetListBase<T>

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl<T: Debug + AddressLike> Debug for AssetListBase<T>

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl<T: AddressLike> Default for AssetListBase<T>

Source§

fn default() -> Self

Returns the “default value” for a type. Read more
Source§

impl<'de, T> Deserialize<'de> for AssetListBase<T>
where T: Deserialize<'de> + AddressLike,

Source§

fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>
where __D: Deserializer<'de>,

Deserialize this value from the given Serde deserializer. Read more
Source§

impl From<AssetListBase<Addr>> for AssetListUnchecked

Source§

fn from(list: AssetList) -> Self

Converts to this type from the input type.
Source§

impl<T: AddressLike + JsonSchema> JsonSchema for AssetListBase<T>

Source§

fn schema_name() -> String

The name of the generated JSON Schema. Read more
Source§

fn schema_id() -> Cow<'static, str>

Returns a string that uniquely identifies the schema produced by this type. Read more
Source§

fn json_schema(generator: &mut SchemaGenerator) -> Schema

Generates a JSON Schema for this type. Read more
Source§

fn is_referenceable() -> bool

Whether JSON Schemas generated for this type should be re-used where possible using the $ref keyword. Read more
Source§

impl<T: PartialEq + AddressLike> PartialEq for AssetListBase<T>

Source§

fn eq(&self, other: &AssetListBase<T>) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl<T> Serialize for AssetListBase<T>

Source§

fn serialize<__S>(&self, __serializer: __S) -> Result<__S::Ok, __S::Error>
where __S: Serializer,

Serialize this value into the given Serde serializer. Read more
Source§

impl<T: AddressLike> StructuralPartialEq for AssetListBase<T>

Auto Trait Implementations§

§

impl<T> Freeze for AssetListBase<T>

§

impl<T> RefUnwindSafe for AssetListBase<T>
where T: RefUnwindSafe,

§

impl<T> Send for AssetListBase<T>
where T: Send,

§

impl<T> Sync for AssetListBase<T>
where T: Sync,

§

impl<T> Unpin for AssetListBase<T>
where T: Unpin,

§

impl<T> UnwindSafe for AssetListBase<T>
where T: UnwindSafe,

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<U> As for U

Source§

fn as_<T>(self) -> T
where T: CastFrom<U>,

Casts self to type T. The semantics of numeric casting with the as operator are followed, so <T as As>::as_::<U> can be used in the same way as T as U for numeric conversions. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> DynClone for T
where T: Clone,

Source§

fn __clone_box(&self, _: Private) -> *mut ()

Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T> ToString for T
where T: Display + ?Sized,

Source§

fn to_string(&self) -> String

Converts the given value to a String. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> DeserializeOwned for T
where T: for<'de> Deserialize<'de>,