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
use super::resolver::NonFungibleTokenResolver;
use crate::nft::bind_to_owner::BindToOwnerFeature;
use crate::nft::base::receiver::ext_receiver;
use crate::nft::base::NonFungibleTokenCore;
use crate::nft::metadata::{ TokenMetadata, UpgradeKey, UpgradePrice, BurnerPrice };
use crate::nft::token::{ Token, TokenId };
use crate::nft::utils::{ hash_account_id, refund_approved_account_ids };
use crate::nft::royalty::RoyaltyFeature;
use near_sdk::borsh::{ self, BorshDeserialize, BorshSerialize };
use near_sdk::collections::{ LookupMap, TreeMap, UnorderedSet };
use near_sdk::json_types::Base64VecU8;
use near_sdk::{
    assert_one_yocto,
    env,
    ext_contract,
    log,
    require,
    AccountId,
    BorshStorageKey,
    CryptoHash,
    Gas,
    IntoStorageKey,
    PromiseOrValue,
    PromiseResult,
    StorageUsage,
};
use std::collections::HashMap;
use crate::nft::{TokenRarity, NonFungibleTokenBindToOwner, TokenTypes};

pub const GAS_FOR_RESOLVE_NFT_TRANSFER: Gas = Gas(5_000_000_000_000);
pub const GAS_FOR_NFT_TRANSFER_CALL: Gas = Gas(25_000_000_000_000 + GAS_FOR_RESOLVE_NFT_TRANSFER.0);
pub const GAS_FOR_NFT_TRANSFER: Gas = Gas(25_000_000_000_000);

#[derive(BorshSerialize, BorshStorageKey)]
pub enum StorageKey {
    TokensPerOwner {
        account_hash: Vec<u8>,
    },
    TokenPerOwnerInner {
        account_id_hash: CryptoHash,
    },
}

#[ext_contract(ext_self)]
trait NFTResolver {
    fn nft_resolve_transfer(
        &mut self,
        previous_owner_id: AccountId,
        receiver_id: AccountId,
        token_id: TokenId,
        approved_account_ids: Option<HashMap<AccountId, u64>>
    ) -> bool;
}

/// Implementation of the non-fungible token standard.
/// Allows to include NEP-171 compatible token to any contract.
/// There are next traits that any contract may implement:
///     - NonFungibleTokenCore -- interface with nft_transfer methods. NonFungibleToken provides methods for it.
///     - NonFungibleTokenApproval -- interface with nft_approve methods. NonFungibleToken provides methods for it.
///     - NonFungibleTokenEnumeration -- interface for getting lists of tokens. NonFungibleToken provides methods for it.
///     - NonFungibleTokenMetadata -- return metadata for the token in NEP-177, up to contract to implement.
///
/// For example usage, see examples/non-fungible-token/src/lib.rs.
#[derive(BorshDeserialize, BorshSerialize)]
pub struct NonFungibleToken {
  // The storage size in bytes for each new token
  pub extra_storage_in_bytes_per_token: StorageUsage,

  // always required
  pub owner_by_id: TreeMap<TokenId, AccountId>,

  // required by metadata extension
  pub token_metadata_by_id: Option<LookupMap<TokenId, TokenMetadata>>,

  // required by enumeration extension
  pub tokens_per_owner: Option<LookupMap<AccountId, UnorderedSet<TokenId>>>,

  // required by approval extension
  pub approvals_by_id: Option<LookupMap<TokenId, HashMap<AccountId, u64>>>,
  pub next_approval_id_by_id: Option<LookupMap<TokenId, u64>>,

  // required by royalty and nft_payout extensions
  pub royalty: RoyaltyFeature,

  // required by bind_to_owner extension
  pub bind_to_owner: BindToOwnerFeature,

  // required by upgrade extension
  pub token_rarity_by_id: Option<LookupMap<TokenId, TokenRarity>>,
  pub token_types_by_id: Option<LookupMap<TokenId, TokenTypes>>,

  // required by reveal extension
  pub token_hidden_metadata: UnorderedSet<TokenMetadata>,
  pub tokens_to_reveal: UnorderedSet<TokenId>,
  pub token_reveal_time_by_id: LookupMap<TokenId, u64>,

  // required by upgrade extension
  pub upgrade_prices: Option<LookupMap<UpgradeKey, UpgradePrice>>,
  pub burner_upgrade_prices: Option<LookupMap<UpgradeKey, BurnerPrice>>,
  
}

impl NonFungibleToken {
    pub fn new<Q, R, S, T, R1, B, RM, RT, RTM, E1, E2, U1, U2>(
        owner_by_id_prefix: Q,
        token_metadata_prefix: Option<R>,
        enumeration_prefix: Option<S>,
        approval_prefix: Option<T>,

        nft_royalty_prefix: R1,

        bind_to_owner_prefix: B,

        reveal_hidden_meta_prefix: RM,
        reveal_tokens_prefix: RT,
        reveal_time_prefix: RTM,

        token_rarity_prefix: Option<E1>,        
        token_types_prefix: Option<E2>,

        upgrade_prefix: Option<U1>,
        burner_prefix: Option<U2>,
    )
        -> Self
        where
            Q: IntoStorageKey,
            R: IntoStorageKey,
            S: IntoStorageKey,
            T: IntoStorageKey,
            R1: IntoStorageKey,
            B: IntoStorageKey,
            RM: IntoStorageKey,
            RT: IntoStorageKey,
            RTM: IntoStorageKey,
            E1: IntoStorageKey,
            E2: IntoStorageKey,            
            U1: IntoStorageKey,
            U2: IntoStorageKey
    {
        let (approvals_by_id, next_approval_id_by_id) = if let Some(prefix) = approval_prefix {
            let prefix: Vec<u8> = prefix.into_storage_key();
            (
                Some(LookupMap::new(prefix.clone())),
                Some(LookupMap::new([prefix, "n".into()].concat())),
            )
        } else {
            (None, None)
        };
        let mut this = Self {
            extra_storage_in_bytes_per_token: 0,
            owner_by_id: TreeMap::new(owner_by_id_prefix),
            token_metadata_by_id: token_metadata_prefix.map(LookupMap::new),
            tokens_per_owner: enumeration_prefix.map(LookupMap::new),
            approvals_by_id,
            next_approval_id_by_id,

            royalty: RoyaltyFeature::new(env::current_account_id(), 0, nft_royalty_prefix),
            bind_to_owner: BindToOwnerFeature::new(bind_to_owner_prefix),

            token_hidden_metadata: UnorderedSet::new(reveal_hidden_meta_prefix),
            tokens_to_reveal: UnorderedSet::new(reveal_tokens_prefix),
            token_reveal_time_by_id: LookupMap::new(reveal_time_prefix),

            token_rarity_by_id: token_rarity_prefix.map(LookupMap::new),            
            token_types_by_id: token_types_prefix.map(LookupMap::new),

            upgrade_prices: upgrade_prefix.map(LookupMap::new),
            burner_upgrade_prices: burner_prefix.map(LookupMap::new),
        };
        this.measure_min_token_storage_cost();
        this
    }

    // TODO: does this seem reasonable?
    fn measure_min_token_storage_cost(&mut self) {
        let initial_storage_usage = env::storage_usage();
        // 64 Length because this is the max account id length
        let tmp_token_id = "a".repeat(64);
        let tmp_owner_id = AccountId::new_unchecked("a".repeat(64));

        // 1. set some dummy data
        self.owner_by_id.insert(&tmp_token_id, &tmp_owner_id);
        if let Some(token_metadata_by_id) = &mut self.token_metadata_by_id {
            token_metadata_by_id.insert(
                &tmp_token_id,
                &(TokenMetadata {
                    title: Some("a".repeat(64)),
                    description: Some("a".repeat(64)),
                    media: Some("a".repeat(64)),
                    media_hash: Some(Base64VecU8::from("a".repeat(64).as_bytes().to_vec())),
                    copies: Some(1),
                    issued_at: None,
                    expires_at: None,
                    starts_at: None,
                    updated_at: None,
                    extra: None,
                    reference: None,
                    reference_hash: None,
                })
            );
        }
        if let Some(tokens_per_owner) = &mut self.tokens_per_owner {
            let u = &mut UnorderedSet::new(StorageKey::TokensPerOwner {
                account_hash: env::sha256(tmp_owner_id.as_bytes()),
            });
            u.insert(&tmp_token_id);
            tokens_per_owner.insert(&tmp_owner_id, u);
        }
        if let Some(approvals_by_id) = &mut self.approvals_by_id {
            let mut approvals = HashMap::new();
            approvals.insert(tmp_owner_id.clone(), 1u64);
            approvals_by_id.insert(&tmp_token_id, &approvals);
        }
        if let Some(next_approval_id_by_id) = &mut self.next_approval_id_by_id {
            next_approval_id_by_id.insert(&tmp_token_id, &1u64);
        }
        let u = UnorderedSet::new(
            (StorageKey::TokenPerOwnerInner {
                account_id_hash: hash_account_id(&tmp_owner_id),
            })
                .try_to_vec()
                .unwrap()
        );
        if let Some(tokens_per_owner) = &mut self.tokens_per_owner {
            tokens_per_owner.insert(&tmp_owner_id, &u);
        }

        // 2. see how much space it took
        self.extra_storage_in_bytes_per_token = env::storage_usage() - initial_storage_usage;

        // 3. roll it all back
        if let Some(next_approval_id_by_id) = &mut self.next_approval_id_by_id {
            next_approval_id_by_id.remove(&tmp_token_id);
        }
        if let Some(approvals_by_id) = &mut self.approvals_by_id {
            approvals_by_id.remove(&tmp_token_id);
        }
        if let Some(tokens_per_owner) = &mut self.tokens_per_owner {
            tokens_per_owner.remove(&tmp_owner_id);
        }
        if let Some(token_metadata_by_id) = &mut self.token_metadata_by_id {
            token_metadata_by_id.remove(&tmp_token_id);
        }
        if let Some(tokens_per_owner) = &mut self.tokens_per_owner {
            tokens_per_owner.remove(&tmp_owner_id);
        }
        self.owner_by_id.remove(&tmp_token_id);
    }
}

impl NonFungibleTokenCore for NonFungibleToken {
    fn nft_transfer(
        &mut self,
        receiver_id: AccountId,
        token_id: TokenId,
        approval_id: Option<u64>,
        memo: Option<String>
    ) {
        assert_one_yocto();
        let sender_id = env::predecessor_account_id();

        self.internal_transfer(&sender_id, &receiver_id, &token_id, approval_id, memo);
    }

    fn nft_transfer_call(
        &mut self,
        receiver_id: AccountId,
        token_id: TokenId,
        approval_id: Option<u64>,
        memo: Option<String>,
        msg: String
    ) -> PromiseOrValue<bool> {
        assert_one_yocto();

        require!(
            env::prepaid_gas() > GAS_FOR_NFT_TRANSFER_CALL + GAS_FOR_RESOLVE_NFT_TRANSFER,
            "More gas is required"
        );
        let sender_id = env::predecessor_account_id();
        let (old_owner, old_approvals) = self.internal_transfer(
            &sender_id,
            &receiver_id,
            &token_id,
            approval_id,
            memo
        );

        ext_receiver
            ::ext(receiver_id.clone())
            .with_static_gas(env::prepaid_gas() - GAS_FOR_NFT_TRANSFER_CALL)
            .nft_on_transfer(sender_id, old_owner.clone(), token_id.clone(), msg)
            .then(
                ext_self
                    ::ext(env::current_account_id())
                    .with_static_gas(GAS_FOR_RESOLVE_NFT_TRANSFER)
                    .nft_resolve_transfer(old_owner, receiver_id, token_id, old_approvals)
            )
            .into()
    }

    fn nft_token(&self, token_id: TokenId) -> Option<Token> {
        let owner_id = self.owner_by_id.get(&token_id)?;
        let token = self.enum_get_token(owner_id.clone(), token_id.clone());

        Some(token)
    }
}

impl NonFungibleTokenResolver for NonFungibleToken {
    /// Returns true if token was successfully transferred to `receiver_id`.
    fn nft_resolve_transfer(
        &mut self,
        previous_owner_id: AccountId,
        receiver_id: AccountId,
        token_id: TokenId,
        approved_account_ids: Option<HashMap<AccountId, u64>>
    ) -> bool {
        // Get whether token should be returned
        let must_revert = match env::promise_result(0) {
            PromiseResult::NotReady => env::abort(),
            PromiseResult::Successful(value) => {
                if let Ok(yes_or_no) = near_sdk::serde_json::from_slice::<bool>(&value) {
                    yes_or_no
                } else {
                    true
                }
            }
            PromiseResult::Failed => true,
        };

        // if call succeeded, return early
        if !must_revert {
            return true;
        }

        // OTHERWISE, try to set owner back to previous_owner_id and restore approved_account_ids

        // Check that receiver didn't already transfer it away or burn it.
        if let Some(current_owner) = self.owner_by_id.get(&token_id) {
            if current_owner != receiver_id {
                // The token is not owned by the receiver anymore. Can't return it.
                return true;
            }
        } else {
            // The token was burned and doesn't exist anymore.
            // Refund storage cost for storing approvals to original owner and return early.
            if let Some(approved_account_ids) = approved_account_ids {
                refund_approved_account_ids(previous_owner_id, &approved_account_ids);
            }
            return true;
        }

        log!("Return token {} from @{} to @{}", token_id, receiver_id, previous_owner_id);

        self.internal_transfer_unguarded(&token_id, &receiver_id, &previous_owner_id);

        // If using Approval Management extension,
        // 1. revert any approvals receiver already set, refunding storage costs
        // 2. reset approvals to what previous owner had set before call to nft_transfer_call
        if let Some(by_id) = &mut self.approvals_by_id {
            if let Some(receiver_approvals) = by_id.get(&token_id) {
                refund_approved_account_ids(receiver_id, &receiver_approvals);
            }
            if let Some(previous_owner_approvals) = approved_account_ids {
                by_id.insert(&token_id, &previous_owner_approvals);
            }
        }

        false
    }
}