-
Notifications
You must be signed in to change notification settings - Fork 252
/
Copy pathlib.rs
438 lines (393 loc) · 15.5 KB
/
lib.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
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
/*!
Non-Fungible Token implementation with JSON serialization.
NOTES:
- The maximum balance value is limited by U128 (2**128 - 1).
- JSON calls should pass U128 as a base-10 string. E.g. "100".
- The contract optimizes the inner trie structure by hashing account IDs. It will prevent some
abuse of deep tries. Shouldn't be an issue, once NEAR clients implement full hashing of keys.
- The contract tracks the change in storage before and after the call. If the storage increases,
the contract requires the caller of the contract to attach enough deposit to the function call
to cover the storage cost.
This is done to prevent a denial of service attack on the contract by taking all available storage.
If the storage decreases, the contract will issue a refund for the cost of the released storage.
The unused tokens from the attached deposit are also refunded, so it's safe to
attach more deposit than required.
- To prevent the deployed contract from being modified or deleted, it should not have any access
keys on its account.
*/
use near_contract_standards::non_fungible_token::approval::NonFungibleTokenApproval;
use near_contract_standards::non_fungible_token::core::{
NonFungibleTokenCore, NonFungibleTokenResolver,
};
use near_contract_standards::non_fungible_token::enumeration::NonFungibleTokenEnumeration;
use near_contract_standards::non_fungible_token::metadata::{
NFTContractMetadata, NonFungibleTokenMetadataProvider, TokenMetadata, NFT_METADATA_SPEC,
};
use near_contract_standards::non_fungible_token::NonFungibleToken;
use near_contract_standards::non_fungible_token::{Token, TokenId};
use near_sdk::collections::LazyOption;
use near_sdk::json_types::U128;
use near_sdk::{
env, near, require, AccountId, BorshStorageKey, PanicOnDefault, Promise, PromiseOrValue,
};
use std::collections::HashMap;
#[derive(PanicOnDefault)]
#[near(contract_state)]
pub struct Contract {
tokens: NonFungibleToken,
metadata: LazyOption<NFTContractMetadata>,
}
const DATA_IMAGE_SVG_NEAR_ICON: &str = "data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 288 288'%3E%3Cg id='l' data-name='l'%3E%3Cpath d='M187.58,79.81l-30.1,44.69a3.2,3.2,0,0,0,4.75,4.2L191.86,103a1.2,1.2,0,0,1,2,.91v80.46a1.2,1.2,0,0,1-2.12.77L102.18,77.93A15.35,15.35,0,0,0,90.47,72.5H87.34A15.34,15.34,0,0,0,72,87.84V201.16A15.34,15.34,0,0,0,87.34,216.5h0a15.35,15.35,0,0,0,13.08-7.31l30.1-44.69a3.2,3.2,0,0,0-4.75-4.2L96.14,186a1.2,1.2,0,0,1-2-.91V104.61a1.2,1.2,0,0,1,2.12-.77l89.55,107.23a15.35,15.35,0,0,0,11.71,5.43h3.13A15.34,15.34,0,0,0,216,201.16V87.84A15.34,15.34,0,0,0,200.66,72.5h0A15.35,15.35,0,0,0,187.58,79.81Z'/%3E%3C/g%3E%3C/svg%3E";
#[derive(BorshStorageKey)]
#[near]
enum StorageKey {
NonFungibleToken,
Metadata,
TokenMetadata,
Enumeration,
Approval,
}
#[near]
impl Contract {
/// Initializes the contract owned by `owner_id` with
/// default metadata (for example purposes only).
#[init]
pub fn new_default_meta(owner_id: AccountId) -> Self {
Self::new(
owner_id,
NFTContractMetadata {
spec: NFT_METADATA_SPEC.to_string(),
name: "Example NEAR non-fungible token".to_string(),
symbol: "EXAMPLE".to_string(),
icon: Some(DATA_IMAGE_SVG_NEAR_ICON.to_string()),
base_uri: None,
reference: None,
reference_hash: None,
},
)
}
#[init]
pub fn new(owner_id: AccountId, metadata: NFTContractMetadata) -> Self {
require!(!env::state_exists(), "Already initialized");
metadata.assert_valid();
Self {
tokens: NonFungibleToken::new(
StorageKey::NonFungibleToken,
owner_id,
Some(StorageKey::TokenMetadata),
Some(StorageKey::Enumeration),
Some(StorageKey::Approval),
),
metadata: LazyOption::new(StorageKey::Metadata, Some(&metadata)),
}
}
/// Mint a new token with ID=`token_id` belonging to `token_owner_id`.
///
/// Since this example implements metadata, it also requires per-token metadata to be provided
/// in this call. `self.tokens.mint` will also require it to be Some, since
/// `StorageKey::TokenMetadata` was provided at initialization.
///
/// `self.tokens.mint` will enforce `predecessor_account_id` to equal the `owner_id` given in
/// initialization call to `new`.
#[payable]
pub fn nft_mint(
&mut self,
token_id: TokenId,
token_owner_id: AccountId,
token_metadata: TokenMetadata,
) -> Token {
assert_eq!(env::predecessor_account_id(), self.tokens.owner_id, "Unauthorized");
self.tokens.internal_mint(token_id, token_owner_id, Some(token_metadata))
}
}
#[near]
impl NonFungibleTokenCore for Contract {
#[payable]
fn nft_transfer(
&mut self,
receiver_id: AccountId,
token_id: TokenId,
approval_id: Option<u64>,
memo: Option<String>,
) {
self.tokens.nft_transfer(receiver_id, token_id, approval_id, memo);
}
#[payable]
fn nft_transfer_call(
&mut self,
receiver_id: AccountId,
token_id: TokenId,
approval_id: Option<u64>,
memo: Option<String>,
msg: String,
) -> PromiseOrValue<bool> {
self.tokens.nft_transfer_call(receiver_id, token_id, approval_id, memo, msg)
}
fn nft_token(&self, token_id: TokenId) -> Option<Token> {
self.tokens.nft_token(token_id)
}
}
#[near]
impl NonFungibleTokenResolver for Contract {
#[private]
fn nft_resolve_transfer(
&mut self,
previous_owner_id: AccountId,
receiver_id: AccountId,
token_id: TokenId,
approved_account_ids: Option<HashMap<AccountId, u64>>,
) -> bool {
self.tokens.nft_resolve_transfer(
previous_owner_id,
receiver_id,
token_id,
approved_account_ids,
)
}
}
#[near]
impl NonFungibleTokenApproval for Contract {
#[payable]
fn nft_approve(
&mut self,
token_id: TokenId,
account_id: AccountId,
msg: Option<String>,
) -> Option<Promise> {
self.tokens.nft_approve(token_id, account_id, msg)
}
#[payable]
fn nft_revoke(&mut self, token_id: TokenId, account_id: AccountId) {
self.tokens.nft_revoke(token_id, account_id);
}
#[payable]
fn nft_revoke_all(&mut self, token_id: TokenId) {
self.tokens.nft_revoke_all(token_id);
}
fn nft_is_approved(
&self,
token_id: TokenId,
approved_account_id: AccountId,
approval_id: Option<u64>,
) -> bool {
self.tokens.nft_is_approved(token_id, approved_account_id, approval_id)
}
}
#[near]
impl NonFungibleTokenEnumeration for Contract {
fn nft_total_supply(&self) -> U128 {
self.tokens.nft_total_supply()
}
fn nft_tokens(&self, from_index: Option<U128>, limit: Option<u64>) -> Vec<Token> {
self.tokens.nft_tokens(from_index, limit)
}
fn nft_supply_for_owner(&self, account_id: AccountId) -> U128 {
self.tokens.nft_supply_for_owner(account_id)
}
fn nft_tokens_for_owner(
&self,
account_id: AccountId,
from_index: Option<U128>,
limit: Option<u64>,
) -> Vec<Token> {
self.tokens.nft_tokens_for_owner(account_id, from_index, limit)
}
}
#[near]
impl NonFungibleTokenMetadataProvider for Contract {
fn nft_metadata(&self) -> NFTContractMetadata {
self.metadata.get().unwrap()
}
}
#[cfg(all(test, not(target_arch = "wasm32")))]
mod tests {
use near_sdk::test_utils::{accounts, VMContextBuilder};
use near_sdk::{testing_env, NearToken};
use std::collections::HashMap;
use super::*;
const MINT_STORAGE_COST: NearToken = NearToken::from_yoctonear(5870000000000000000000u128);
fn get_context(predecessor_account_id: AccountId) -> VMContextBuilder {
let mut builder = VMContextBuilder::new();
builder
.current_account_id(accounts(0))
.signer_account_id(predecessor_account_id.clone())
.predecessor_account_id(predecessor_account_id);
builder
}
fn sample_token_metadata() -> TokenMetadata {
TokenMetadata {
title: Some("Olympus Mons".into()),
description: Some("The tallest mountain in the charted solar system".into()),
media: None,
media_hash: None,
copies: Some(1u64),
issued_at: None,
expires_at: None,
starts_at: None,
updated_at: None,
extra: None,
reference: None,
reference_hash: None,
}
}
#[test]
fn test_new() {
let mut context = get_context(accounts(1));
testing_env!(context.build());
let contract = Contract::new_default_meta(accounts(1).into());
testing_env!(context.is_view(true).build());
assert_eq!(contract.nft_token("1".to_string()), None);
}
#[test]
#[should_panic(expected = "The contract is not initialized")]
fn test_default() {
let context = get_context(accounts(1));
testing_env!(context.build());
let _contract = Contract::default();
}
#[test]
fn test_mint() {
let mut context = get_context(accounts(0));
testing_env!(context.build());
let mut contract = Contract::new_default_meta(accounts(0).into());
testing_env!(context
.storage_usage(env::storage_usage())
.attached_deposit(MINT_STORAGE_COST)
.predecessor_account_id(accounts(0))
.build());
let token_id = "0".to_string();
let token = contract.nft_mint(token_id.clone(), accounts(0), sample_token_metadata());
assert_eq!(token.token_id, token_id);
assert_eq!(token.owner_id, accounts(0));
assert_eq!(token.metadata.unwrap(), sample_token_metadata());
assert_eq!(token.approved_account_ids.unwrap(), HashMap::new());
}
#[test]
fn test_transfer() {
let mut context = get_context(accounts(0));
testing_env!(context.build());
let mut contract = Contract::new_default_meta(accounts(0).into());
testing_env!(context
.storage_usage(env::storage_usage())
.attached_deposit(MINT_STORAGE_COST)
.predecessor_account_id(accounts(0))
.build());
let token_id = "0".to_string();
contract.nft_mint(token_id.clone(), accounts(0), sample_token_metadata());
testing_env!(context
.storage_usage(env::storage_usage())
.attached_deposit(NearToken::from_yoctonear(1))
.predecessor_account_id(accounts(0))
.build());
contract.nft_transfer(accounts(1), token_id.clone(), None, None);
testing_env!(context
.storage_usage(env::storage_usage())
.account_balance(env::account_balance())
.is_view(true)
.attached_deposit(NearToken::from_near(0))
.build());
if let Some(token) = contract.nft_token(token_id.clone()) {
assert_eq!(token.token_id, token_id);
assert_eq!(token.owner_id, accounts(1));
assert_eq!(token.metadata.unwrap(), sample_token_metadata());
assert_eq!(token.approved_account_ids.unwrap(), HashMap::new());
} else {
panic!("token not correctly created, or not found by nft_token");
}
}
#[test]
fn test_approve() {
let mut context = get_context(accounts(0));
testing_env!(context.build());
let mut contract = Contract::new_default_meta(accounts(0).into());
testing_env!(context
.storage_usage(env::storage_usage())
.attached_deposit(MINT_STORAGE_COST)
.predecessor_account_id(accounts(0))
.build());
let token_id = "0".to_string();
contract.nft_mint(token_id.clone(), accounts(0), sample_token_metadata());
// alice approves bob
testing_env!(context
.storage_usage(env::storage_usage())
.attached_deposit(NearToken::from_yoctonear(150000000000000000000u128))
.predecessor_account_id(accounts(0))
.build());
contract.nft_approve(token_id.clone(), accounts(1), None);
testing_env!(context
.storage_usage(env::storage_usage())
.account_balance(env::account_balance())
.is_view(true)
.attached_deposit(NearToken::from_near(0))
.build());
assert!(contract.nft_is_approved(token_id.clone(), accounts(1), Some(1)));
}
#[test]
fn test_revoke() {
let mut context = get_context(accounts(0));
testing_env!(context.build());
let mut contract = Contract::new_default_meta(accounts(0).into());
testing_env!(context
.storage_usage(env::storage_usage())
.attached_deposit(MINT_STORAGE_COST)
.predecessor_account_id(accounts(0))
.build());
let token_id = "0".to_string();
contract.nft_mint(token_id.clone(), accounts(0), sample_token_metadata());
// alice approves bob
testing_env!(context
.storage_usage(env::storage_usage())
.attached_deposit(NearToken::from_yoctonear(150000000000000000000))
.predecessor_account_id(accounts(0))
.build());
contract.nft_approve(token_id.clone(), accounts(1), None);
// alice revokes bob
testing_env!(context
.storage_usage(env::storage_usage())
.attached_deposit(NearToken::from_yoctonear(1))
.predecessor_account_id(accounts(0))
.build());
contract.nft_revoke(token_id.clone(), accounts(1));
testing_env!(context
.storage_usage(env::storage_usage())
.account_balance(env::account_balance())
.is_view(true)
.attached_deposit(NearToken::from_near(0))
.build());
assert!(!contract.nft_is_approved(token_id.clone(), accounts(1), None));
}
#[test]
fn test_revoke_all() {
let mut context = get_context(accounts(0));
testing_env!(context.build());
let mut contract = Contract::new_default_meta(accounts(0).into());
testing_env!(context
.storage_usage(env::storage_usage())
.attached_deposit(MINT_STORAGE_COST)
.predecessor_account_id(accounts(0))
.build());
let token_id = "0".to_string();
contract.nft_mint(token_id.clone(), accounts(0), sample_token_metadata());
// alice approves bob
testing_env!(context
.storage_usage(env::storage_usage())
.attached_deposit(NearToken::from_yoctonear(150000000000000000000))
.predecessor_account_id(accounts(0))
.build());
contract.nft_approve(token_id.clone(), accounts(1), None);
// alice revokes bob
testing_env!(context
.storage_usage(env::storage_usage())
.attached_deposit(NearToken::from_yoctonear(1))
.predecessor_account_id(accounts(0))
.build());
contract.nft_revoke_all(token_id.clone());
testing_env!(context
.storage_usage(env::storage_usage())
.account_balance(env::account_balance())
.is_view(true)
.attached_deposit(NearToken::from_near(0))
.build());
assert!(!contract.nft_is_approved(token_id.clone(), accounts(1), Some(1)));
}
}