Struct cw_asset::AssetBase

source ·
pub struct AssetBase<T: AddressLike> {
    pub info: AssetInfoBase<T>,
    pub amount: Uint128,
}
Expand description

Represents a fungible asset with a known amount

Each asset instance contains two values: info, which specifies the asset’s type (CW20 or native), and its amount, which specifies the asset’s amount.

Fields§

§info: AssetInfoBase<T>

Specifies the asset’s type (CW20 or native)

§amount: Uint128

Specifies the asset’s amount

Implementations§

source§

impl<T: AddressLike> AssetBase<T>

source

pub fn new<A: Into<AssetInfoBase<T>>, B: Into<Uint128>>( info: A, amount: B, ) -> Self

Create a new asset instance based on given asset info and amount

To create an unchecked instance, the info parameter may be either checked or unchecked; to create a checked instance, the info paramter must also be checked.

use cosmwasm_std::Addr;
use cw_asset::{Asset, AssetInfo};

let info1 = AssetInfo::cw20(Addr::unchecked("token_addr"));
let asset1 = Asset::new(info1, 12345u128);

let info2 = AssetInfo::native("uusd");
let asset2 = Asset::new(info2, 67890u128);
source

pub fn native<A: Into<String>, B: Into<Uint128>>(denom: A, amount: B) -> Self

Create a new asset instance representing a native coin of given denom and amount

use cw_asset::Asset;

let asset = Asset::native("uusd", 12345u128);
source

pub fn cw20<A: Into<T>, B: Into<Uint128>>(contract_addr: A, amount: B) -> Self

Create a new asset instance representing a CW20 token of given contract address and amount.

use cosmwasm_std::Addr;
use cw_asset::Asset;

let asset = Asset::cw20(Addr::unchecked("token_addr"), 12345u128);
source§

impl AssetBase<String>

source

pub fn from_sdk_string(s: &str) -> Result<Self, AssetError>

Parse a string of the format {amount}{denom} into an AssetUnchecked object. This is the format that Cosmos SDK uses to stringify native coins. For example:

  • 12345uatom
  • 69420ibc/27394FB092D2ECCD56123C74F36E4C1F926001CEADA9CA97EA622B25F41E5EB2
  • 88888factory/osmo1z926ax906k0ycsuckele6x5hh66e2m4m6ry7dn

Since native coin denoms can only start with a non-numerial character, while its amount can only contain numerical characters, we simply consider the first non-numerical character and all that comes after as the denom, while all that comes before it as the amount. This is the approach used in the Steak Hub contract.

source

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

Validate data contained in an unchecked asset instnace, return a new checked asset 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};
use cw_asset::{Asset, AssetUnchecked};

fn validate_asset(api: &dyn Api, asset_unchecked: &AssetUnchecked) {
    match asset_unchecked.check(api, Some(&["uatom", "uluna"])) {
        Ok(asset) => println!("asset is valid: {}", asset.to_string()),
        Err(err) => println!("asset is invalid! reason: {}", err),
    }
}
source§

impl AssetBase<Addr>

source

pub fn send_msg<A: Into<String>>( &self, to: A, msg: Binary, ) -> Result<CosmosMsg, AssetError>

Generate a message that sends a CW20 token to the specified recipient with a binary payload.

NOTE: Only works for CW20 tokens. Returns error if invoked on an Asset instance representing a native coin, as native coins do not have an equivalent method mplemented.

use serde::Serialize;

#[derive(Serialize)]
enum MockReceiveMsg {
    MockCommand {},
}

use cosmwasm_std::{to_json_binary, Addr, Response};
use cw_asset::{Asset, AssetError};

fn send_asset(
    asset: &Asset,
    contract_addr: &Addr,
    msg: &MockReceiveMsg,
) -> Result<Response, AssetError> {
    let msg = asset.send_msg(contract_addr, to_json_binary(msg)?)?;

    Ok(Response::new().add_message(msg).add_attribute("asset_sent", asset.to_string()))
}
source

pub fn transfer_msg<A: Into<String>>( &self, to: A, ) -> Result<CosmosMsg, AssetError>

Generate a message that transfers the asset from the sender to to a specified account.

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

fn transfer_asset(asset: &Asset, recipient_addr: &Addr) -> Result<Response, AssetError> {
    let msg = asset.transfer_msg(recipient_addr)?;

    Ok(Response::new().add_message(msg).add_attribute("asset_sent", asset.to_string()))
}
source

pub fn transfer_from_msg<A: Into<String>, B: Into<String>>( &self, from: A, to: B, ) -> Result<CosmosMsg, AssetError>

Generate a message that draws the asset from the account specified by from to the one specified by to.

NOTE: Only works for CW20 tokens. Returns error if invoked on an Asset instance representing a native coin, as native coins do not have an equivalent method implemented.

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

fn draw_asset(
    asset: &Asset,
    user_addr: &Addr,
    contract_addr: &Addr,
) -> Result<Response, AssetError> {
    let msg = asset.transfer_from_msg(user_addr, contract_addr)?;

    Ok(Response::new().add_message(msg).add_attribute("asset_drawn", asset.to_string()))
}

Trait Implementations§

source§

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

source§

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

Returns a copy 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 AssetBase<T>

source§

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

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

impl<'de, T> Deserialize<'de> for AssetBase<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<AssetBase<Addr>> for AssetUnchecked

source§

fn from(asset: Asset) -> Self

Converts to this type from the input type.
source§

impl<T: AddressLike + JsonSchema> JsonSchema for AssetBase<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(gen: &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 PartialEq<AssetBase<Addr>> for Coin

source§

fn eq(&self, other: &Asset) -> 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: PartialEq + AddressLike> PartialEq for AssetBase<T>

source§

fn eq(&self, other: &AssetBase<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 AssetBase<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 TryFrom<&AssetBase<Addr>> for Coin

§

type Error = AssetError

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

fn try_from(asset: &Asset) -> Result<Self, Self::Error>

Performs the conversion.
source§

impl TryFrom<AssetBase<Addr>> for Coin

§

type Error = AssetError

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

fn try_from(asset: Asset) -> Result<Self, Self::Error>

Performs the conversion.
source§

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

Auto Trait Implementations§

§

impl<T> Freeze for AssetBase<T>
where T: Freeze,

§

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

§

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

§

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

§

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

§

impl<T> UnwindSafe for AssetBase<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, dst: *mut T)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dst. 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.
§

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

§

type Output = T

Should always be Self
source§

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

§

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§

default 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>,

§

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>,

§

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>,