1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use std::fmt;
use crate::factory::PairType;
use crate::querier::{query_balance, query_token_balance, query_token_symbol};
use cosmwasm_std::{
to_binary, Addr, Api, BankMsg, Coin, CosmosMsg, Decimal, MessageInfo, QuerierWrapper, StdError,
StdResult, Uint128, WasmMsg,
};
use cw20::Cw20ExecuteMsg;
use terra_cosmwasm::TerraQuerier;
/// ## Description
/// This enum describes a Terra asset (native or CW20).
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]
pub struct Asset {
/// Information about an asset stored in a [`AssetInfo`] struct
pub info: AssetInfo,
/// A token amount
pub amount: Uint128,
}
impl fmt::Display for Asset {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}{}", self.amount, self.info)
}
}
/// Decimal points
static DECIMAL_FRACTION: Uint128 = Uint128::new(1_000_000_000_000_000_000u128);
impl Asset {
/// ## Description
/// Returns true if the token is native. Otherwise returns false.
/// ## Params
/// * **self** is the type of the caller object.
pub fn is_native_token(&self) -> bool {
self.info.is_native_token()
}
/// ## Description
/// Calculates and returns a tax for a chain's native token. For other tokens it returns zero.
/// ## Params
/// * **self** is the type of the caller object.
///
/// * **querier** is an object of type [`QuerierWrapper`]
pub fn compute_tax(&self, querier: &QuerierWrapper) -> StdResult<Uint128> {
let amount = self.amount;
if let AssetInfo::NativeToken { denom } = &self.info {
let terra_querier = TerraQuerier::new(querier);
let tax_rate: Decimal = (terra_querier.query_tax_rate()?).rate;
let tax_cap: Uint128 = (terra_querier.query_tax_cap(denom.to_string())?).cap;
Ok(std::cmp::min(
(amount.checked_sub(amount.multiply_ratio(
DECIMAL_FRACTION,
DECIMAL_FRACTION * tax_rate + DECIMAL_FRACTION,
)))?,
tax_cap,
))
} else {
Ok(Uint128::zero())
}
}
/// ## Description
/// Calculates and returns a deducted tax for transferring the native token from the chain. For other tokens it returns an [`Err`].
/// ## Params
/// * **self** is the type of the caller object.
///
/// * **querier** is an object of type [`QuerierWrapper`]
pub fn deduct_tax(&self, querier: &QuerierWrapper) -> StdResult<Coin> {
let amount = self.amount;
if let AssetInfo::NativeToken { denom } = &self.info {
Ok(Coin {
denom: denom.to_string(),
amount: amount.checked_sub(self.compute_tax(querier)?)?,
})
} else {
Err(StdError::generic_err("cannot deduct tax from token asset"))
}
}
/// ## Description
/// Returns a message of type [`CosmosMsg`].
///
/// For native tokens of type [`AssetInfo`] uses the default method [`BankMsg::Send`] to send a token amount to a recipient.
/// Before the token is sent, we need to deduct a tax.
///
/// For a token of type [`AssetInfo`] we use the default method [`Cw20ExecuteMsg::Transfer`] and so there's no need to deduct any other tax.
/// ## Params
/// * **self** is the type of the caller object.
///
/// * **querier** is the object of type [`QuerierWrapper`]
///
/// * **recipient** is the address where the funds will be sent.
pub fn into_msg(self, querier: &QuerierWrapper, recipient: Addr) -> StdResult<CosmosMsg> {
let amount = self.amount;
match &self.info {
AssetInfo::Token { contract_addr } => Ok(CosmosMsg::Wasm(WasmMsg::Execute {
contract_addr: contract_addr.to_string(),
msg: to_binary(&Cw20ExecuteMsg::Transfer {
recipient: recipient.to_string(),
amount,
})?,
funds: vec![],
})),
AssetInfo::NativeToken { .. } => Ok(CosmosMsg::Bank(BankMsg::Send {
to_address: recipient.to_string(),
amount: vec![self.deduct_tax(querier)?],
})),
}
}
/// ## Description
/// Validates an amount of native tokens being sent. Returns [`Ok`] if successful, otherwise returns [`Err`].
/// ## Params
/// * **self** is the type of the caller object.
///
/// * **message_info** is an object of type [`MessageInfo`]
pub fn assert_sent_native_token_balance(&self, message_info: &MessageInfo) -> StdResult<()> {
if let AssetInfo::NativeToken { denom } = &self.info {
match message_info.funds.iter().find(|x| x.denom == *denom) {
Some(coin) => {
if self.amount == coin.amount {
Ok(())
} else {
Err(StdError::generic_err("Native token balance mismatch between the argument and the transferred"))
}
}
None => {
if self.amount.is_zero() {
Ok(())
} else {
Err(StdError::generic_err("Native token balance mismatch between the argument and the transferred"))
}
}
}
} else {
Ok(())
}
}
}
/// ## Description
/// This enum describes available Token types.
/// ## Examples
/// ```
/// # use cosmwasm_std::Addr;
/// ```
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum AssetInfo {
/// Non-native Token
Token { contract_addr: Addr },
/// Native token
NativeToken { denom: String },
}
impl fmt::Display for AssetInfo {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
AssetInfo::NativeToken { denom } => write!(f, "{}", denom),
AssetInfo::Token { contract_addr } => write!(f, "{}", contract_addr),
}
}
}
impl AssetInfo {
/// ## Description
/// Returns true if the caller is a native token. Otherwise returns false.
/// ## Params
/// * **self** is the caller object type
pub fn is_native_token(&self) -> bool {
match self {
AssetInfo::NativeToken { .. } => true,
AssetInfo::Token { .. } => false,
}
}
/// ## Description
/// Returns the balance of token in a pool.
/// ## Params
/// * **self** is the type of the caller object.
///
/// * **pool_addr** is the address of the contract whose token balance we check.
pub fn query_pool(&self, querier: &QuerierWrapper, pool_addr: Addr) -> StdResult<Uint128> {
match self {
AssetInfo::Token { contract_addr, .. } => {
query_token_balance(querier, contract_addr.clone(), pool_addr)
}
AssetInfo::NativeToken { denom, .. } => {
query_balance(querier, pool_addr, denom.to_string())
}
}
}
/// ## Description
/// Returns True if the calling token is the same as the token specified in the input parameters.
/// Otherwise returns False.
/// ## Params
/// * **self** is the type of the caller object.
///
/// * **asset** is object of type [`AssetInfo`].
pub fn equal(&self, asset: &AssetInfo) -> bool {
match self {
AssetInfo::Token { contract_addr, .. } => {
let self_contract_addr = contract_addr;
match asset {
AssetInfo::Token { contract_addr, .. } => self_contract_addr == contract_addr,
AssetInfo::NativeToken { .. } => false,
}
}
AssetInfo::NativeToken { denom, .. } => {
let self_denom = denom;
match asset {
AssetInfo::Token { .. } => false,
AssetInfo::NativeToken { denom, .. } => self_denom == denom,
}
}
}
}
/// ## Description
/// If the caller object is a native token of type ['AssetInfo`] then his `denom` field converts to a byte string.
///
/// If the caller object is a token of type ['AssetInfo`] then his `contract_addr` field converts to a byte string.
/// ## Params
/// * **self** is the type of the caller object.
pub fn as_bytes(&self) -> &[u8] {
match self {
AssetInfo::NativeToken { denom } => denom.as_bytes(),
AssetInfo::Token { contract_addr } => contract_addr.as_bytes(),
}
}
/// ## Description
/// Returns [`Ok`] if the token of type [`AssetInfo`] is in lowercase and valid. Otherwise returns [`Err`].
/// ## Params
/// * **self** is the type of the caller object.
///
/// * **api** is a object of type [`Api`]
pub fn check(&self, api: &dyn Api) -> StdResult<()> {
match self {
AssetInfo::Token { contract_addr } => {
addr_validate_to_lower(api, contract_addr.as_str())?;
}
AssetInfo::NativeToken { denom } => {
if denom != &denom.to_lowercase() {
return Err(StdError::generic_err(format!(
"Native token denom {} should be lowercase",
denom
)));
}
}
}
Ok(())
}
}
/// ## Description
/// This structure stores the main parameters for an Astroport pair
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]
pub struct PairInfo {
/// Asset information for the two assets in the pool
pub asset_infos: [AssetInfo; 2],
/// Pair contract address
pub contract_addr: Addr,
/// Pair LP token address
pub liquidity_token: Addr,
/// The pool type (xyk, stableswap etc) available in [`PairType`]
pub pair_type: PairType,
}
impl PairInfo {
/// ## Description
/// Returns the balance for each asset in the pool.
/// ## Params
/// * **self** is the type of the caller object
///
/// * **querier** is the object of type [`QuerierWrapper`]
///
/// * **contract_addr** is pair's pool address.
pub fn query_pools(
&self,
querier: &QuerierWrapper,
contract_addr: Addr,
) -> StdResult<[Asset; 2]> {
Ok([
Asset {
amount: self.asset_infos[0].query_pool(querier, contract_addr.clone())?,
info: self.asset_infos[0].clone(),
},
Asset {
amount: self.asset_infos[1].query_pool(querier, contract_addr)?,
info: self.asset_infos[1].clone(),
},
])
}
}
/// ## Description
/// Returns a lowercased, validated address upon success. Otherwise returns [`Err`]
/// ## Params
/// * **api** is an object of type [`Api`]
///
/// * **addr** is an object of type [`Addr`]
pub fn addr_validate_to_lower(api: &dyn Api, addr: &str) -> StdResult<Addr> {
if addr.to_lowercase() != addr {
return Err(StdError::generic_err(format!(
"Address {} should be lowercase",
addr
)));
}
api.addr_validate(addr)
}
const TOKEN_SYMBOL_MAX_LENGTH: usize = 4;
/// ## Description
/// Returns a formatted LP token name
/// ## Params
/// * **asset_infos** is an array with two items the type of [`AssetInfo`].
///
/// * **querier** is an object of type [`QuerierWrapper`].
pub fn format_lp_token_name(
asset_infos: [AssetInfo; 2],
querier: &QuerierWrapper,
) -> StdResult<String> {
let mut short_symbols: Vec<String> = vec![];
for asset_info in asset_infos {
let short_symbol: String;
match asset_info {
AssetInfo::NativeToken { denom } => {
short_symbol = denom.chars().take(TOKEN_SYMBOL_MAX_LENGTH).collect();
}
AssetInfo::Token { contract_addr } => {
let token_symbol = query_token_symbol(querier, contract_addr)?;
short_symbol = token_symbol.chars().take(TOKEN_SYMBOL_MAX_LENGTH).collect();
}
}
short_symbols.push(short_symbol);
}
Ok(format!("{}-{}-LP", short_symbols[0], short_symbols[1]).to_uppercase())
}
pub fn native_asset(denom: String, amount: Uint128) -> Asset {
Asset {
info: AssetInfo::NativeToken { denom },
amount,
}
}
pub fn token_asset(contract_addr: Addr, amount: Uint128) -> Asset {
Asset {
info: AssetInfo::Token { contract_addr },
amount,
}
}
pub fn native_asset_info(denom: String) -> AssetInfo {
AssetInfo::NativeToken { denom }
}
pub fn token_asset_info(contract_addr: Addr) -> AssetInfo {
AssetInfo::Token { contract_addr }
}