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
//! # Abstract Token
//!
//! `abstract_core::abstract_token` is a custom token that's only transferable between abstract_core instances.
//!
//! ## Description
//! An app is a contract that is allowed to perform actions on a [proxy](crate::proxy) contract while also being migratable.
//!
use cosmwasm_schema::QueryResponses;
use cosmwasm_std::{Binary, StdError, StdResult, Uint128};
#[allow(unused)]
use cw20::{
    AllAccountsResponse, AllAllowancesResponse, AllowanceResponse, BalanceResponse,
    DownloadLogoResponse, MarketingInfoResponse, TokenInfoResponse,
};
pub use cw20::{Cw20Coin, Cw20ExecuteMsg, Expiration, Logo, MinterResponse};
pub use cw20_base::msg::QueryMsg as Cw20QueryMsg;
use std::convert::TryInto;

/// ## Description
/// This structure describes the basic settings for creating a token contract.
/// TokenContract InstantiateMsg
#[cosmwasm_schema::cw_serde]
pub struct InstantiateMsg {
    /// the name
    pub name: String,
    /// the symbol
    pub symbol: String,
    /// the precision after the decimal point
    pub decimals: u8,
    /// the initial balance of token
    pub initial_balances: Vec<Cw20Coin>,
    /// the controls configs of type [`MinterResponse`]
    pub mint: Option<MinterResponse>,
    /// address of version control contract.
    pub version_control_address: String,
}

/// ## Description
/// This structure describes a migration message.
/// We currently take no arguments for migrations.
#[cosmwasm_schema::cw_serde]
pub struct MigrateMsg {}

impl InstantiateMsg {
    pub fn get_cap(&self) -> Option<Uint128> {
        self.mint.as_ref().and_then(|v| v.cap)
    }

    pub fn validate(&self) -> StdResult<()> {
        // Check name, symbol, decimals
        if !is_valid_name(&self.name) {
            return Err(StdError::generic_err(
                "Name is not in the expected format (3-50 UTF-8 bytes)",
            ));
        }
        if !is_valid_symbol(&self.symbol) {
            return Err(StdError::generic_err(
                "Ticker symbol is not in expected format [a-zA-Z\\-]{3,12}",
            ));
        }
        if self.decimals > 18 {
            return Err(StdError::generic_err("Decimals must not exceed 18"));
        }
        Ok(())
    }
}

/// ## Description
/// Checks the validity of the token name
/// ## Params
/// * **name** is the object of type [`str`]. the name to check
fn is_valid_name(name: &str) -> bool {
    let bytes = name.as_bytes();
    if bytes.len() < 3 || bytes.len() > 50 {
        return false;
    }
    true
}

/// ## Description
/// Checks the validity of the token symbol
/// ## Params
/// * **symbol** is the object of type [`str`]. the symbol to check
fn is_valid_symbol(symbol: &str) -> bool {
    let bytes = symbol.as_bytes();
    if bytes.len() < 3 || bytes.len() > 12 {
        return false;
    }
    for byte in bytes.iter() {
        if (*byte != 45) && (*byte < 65 || *byte > 90) && (*byte < 97 || *byte > 122) {
            return false;
        }
    }
    true
}

#[cosmwasm_schema::cw_serde]
#[cfg_attr(feature = "boot", derive(boot_core::ExecuteFns))]
pub enum ExecuteMsg {
    UpdateWhitelist {
        to_add: Vec<String>,
        to_remove: Vec<String>,
        restrict_transfers: Option<bool>,
    },
    UpdateAdmin {
        new_admin: String,
    },
    /// Transfer is a base message to move tokens to another account without triggering actions
    Transfer {
        recipient: String,
        amount: Uint128,
    },
    /// Burn is a base message to destroy tokens forever
    Burn {
        amount: Uint128,
    },
    /// Send is a base message to transfer tokens to a contract and trigger an action
    /// on the receiving contract.
    Send {
        contract: String,
        amount: Uint128,
        msg: Binary,
    },
    /// Only with "approval" api. Allows spender to access an additional amount tokens
    /// from the owner's (env.sender) account. If expires is Some(), overwrites current allowance
    /// expiration with this one.
    IncreaseAllowance {
        spender: String,
        amount: Uint128,
        expires: Option<Expiration>,
    },
    /// Only with "approval" api. Lowers the spender's access of tokens
    /// from the owner's (env.sender) account by amount. If expires is Some(), overwrites current
    /// allowance expiration with this one.
    DecreaseAllowance {
        spender: String,
        amount: Uint128,
        expires: Option<Expiration>,
    },
    /// Only with "approval" api. Transfers amount tokens from owner -> recipient
    /// if `env.sender` has sufficient pre-approval.
    TransferFrom {
        owner: String,
        recipient: String,
        amount: Uint128,
    },
    /// Only with "approval" api. Sends amount tokens from owner -> contract
    /// if `env.sender` has sufficient pre-approval.
    SendFrom {
        owner: String,
        contract: String,
        amount: Uint128,
        msg: Binary,
    },
    /// Only with "approval" api. Destroys tokens forever
    BurnFrom {
        owner: String,
        amount: Uint128,
    },
    /// Only with the "mintable" api. If authorized, creates amount new tokens
    /// and adds to the recipient balance.
    Mint {
        recipient: String,
        amount: Uint128,
    },
    /// Only with the "marketing" api. If authorized, updates marketing metadata.
    /// Setting None/null for any of these will leave it unchanged.
    /// Setting Some("") will clear this field on the contract storage
    UpdateMarketing {
        // A URL pointing to the project behind this token.
        project: Option<String>,
        // A longer description of the token and it's utility. Designed for tooltips or such
        description: Option<String>,
        // The address (if any) who can update this data structure
        marketing: Option<String>,
    },
    /// If set as the "marketing" role on the contract, upload a new URL, SVG, or PNG for the token
    UploadLogo(Logo),
}

impl TryInto<Cw20ExecuteMsg> for ExecuteMsg {
    type Error = StdError;

    fn try_into(self) -> Result<Cw20ExecuteMsg, Self::Error> {
        match self {
            ExecuteMsg::UpdateWhitelist {
                to_add: _,
                to_remove: _,
                restrict_transfers: _,
            } => Err(StdError::generic_err("can't parse into cw20 msg")),
            ExecuteMsg::UpdateAdmin { new_admin: _ } => {
                Err(StdError::generic_err("can't parse into cw20 msg"))
            }
            ExecuteMsg::Transfer { recipient, amount } => {
                Ok(Cw20ExecuteMsg::Transfer { recipient, amount })
            }
            ExecuteMsg::Burn { amount } => Ok(Cw20ExecuteMsg::Burn { amount }),
            ExecuteMsg::Send {
                contract,
                amount,
                msg,
            } => Ok(Cw20ExecuteMsg::Send {
                contract,
                amount,
                msg,
            }),
            ExecuteMsg::IncreaseAllowance {
                spender,
                amount,
                expires,
            } => Ok(Cw20ExecuteMsg::IncreaseAllowance {
                spender,
                amount,
                expires,
            }),
            ExecuteMsg::DecreaseAllowance {
                spender,
                amount,
                expires,
            } => Ok(Cw20ExecuteMsg::DecreaseAllowance {
                spender,
                amount,
                expires,
            }),
            ExecuteMsg::TransferFrom {
                owner,
                recipient,
                amount,
            } => Ok(Cw20ExecuteMsg::TransferFrom {
                owner,
                recipient,
                amount,
            }),
            ExecuteMsg::SendFrom {
                owner,
                contract,
                amount,
                msg,
            } => Ok(Cw20ExecuteMsg::SendFrom {
                owner,
                contract,
                amount,
                msg,
            }),
            ExecuteMsg::BurnFrom { owner, amount } => {
                Ok(Cw20ExecuteMsg::BurnFrom { owner, amount })
            }
            ExecuteMsg::Mint { recipient, amount } => {
                Ok(Cw20ExecuteMsg::Mint { recipient, amount })
            }
            ExecuteMsg::UpdateMarketing {
                project,
                description,
                marketing,
            } => Ok(Cw20ExecuteMsg::UpdateMarketing {
                project,
                description,
                marketing,
            }),
            ExecuteMsg::UploadLogo(l) => Ok(Cw20ExecuteMsg::UploadLogo(l)),
        }
    }
}
#[cosmwasm_schema::cw_serde]
#[derive(QueryResponses)]
#[cfg_attr(feature = "boot", derive(boot_core::QueryFns))]
pub enum QueryMsg {
    #[returns(ConfigResponse)]
    Config {},
    /// Returns the current balance of the given address, 0 if unset.
    /// Return type: BalanceResponse.
    #[returns(BalanceResponse)]
    Balance { address: String },
    /// Returns metadata on the contract - name, decimals, supply, etc.
    /// Return type: TokenInfoResponse.
    #[returns(TokenInfoResponse)]
    TokenInfo {},
    /// Only with "mintable" api.
    /// Returns who can mint and the hard cap on maximum tokens after minting.
    /// Return type: MinterResponse.
    #[returns(MinterResponse)]
    Minter {},
    /// Only with "allowance" api.
    /// Returns how much spender can use from owner account, 0 if unset.
    /// Return type: AllowanceResponse.
    #[returns(AllowanceResponse)]
    Allowance { owner: String, spender: String },
    /// Only with "enumerable" api (and "allowances")
    /// Returns all allowances this owner has approved. Supports pagination.
    /// Return type: AllAllowancesResponse.
    #[returns(AllAllowancesResponse)]
    AllAllowances {
        owner: String,
        start_after: Option<String>,
        limit: Option<u32>,
    },
    /// Only with "enumerable" api
    /// Returns all accounts that have balances. Supports pagination.
    /// Return type: AllAccountsResponse.
    #[returns(AllAccountsResponse)]
    AllAccounts {
        start_after: Option<String>,
        limit: Option<u32>,
    },
    /// Only with "marketing" api
    /// Returns more metadata on the contract to display in the client:
    /// - description, logo, project url, etc.
    /// Return type: MarketingInfoResponse
    #[returns(MarketingInfoResponse)]
    MarketingInfo {},
    /// Only with "marketing" api
    /// Downloads the embedded logo data (if stored on chain). Errors if no logo data is stored for this
    /// contract.
    /// Return type: DownloadLogoResponse.
    #[returns(DownloadLogoResponse)]
    DownloadLogo {},
}

impl TryInto<Cw20QueryMsg> for QueryMsg {
    type Error = StdError;

    fn try_into(self) -> Result<Cw20QueryMsg, Self::Error> {
        match self {
            Self::Balance { address } => Ok(Cw20QueryMsg::Balance { address }),
            Self::TokenInfo {} => Ok(Cw20QueryMsg::TokenInfo {}),
            Self::Minter {} => Ok(Cw20QueryMsg::Minter {}),
            Self::Allowance { owner, spender } => Ok(Cw20QueryMsg::Allowance { owner, spender }),
            Self::AllAllowances {
                owner,
                start_after,
                limit,
            } => Ok(Cw20QueryMsg::AllAllowances {
                owner,
                start_after,
                limit,
            }),
            Self::AllAccounts { start_after, limit } => {
                Ok(Cw20QueryMsg::AllAccounts { start_after, limit })
            }
            Self::MarketingInfo {} => Ok(Cw20QueryMsg::MarketingInfo {}),
            Self::DownloadLogo {} => Ok(Cw20QueryMsg::DownloadLogo {}),
            QueryMsg::Config {} => Err(StdError::generic_err("could not convert into cw20 query")),
        }
    }
}
#[cosmwasm_schema::cw_serde]
pub struct ConfigResponse {
    pub transfers_restricted: bool,
    pub version_control_address: String,
    pub whitelisted_addr: Vec<String>,
    pub admin: String,
}