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
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};

use cosmwasm_std::{Empty, Addr, Reply, SubMsgResult};
use cw2::{get_contract_version, set_contract_version};
pub use cw721_archid::{ContractError, InstantiateMsg, MintMsg, MinterResponse, QueryMsg};
use cw721_updatable::{ContractInfoResponse};

#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub struct MigrateMsg {}

#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Serialize, Deserialize, Clone, PartialEq, JsonSchema, Debug)]
pub struct Subdomain {
    pub name: Option<String>,
    pub resolver: Option<Addr>,
    pub minted: Option<bool>,
    pub created: Option<u64>,
    pub expiry: Option<u64>,
}

#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Serialize, Deserialize, Clone, PartialEq, JsonSchema, Debug)]
pub struct Account {
  pub username: Option<String>,
  pub profile: Option<String>,
  pub account_type: Option<String>,
  pub verfication_hash: Option<String>,
}

#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Serialize, Deserialize, Clone, PartialEq, JsonSchema, Debug)]
pub struct Website {
  pub url: Option<String>,
  pub domain: Option<String>,
  pub verfication_hash: Option<String>,
}

#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Serialize, Deserialize, Clone, PartialEq, JsonSchema, Debug)]
pub struct Metadata {
  pub name: Option<String>,         // e.g. for interoperability with external marketplaces
  pub description: Option<String>,  // e.g. ibid.
  pub image: Option<String>,        // e.g. ibid.
  pub created: Option<u64>,
  pub expiry: Option<u64>,
  pub domain: Option<String>,
  pub subdomains: Option<Vec<Subdomain>>,
  pub accounts: Option<Vec<Account>>,
  pub websites: Option<Vec<Website>>,
}

pub type Extension = Option<Metadata>;

pub type Cw721MetadataContract<'a> = cw721_archid::Cw721Contract<'a, Extension, Empty, Empty, Empty>;

pub type ExecuteMsg = cw721_archid::ExecuteMsg<Extension, Empty>;
pub type UpdateMetadataMsg = cw721_archid::msg::UpdateMetadataMsg<Extension>;

const CONTRACT_NAME: &str = "crates.io:archid-token";
const CONTRACT_VERSION: &str = env!("CARGO_PKG_VERSION");

pub mod entry {
    use super::*;

    #[cfg(not(feature = "library"))]
    use cosmwasm_std::entry_point;
    use cosmwasm_std::{Binary, Deps, DepsMut, Env, MessageInfo, Response, StdResult};

    #[cfg_attr(not(feature = "library"), entry_point)]
    pub fn instantiate(
        deps: DepsMut,
        _env: Env,
        _info: MessageInfo,
        msg: InstantiateMsg,
    ) -> StdResult<Response> {
        set_contract_version(deps.storage, CONTRACT_NAME, CONTRACT_VERSION)?;

        let info = ContractInfoResponse {
            name: msg.name,
            symbol: msg.symbol,
        };
        Cw721MetadataContract::default()
            .contract_info
            .save(deps.storage, &info)?;
        let minter = deps.api.addr_validate(&msg.minter)?;
        Cw721MetadataContract::default()
            .minter
            .save(deps.storage, &minter)?;
        Ok(Response::default())
    }

    #[cfg_attr(not(feature = "library"), entry_point)]
    pub fn execute(
        deps: DepsMut,
        env: Env,
        info: MessageInfo,
        msg: ExecuteMsg,
    ) -> Result<Response, ContractError> {
        Cw721MetadataContract::default().execute(deps, env, info, msg)
    }

    #[cfg_attr(not(feature = "library"), entry_point)]
    pub fn reply(_deps: DepsMut, _env: Env, msg: Reply) -> Result<Response, ContractError> {
        match msg.result {
            SubMsgResult::Ok(_) => Ok(Response::default()),
            SubMsgResult::Err(_) => Err(ContractError::Unauthorized {}),
        }
    }

    #[cfg_attr(not(feature = "library"), entry_point)]
    pub fn query(deps: Deps, env: Env, msg: QueryMsg<Empty>) -> StdResult<Binary> {
        Cw721MetadataContract::default().query(deps, env, msg)
    }

    #[cfg_attr(not(feature = "library"), entry_point)]
    pub fn migrate(deps: DepsMut, _env: Env, _msg: MigrateMsg) -> Result<Response, ContractError> {
        let original_version = get_contract_version(deps.storage)?;
        let name = CONTRACT_NAME.to_string();
        let version = CONTRACT_VERSION.to_string();
        if original_version.contract != name {
            return Err(ContractError::Unauthorized {});
        }
        if original_version.version >= version {
            return Err(ContractError::Unauthorized {});
        }
        set_contract_version(deps.storage, CONTRACT_NAME, CONTRACT_VERSION)?;
        Ok(Response::default())
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    use cosmwasm_std::testing::{mock_dependencies, mock_env, mock_info};
    use cw721_updatable::{Cw721Query, NftInfoResponse};

    const CREATOR: &str = "creator";

    #[test]
    fn use_metadata_extension() {
        let mut deps = mock_dependencies();
        let contract = Cw721MetadataContract::default();

        let info = mock_info(CREATOR, &[]);
        let init_msg = InstantiateMsg {
            name: "archid token".to_string(),
            symbol: "AID".to_string(),
            minter: CREATOR.to_string(),
        };
        contract
            .instantiate(deps.as_mut(), mock_env(), info.clone(), init_msg)
            .unwrap();

        let resolver_addr = Addr::unchecked("archway1yvnw8xj5elngcq95e2n2p8f80zl7shfwyxk88858pl6cgzveeqtqy7xtf7".to_string()); 

        let subdomain1 = Subdomain {
            name: Some("game".to_string()),
            resolver: Some(resolver_addr.clone()),
            minted: Some(false),
            created: Some(1000000),
            expiry: Some(1234567),
        };
        let subdomain2 = Subdomain {
            name: Some("dapp".to_string()),
            resolver: Some(resolver_addr.clone()),
            minted: Some(false),
            created: Some(1000000),
            expiry: Some(1234567),
        };
        let subdomain3 = Subdomain {
            name: Some("market".to_string()),
            resolver: Some(resolver_addr.clone()),
            minted: Some(false),
            created: Some(1000000),
            expiry: Some(1234567),
        };

        let subdomains = vec![
            subdomain1, 
            subdomain2, 
            subdomain3
        ];

        let accounts = vec![
            Account {
                username: Some("drew@chainofinsight.com".to_string()),
                profile: None,
                account_type: Some("email".to_string()),
                verfication_hash: None, // XXX: Only "self attestations" for now
            },
            Account {
                username: Some("@chainofinsight".to_string()),
                profile: Some("twitter.com/chainofinsight".to_string()),
                account_type: Some("twitter".to_string()),
                verfication_hash: None,
            }
        ];
    
        let websites = vec![
            Website {
                url: Some("drewstaylor.com".to_string()),
                domain: Some("drewstaylor.arch".to_string()),
                verfication_hash: None,
            },
            Website {
                url: Some("game.drewstaylor.com".to_string()),
                domain: Some("game.drewstaylor.arch".to_string()),
                verfication_hash: None,
            },
            Website {
                url: Some("dapp.drewstaylor.com".to_string()),
                domain: Some("dapp.drewstaylor.arch".to_string()),
                verfication_hash: None,
            },
            Website {
                url: Some("market.drewstaylor.com".to_string()),
                domain: Some("market.drewstaylor.arch".to_string()),
                verfication_hash: None,
            }
        ];
    
        let metadata_extension = Some(Metadata {
            name: Some("drewstaylor.arch".into()),
            description: Some("default token description".into()),
            image: Some("ipfs://QmZdPdZzZum2jQ7jg1ekfeE3LSz1avAaa42G6mfimw9TEn".into()),
            domain: Some("drewstaylor.arch".into()),
            created: Some(1000000),
            expiry: Some(1234567),
            subdomains: Some(subdomains),
            accounts: Some(accounts),
            websites: Some(websites),
        });

        let token_id = "drewstaylor.arch";
        let mint_msg = MintMsg {
            token_id: token_id.to_string(),
            owner: CREATOR.to_string(),
            token_uri: None,
            extension: metadata_extension,
        };
        let exec_msg = ExecuteMsg::Mint(mint_msg.clone());
        contract
            .execute(deps.as_mut(), mock_env(), info, exec_msg)
            .unwrap();

        let res = contract.nft_info(deps.as_ref(), token_id.into()).unwrap();

        assert_eq!(res.token_uri, mint_msg.token_uri);
        assert_eq!(res.extension, mint_msg.extension);
    }

    #[test]
    fn updating_metadata() {
        let mut deps = mock_dependencies();
        let contract = Cw721MetadataContract::default();

        let info = mock_info(CREATOR, &[]);
        let init_msg = InstantiateMsg {
            name: "archid token".to_string(),
            symbol: "AID".to_string(),
            minter: CREATOR.to_string(),
        };
        contract
            .instantiate(deps.as_mut(), mock_env(), info.clone(), init_msg)
            .unwrap();

        let token_id1 = "updatable".to_string();
        let token_id2 = "won't be updated".to_string();

        let metadata_extension = Some(Metadata {
            name: Some("original.arch".into()),
            description: Some("default token description".into()),
            image: Some("ipfs://QmZdPdZzZum2jQ7jg1ekfeE3LSz1avAaa42G6mfimw9TEn".into()),
            domain: Some("original.arch".into()),
            created: Some(1000000),
            expiry: Some(1234567),
            subdomains: None,
            accounts: None,
            websites: None,
        });

        let modified_metadata_extension = Some(Metadata {
            name: Some("modified.arch".into()),
            description: Some("default token description".into()),
            image: Some("ipfs://QmZdPdZzZum2jQ7jg1ekfeE3LSz1avAaa42G6mfimw9TEn".into()),
            domain: Some("modified.arch".into()),
            created: Some(1000000),
            expiry: Some(1234567),
            subdomains: None,
            accounts: None,
            websites: None,
        });

        let mint_msg = ExecuteMsg::Mint(MintMsg {
            token_id: token_id1.clone(),
            owner: CREATOR.to_string(),
            token_uri: None,
            extension: metadata_extension.clone(),
        });

        let mint_msg2 = ExecuteMsg::Mint(MintMsg {
            token_id: token_id2.clone(),
            owner: "innocent hodlr".to_string(),
            token_uri: None,
            extension: metadata_extension.clone(),
        });

        let err_metadata_extension = Some(Metadata {
            name: Some("evil doer".into()),
            description: Some("has rugged your token".into()),
            image: Some("rugged".into()),
            domain: None,
            created: None,
            expiry: None,
            subdomains: None,
            accounts: None,
            websites: None,
        });

        let update_msg = ExecuteMsg::UpdateMetadata(UpdateMetadataMsg {
            token_id: token_id1.clone(),
            extension: modified_metadata_extension.clone(),
        });

        let err_update_msg = ExecuteMsg::UpdateMetadata(UpdateMetadataMsg {
            token_id: token_id1.clone(),
            extension: err_metadata_extension.clone(),
        });

        // Mint
        let admin = mock_info(CREATOR, &[]);
        let _mint1 = contract
            .execute(deps.as_mut(), mock_env(), admin.clone(), mint_msg)
            .unwrap();

        let _mint2 = contract
            .execute(deps.as_mut(), mock_env(), admin.clone(), mint_msg2)
            .unwrap();

        // Original NFT infos are correct
        let info1 = contract.nft_info(deps.as_ref(), token_id1.clone()).unwrap();
        assert_eq!(
            info1,
            NftInfoResponse {
                token_uri: None,
                extension: metadata_extension.clone(),
            }
        );

        let info2 = contract.nft_info(deps.as_ref(), token_id2.clone()).unwrap();
        assert_eq!(
            info2,
            NftInfoResponse {
                token_uri: None,
                extension: metadata_extension.clone(),
            }
        );

        // Random cannot update NFT
        let random = mock_info("random", &[]);
        
        let err = contract
            .execute(deps.as_mut(), mock_env(), random, err_update_msg)
            .unwrap_err();
        assert_eq!(err, ContractError::Unauthorized {});

        // Only allowed minters can update NFT
        let _update = contract
            .execute(deps.as_mut(), mock_env(), admin.clone(), update_msg)
            .unwrap();

        let update_info = contract.nft_info(deps.as_ref(), token_id1.clone()).unwrap();

        // Modified NFT info is correct
        assert_eq!(
            update_info,
            NftInfoResponse {
                token_uri: None,
                extension: modified_metadata_extension,
            }
        );
    }

    #[test]
    fn burning_admin_only() {
        let mut deps = mock_dependencies();
        let contract = Cw721MetadataContract::default();

        let info = mock_info(CREATOR, &[]);
        let init_msg = InstantiateMsg {
            name: "archid token".to_string(),
            symbol: "AID".to_string(),
            minter: CREATOR.to_string(),
        };
        contract
            .instantiate(deps.as_mut(), mock_env(), info.clone(), init_msg)
            .unwrap();

        let token_id = "petrify".to_string();
        let token_uri = "https://www.merriam-webster.com/dictionary/petrify".to_string();

        let mint_msg = ExecuteMsg::Mint(MintMsg {
            token_id: token_id.clone(),
            owner: "someone".to_string(),
            token_uri: Some(token_uri),
            extension: None,
        });

        let burn_msg = ExecuteMsg::Burn { token_id };

        // Mint NFT
        let admin = mock_info(CREATOR, &[]);
        let _ = contract
            .execute(deps.as_mut(), mock_env(), admin.clone(), mint_msg)
            .unwrap();

        // Owner not allowed to burn as admin
        let owner = mock_info("someone", &[]);
        let err = contract
            .execute(deps.as_mut(), mock_env(), owner, burn_msg.clone())
            .unwrap_err();

        assert_eq!(err, ContractError::Unauthorized {});

        // Admin can burn tokens owned by anyone
        let _ = contract
            .execute(deps.as_mut(), mock_env(), admin, burn_msg)
            .unwrap();

        // Ensure num tokens decreases
        let count = contract.num_tokens(deps.as_ref()).unwrap();
        assert_eq!(0, count.count);

        // Requesting NFT metadata returns error
        let _ = contract
            .nft_info(deps.as_ref(), "petrify".to_string())
            .unwrap_err();

        // Listing token_ids should now be empty
        let tokens = contract.all_tokens(deps.as_ref(), None, None).unwrap();
        assert!(tokens.tokens.is_empty());
    }
}