-
Notifications
You must be signed in to change notification settings - Fork 180
/
state.rs
418 lines (377 loc) · 12.5 KB
/
state.rs
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
use cosmwasm_schema::cw_serde;
use cosmwasm_std::{
from_json, to_json_binary, Addr, Binary, BlockInfo, Decimal, Deps, Empty, Env, MessageInfo,
StdResult, Storage, Timestamp,
};
use cw_ownable::{OwnershipStore, OWNERSHIP};
use cw_storage_plus::{Index, IndexList, IndexedMap, Item, Map, MultiIndex};
use cw_utils::Expiration;
use serde::de::DeserializeOwned;
use crate::error::Cw721ContractError;
use crate::traits::{Contains, Cw721CustomMsg, Cw721State, FromAttributesState, ToAttributesState};
use crate::{traits::StateFactory, NftExtensionMsg};
/// Creator owns this contract and can update collection info!
/// !!! Important note here: !!!
/// - creator is stored using using cw-ownable's OWNERSHIP singleton, so it is not stored here
/// - in release v0.18.0 it was used for minter (which is confusing), but now it is used for creator
pub const CREATOR: OwnershipStore = OWNERSHIP;
/// - minter is stored in the contract storage using cw_ownable::OwnershipStore (same as for OWNERSHIP but with different key)
pub const MINTER: OwnershipStore = OwnershipStore::new("collection_minter");
// ----------------------
// NOTE: below are max restrictions for default collection extension (CollectionExtensionResponse)
// This may be quite restrictive and may be increased in the future.
// Custom contracts may also provide different collection extension.
// Please also note, each element in the collection extension is stored as a separate `Attribute`.
/// Maximum length of the description field in the collection info.
pub const MAX_COLLECTION_DESCRIPTION_LENGTH: u32 = 512;
/// Max increase/decrease of of royalty share percentage.
pub const MAX_ROYALTY_SHARE_DELTA_PCT: u64 = 2;
/// Max royalty share percentage.
pub const MAX_ROYALTY_SHARE_PCT: u64 = 10;
// ----------------------
pub const ATTRIBUTE_DESCRIPTION: &str = "description";
pub const ATTRIBUTE_IMAGE: &str = "image";
pub const ATTRIBUTE_EXTERNAL_LINK: &str = "external_link";
pub const ATTRIBUTE_EXPLICIT_CONTENT: &str = "explicit_content";
pub const ATTRIBUTE_START_TRADING_TIME: &str = "start_trading_time";
pub const ATTRIBUTE_ROYALTY_INFO: &str = "royalty_info";
// ----------------------
pub struct Cw721Config<
'a,
// NftInfo extension (onchain metadata).
TNftExtension,
> where
TNftExtension: Cw721State,
{
/// Note: replaces deprecated/legacy key "nft_info"!
pub collection_info: Item<'a, CollectionInfo>,
pub collection_extension: Map<'a, String, Attribute>,
pub num_tokens: Item<'a, u64>,
/// Stored as (granter, operator) giving operator full control over granter's account.
/// NOTE: granter is the owner, so operator has only control for NFTs owned by granter!
pub operators: Map<'a, (&'a Addr, &'a Addr), Expiration>,
pub nft_info: IndexedMap<'a, &'a str, NftInfo<TNftExtension>, TokenIndexes<'a, TNftExtension>>,
pub withdraw_address: Item<'a, String>,
}
impl<TNftExtension> Default for Cw721Config<'static, TNftExtension>
where
TNftExtension: Cw721State,
{
fn default() -> Self {
Self::new(
// `cw721_` prefix is added for avoiding conflicts with other contracts.
"cw721_collection_info", // replaces deprecated/legacy key "nft_info"
"cw721_collection_info_extension",
"num_tokens",
"operators",
"tokens",
"tokens__owner",
"withdraw_address",
)
}
}
impl<'a, TNftExtension> Cw721Config<'a, TNftExtension>
where
TNftExtension: Cw721State,
{
fn new(
collection_info_key: &'a str,
collection_info_extension_key: &'a str,
num_tokens_key: &'a str,
operator_key: &'a str,
nft_info_key: &'a str,
nft_info_owner_key: &'a str,
withdraw_address_key: &'a str,
) -> Self {
let indexes = TokenIndexes {
owner: MultiIndex::new(token_owner_idx, nft_info_key, nft_info_owner_key),
};
Self {
collection_info: Item::new(collection_info_key),
num_tokens: Item::new(num_tokens_key),
operators: Map::new(operator_key),
nft_info: IndexedMap::new(nft_info_key, indexes),
withdraw_address: Item::new(withdraw_address_key),
collection_extension: Map::new(collection_info_extension_key),
}
}
pub fn token_count(&self, storage: &dyn Storage) -> StdResult<u64> {
Ok(self.num_tokens.may_load(storage)?.unwrap_or_default())
}
pub fn increment_tokens(&self, storage: &mut dyn Storage) -> StdResult<u64> {
let val = self.token_count(storage)? + 1;
self.num_tokens.save(storage, &val)?;
Ok(val)
}
pub fn decrement_tokens(&self, storage: &mut dyn Storage) -> StdResult<u64> {
let val = self.token_count(storage)? - 1;
self.num_tokens.save(storage, &val)?;
Ok(val)
}
}
pub fn token_owner_idx<TNftExtension>(_pk: &[u8], d: &NftInfo<TNftExtension>) -> Addr {
d.owner.clone()
}
#[cw_serde]
pub struct NftInfo<TNftExtension> {
/// The owner of the newly minted NFT
pub owner: Addr,
/// Approvals are stored here, as we clear them all upon transfer and cannot accumulate much
pub approvals: Vec<Approval>,
/// Universal resource identifier for this NFT
/// Should point to a JSON file that conforms to the ERC721
/// Metadata JSON Schema
pub token_uri: Option<String>,
/// You can add any custom metadata here when you extend cw721-base
pub extension: TNftExtension,
}
#[cw_serde]
pub struct Approval {
/// Account that can transfer/send the token
pub spender: Addr,
/// When the Approval expires (maybe Expiration::never)
pub expires: Expiration,
}
impl Approval {
pub fn is_expired(&self, block: &BlockInfo) -> bool {
self.expires.is_expired(block)
}
}
pub struct TokenIndexes<'a, TNftExtension>
where
TNftExtension: Cw721State,
{
pub owner: MultiIndex<'a, Addr, NftInfo<TNftExtension>, String>,
}
impl<'a, TNftExtension> IndexList<NftInfo<TNftExtension>> for TokenIndexes<'a, TNftExtension>
where
TNftExtension: Cw721State,
{
fn get_indexes(
&'_ self,
) -> Box<dyn Iterator<Item = &'_ dyn Index<NftInfo<TNftExtension>>> + '_> {
let v: Vec<&dyn Index<NftInfo<TNftExtension>>> = vec![&self.owner];
Box::new(v.into_iter())
}
}
#[cw_serde]
pub struct CollectionInfo {
pub name: String,
pub symbol: String,
pub updated_at: Timestamp,
}
/// Explicit type equivalent to `Vec<Attribute>`, for better distinction.
pub type CollectionExtensionAttributes = Vec<Attribute>;
#[cw_serde]
pub struct Attribute {
pub key: String,
pub value: Binary,
}
impl Attribute {
pub fn value<T>(&self) -> Result<T, Cw721ContractError>
where
T: DeserializeOwned,
{
Ok(from_json(&self.value)?)
}
}
#[cw_serde]
pub struct RoyaltyInfo {
pub payment_address: Addr,
pub share: Decimal,
}
impl Cw721State for RoyaltyInfo {}
impl Cw721CustomMsg for RoyaltyInfo {}
impl ToAttributesState for Empty {
fn to_attributes_state(&self) -> Result<Vec<Attribute>, Cw721ContractError> {
Ok(vec![])
}
}
impl ToAttributesState for RoyaltyInfo {
fn to_attributes_state(&self) -> Result<Vec<Attribute>, Cw721ContractError> {
Ok(vec![Attribute {
key: ATTRIBUTE_ROYALTY_INFO.to_string(),
value: to_json_binary(&self.clone()).unwrap(),
}])
}
}
impl FromAttributesState for RoyaltyInfo {
fn from_attributes_state(attributes: &[Attribute]) -> Result<Self, Cw721ContractError> {
let royalty_info = attributes
.iter()
.find(|attr| attr.key == ATTRIBUTE_ROYALTY_INFO)
.ok_or_else(|| {
Cw721ContractError::AttributeMissing("royalty payment address".to_string())
})?
.value::<RoyaltyInfo>()?;
Ok(royalty_info)
}
}
impl FromAttributesState for Empty {
fn from_attributes_state(_attributes: &[Attribute]) -> Result<Self, Cw721ContractError> {
Ok(Empty {})
}
}
#[cw_serde]
pub struct CollectionExtension<TRoyaltyInfo> {
pub description: String,
pub image: String,
pub external_link: Option<String>,
pub explicit_content: Option<bool>,
pub start_trading_time: Option<Timestamp>,
pub royalty_info: Option<TRoyaltyInfo>,
}
impl Cw721State for CollectionExtension<RoyaltyInfo> {}
// see: https://docs.opensea.io/docs/metadata-standards
#[cw_serde]
#[derive(Default)]
pub struct NftExtension {
pub image: Option<String>,
pub image_data: Option<String>,
pub external_url: Option<String>,
pub description: Option<String>,
pub name: Option<String>,
pub attributes: Option<Vec<Trait>>,
pub background_color: Option<String>,
pub animation_url: Option<String>,
pub youtube_url: Option<String>,
}
impl Cw721State for NftExtension {}
impl From<NftExtensionMsg> for NftExtension {
fn from(msg: NftExtensionMsg) -> Self {
NftExtension {
image: msg.image,
image_data: msg.image_data,
external_url: msg.external_url,
description: msg.description,
name: msg.name,
attributes: msg.attributes,
background_color: msg.background_color,
animation_url: msg.animation_url,
youtube_url: msg.youtube_url,
}
}
}
impl Contains for Empty {
fn contains(&self, _other: &Empty) -> bool {
true
}
}
impl Contains for NftExtension {
fn contains(&self, other: &NftExtension) -> bool {
fn is_equal(a: &Option<String>, b: &Option<String>) -> bool {
match (a, b) {
(Some(a), Some(b)) => a.contains(b),
(Some(_), None) => true,
(None, None) => true,
_ => false,
}
}
if !is_equal(&self.image, &other.image) {
return false;
}
if !is_equal(&self.image_data, &other.image_data) {
return false;
}
if !is_equal(&self.external_url, &other.external_url) {
return false;
}
if !is_equal(&self.description, &other.description) {
return false;
}
if !is_equal(&self.name, &other.name) {
return false;
}
if !is_equal(&self.background_color, &other.background_color) {
return false;
}
if !is_equal(&self.animation_url, &other.animation_url) {
return false;
}
if !is_equal(&self.youtube_url, &other.youtube_url) {
return false;
}
if let (Some(a), Some(b)) = (&self.attributes, &other.attributes) {
for (i, b) in b.iter().enumerate() {
if !a[i].eq(b) {
return false;
}
}
}
true
}
}
impl<T> Contains for Option<T>
where
T: Contains,
{
fn contains(&self, other: &Option<T>) -> bool {
match (self, other) {
(Some(a), Some(b)) => a.contains(b),
(None, None) => true,
_ => false,
}
}
}
#[cw_serde]
pub struct Trait {
pub display_type: Option<String>,
pub trait_type: String,
pub value: String,
}
impl StateFactory<Trait> for Trait {
fn create(
&self,
deps: Deps,
env: &Env,
info: Option<&MessageInfo>,
current: Option<&Trait>,
) -> Result<Trait, Cw721ContractError> {
self.validate(deps, env, info, current)?;
Ok(self.clone())
}
fn validate(
&self,
_deps: Deps,
_env: &Env,
_info: Option<&MessageInfo>,
_current: Option<&Trait>,
) -> Result<(), Cw721ContractError> {
if self.trait_type.is_empty() {
return Err(Cw721ContractError::TraitTypeEmpty {});
}
if self.value.is_empty() {
return Err(Cw721ContractError::TraitValueEmpty {});
}
if let Some(display_type) = &self.display_type {
if display_type.is_empty() {
return Err(Cw721ContractError::TraitDisplayTypeEmpty {});
}
}
Ok(())
}
}
impl StateFactory<Vec<Trait>> for Vec<Trait> {
fn create(
&self,
deps: Deps,
env: &Env,
info: Option<&MessageInfo>,
current: Option<&Vec<Trait>>,
) -> Result<Vec<Trait>, Cw721ContractError> {
self.validate(deps, env, info, current)?;
Ok(self.clone())
}
fn validate(
&self,
deps: Deps,
env: &Env,
info: Option<&MessageInfo>,
_current: Option<&Vec<Trait>>,
) -> Result<(), Cw721ContractError> {
for attribute in self {
attribute.validate(deps, env, info, None)?;
}
Ok(())
}
}