forked from near/near-sdk-rs
-
Notifications
You must be signed in to change notification settings - Fork 1
/
workspaces.rs
706 lines (616 loc) · 21.5 KB
/
workspaces.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
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
use std::str::FromStr;
use near_sdk::json_types::U128;
use near_workspaces::operations::Function;
use near_workspaces::result::ValueOrReceiptId;
use near_workspaces::{types::NearToken, Account, AccountId, Contract};
use rstest::{fixture, rstest};
const ONE_YOCTO: NearToken = NearToken::from_yoctonear(1);
async fn register_user(contract: &Contract, account_id: &AccountId) -> anyhow::Result<()> {
let res = contract
.call("storage_deposit")
.args_json((account_id, Option::<bool>::None))
.max_gas()
.deposit(near_sdk::env::storage_byte_cost().saturating_mul(125))
.transact()
.await?;
assert!(res.is_success());
Ok(())
}
// TODO: in order to be able to use a once fixture from rstest (which uses std::sync::OnceLock<T>)
// https://docs.rs/rstest/0.16.0/rstest/attr.fixture.html#once-fixture
// or std::sync::LazyLock<T, F> as in neardevhub-contract
// for [near_workspaces::compile_project](https://github.com/near/near-workspaces-rs/blob/main/workspaces/src/cargo/mod.rs#L8)
// `tokio::fs::read` has to be replaced with `std::fs::read`
// and the function made NON-async
fn build_contract(path: &str, contract_name: &str) -> Vec<u8> {
let artifact = cargo_near_build::build(cargo_near_build::BuildOpts {
manifest_path: Some(
cargo_near_build::camino::Utf8PathBuf::from_str(path).expect("camino PathBuf from str"),
),
..Default::default()
})
.expect(&format!("building `{}` contract for tests", contract_name));
let contract_wasm = std::fs::read(&artifact.path)
.map_err(|err| format!("accessing {} to read wasm contents: {}", artifact.path, err))
.expect("std::fs::read");
contract_wasm
}
#[fixture]
#[once]
fn fungible_contract_wasm() -> Vec<u8> {
build_contract("./ft/Cargo.toml", "fungible-token")
}
#[fixture]
#[once]
fn defi_contract_wasm() -> Vec<u8> {
build_contract("./test-contract-defi/Cargo.toml", "defi")
}
#[fixture]
fn initial_balance() -> U128 {
U128::from(NearToken::from_near(10000).as_yoctonear())
}
#[fixture]
async fn initialized_contracts(
initial_balance: U128,
fungible_contract_wasm: &Vec<u8>,
defi_contract_wasm: &Vec<u8>,
) -> anyhow::Result<(Contract, Account, Contract)> {
let worker = near_workspaces::sandbox().await?;
let ft_contract = worker.dev_deploy(fungible_contract_wasm).await?;
let res = ft_contract
.call("new_default_meta")
.args_json((ft_contract.id(), initial_balance))
.max_gas()
.transact()
.await?;
assert!(res.is_success());
let defi_contract = worker.dev_deploy(defi_contract_wasm).await?;
let res = defi_contract
.call("new")
.args_json((ft_contract.id(),))
.max_gas()
.transact()
.await?;
assert!(res.is_success());
let alice = ft_contract
.as_account()
.create_subaccount("alice")
.initial_balance(NearToken::from_near(10))
.transact()
.await?
.into_result()?;
register_user(&ft_contract, alice.id()).await?;
let res = ft_contract
.call("storage_deposit")
.args_json((alice.id(), Option::<bool>::None))
.deposit(near_sdk::env::storage_byte_cost().saturating_mul(125))
.max_gas()
.transact()
.await?;
assert!(res.is_success());
return Ok((ft_contract, alice, defi_contract));
}
#[rstest]
#[tokio::test]
async fn test_total_supply(
initial_balance: U128,
#[future] initialized_contracts: anyhow::Result<(Contract, Account, Contract)>,
) -> anyhow::Result<()> {
let (contract, _, _) =
initialized_contracts.await?;
let res = contract.call("ft_total_supply").view().await?;
assert_eq!(res.json::<U128>()?, initial_balance);
Ok(())
}
#[rstest]
#[tokio::test]
async fn test_storage_deposit_not_enough_deposit(
#[future] initialized_contracts: anyhow::Result<(Contract, Account, Contract)>,
) -> anyhow::Result<()> {
let (contract, _, _) =
initialized_contracts.await?;
let new_account = contract
.as_account()
.create_subaccount("new-account")
.initial_balance(NearToken::from_near(10))
.transact()
.await?
.into_result()?;
let new_account_balance_before_deposit = new_account.view_account().await?.balance;
let contract_balance_before_deposit = contract.view_account().await?.balance;
let minimal_deposit = near_sdk::env::storage_byte_cost().saturating_mul(125);
let res = new_account
.call(contract.id(), "storage_deposit")
.args(b"{}".to_vec())
.max_gas()
.deposit(minimal_deposit.saturating_sub(NearToken::from_yoctonear(1)))
.transact()
.await?;
assert!(res.is_failure());
let new_account_balance_diff = new_account_balance_before_deposit
.saturating_sub(new_account.view_account().await?.balance);
// new_account is charged the transaction fee, so it should loose some NEAR
assert!(new_account_balance_diff > NearToken::from_near(0));
assert!(new_account_balance_diff < NearToken::from_millinear(1));
let contract_balance_diff = contract
.view_account()
.await?
.balance
.saturating_sub(contract_balance_before_deposit);
// contract receives a gas rewards for the function call, so it should gain some NEAR
assert!(contract_balance_diff > NearToken::from_near(0));
assert!(contract_balance_diff < NearToken::from_yoctonear(30_000_000_000_000_000_000));
Ok(())
}
#[rstest]
#[tokio::test]
async fn test_storage_deposit_minimal_deposit(
#[future] initialized_contracts: anyhow::Result<(Contract, Account, Contract)>,
) -> anyhow::Result<()> {
let (contract, _, _) =
initialized_contracts.await?;
let new_account = contract
.as_account()
.create_subaccount("new-account")
.initial_balance(NearToken::from_near(10))
.transact()
.await?
.into_result()?;
let new_account_balance_before_deposit = new_account.view_account().await?.balance;
let contract_balance_before_deposit = contract.view_account().await?.balance;
let minimal_deposit = near_sdk::env::storage_byte_cost().saturating_mul(125);
new_account
.call(contract.id(), "storage_deposit")
.args(b"{}".to_vec())
.max_gas()
.deposit(minimal_deposit)
.transact()
.await?
.into_result()?;
let new_account_balance_diff = new_account_balance_before_deposit
.saturating_sub(new_account.view_account().await?.balance);
// new_account is charged the transaction fee, so it should loose a bit more than minimal_deposit
assert!(new_account_balance_diff > minimal_deposit);
assert!(
new_account_balance_diff < minimal_deposit.saturating_add(NearToken::from_millinear(1))
);
let contract_balance_diff = contract
.view_account()
.await?
.balance
.saturating_sub(contract_balance_before_deposit);
// contract receives a gas rewards for the function call, so the difference should be slightly more than minimal_deposit
assert!(contract_balance_diff > minimal_deposit);
// adjust the upper limit of the assertion to be more flexible for small variations in the gas reward received
assert!(
contract_balance_diff
< minimal_deposit.saturating_add(NearToken::from_yoctonear(50_000_000_000_000_000_000))
);
Ok(())
}
#[rstest]
#[tokio::test]
async fn test_storage_deposit_refunds_excessive_deposit(
#[future] initialized_contracts: anyhow::Result<(Contract, Account, Contract)>,
) -> anyhow::Result<()> {
let (contract, _, _) =
initialized_contracts.await?;
let minimal_deposit = near_sdk::env::storage_byte_cost().saturating_mul(125);
// Check the storage balance bounds to make sure we have the right minimal deposit
//
#[derive(near_sdk::serde::Serialize, near_sdk::serde::Deserialize)]
#[serde(crate = "near_sdk::serde")]
struct StorageBalanceBounds {
min: U128,
max: U128,
}
let storage_balance_bounds: StorageBalanceBounds = contract
.call("storage_balance_bounds")
.view()
.await?
.json()?;
assert_eq!(
storage_balance_bounds.min,
minimal_deposit.as_yoctonear().into()
);
assert_eq!(
storage_balance_bounds.max,
minimal_deposit.as_yoctonear().into()
);
// Check that a non-registered account does not have storage balance
//
#[derive(near_sdk::serde::Serialize, near_sdk::serde::Deserialize)]
#[serde(crate = "near_sdk::serde")]
struct StorageBalanceOf {
total: U128,
available: U128,
}
let storage_balance_bounds: Option<StorageBalanceOf> = contract
.call("storage_balance_of")
.args_json(near_sdk::serde_json::json!({"account_id": "non-registered-account"}))
.view()
.await?
.json()?;
assert!(storage_balance_bounds.is_none());
// Create a new account and deposit some NEAR to cover the storage
//
let new_account = contract
.as_account()
.create_subaccount("new-account")
.initial_balance(NearToken::from_near(10))
.transact()
.await?
.into_result()?;
let new_account_balance_before_deposit = new_account.view_account().await?.balance;
let contract_balance_before_deposit = contract.view_account().await?.balance;
new_account
.call(contract.id(), "storage_deposit")
.args(b"{}".to_vec())
.max_gas()
.deposit(NearToken::from_near(5))
.transact()
.await?
.into_result()?;
// The expected storage balance should be the minimal deposit,
// the balance of the account should be reduced by the deposit,
// and the contract should gain the deposit.
//
let storage_balance_bounds: StorageBalanceOf = contract
.call("storage_balance_of")
.args_json(near_sdk::serde_json::json!({"account_id": new_account.id()}))
.view()
.await?
.json()?;
assert_eq!(
storage_balance_bounds.total,
minimal_deposit.as_yoctonear().into()
);
assert_eq!(storage_balance_bounds.available, 0.into());
let new_account_balance_diff = new_account_balance_before_deposit
.saturating_sub(new_account.view_account().await?.balance);
// new_account is charged the transaction fee, so it should loose a bit more than minimal_deposit
assert!(new_account_balance_diff > minimal_deposit);
assert!(
new_account_balance_diff < minimal_deposit.saturating_add(NearToken::from_millinear(1))
);
let contract_balance_diff = contract
.view_account()
.await?
.balance
.saturating_sub(contract_balance_before_deposit);
// contract receives a gas rewards for the function call, so the difference should be slightly more than minimal_deposit
assert!(contract_balance_diff > minimal_deposit);
assert!(
contract_balance_diff
< minimal_deposit.saturating_add(NearToken::from_yoctonear(50_000_000_000_000_000_000))
);
Ok(())
}
#[rstest]
#[tokio::test]
async fn test_simple_transfer(
initial_balance: U128,
#[future] initialized_contracts: anyhow::Result<(Contract, Account, Contract)>,
) -> anyhow::Result<()> {
let transfer_amount = U128::from(NearToken::from_near(100).as_yoctonear());
let (contract, alice, _) =
initialized_contracts.await?;
let res = contract
.call("ft_transfer")
.args_json((alice.id(), transfer_amount, Option::<bool>::None))
.max_gas()
.deposit(ONE_YOCTO)
.transact()
.await?;
assert!(res.is_success());
let root_balance = contract
.call("ft_balance_of")
.args_json((contract.id(),))
.view()
.await?
.json::<U128>()?;
let alice_balance = contract
.call("ft_balance_of")
.args_json((alice.id(),))
.view()
.await?
.json::<U128>()?;
assert_eq!(initial_balance.0 - transfer_amount.0, root_balance.0);
assert_eq!(transfer_amount.0, alice_balance.0);
Ok(())
}
#[rstest]
#[tokio::test]
async fn test_close_account_empty_balance(
#[future] initialized_contracts: anyhow::Result<(Contract, Account, Contract)>,
) -> anyhow::Result<()> {
let (contract, alice, _) =
initialized_contracts.await?;
let res = alice
.call(contract.id(), "storage_unregister")
.args_json((Option::<bool>::None,))
.max_gas()
.deposit(ONE_YOCTO)
.transact()
.await?;
assert!(res.json::<bool>()?);
Ok(())
}
#[rstest]
#[tokio::test]
async fn test_close_account_non_empty_balance(
#[future] initialized_contracts: anyhow::Result<(Contract, Account, Contract)>,
) -> anyhow::Result<()> {
let (contract, _, _) =
initialized_contracts.await?;
let res = contract
.call("storage_unregister")
.args_json((Option::<bool>::None,))
.max_gas()
.deposit(ONE_YOCTO)
.transact()
.await;
assert!(format!("{:?}", res)
.contains("Can't unregister the account with the positive balance without force"));
let res = contract
.call("storage_unregister")
.args_json((Some(false),))
.max_gas()
.deposit(ONE_YOCTO)
.transact()
.await;
assert!(format!("{:?}", res)
.contains("Can't unregister the account with the positive balance without force"));
Ok(())
}
#[rstest]
#[tokio::test]
async fn simulate_close_account_force_non_empty_balance(
#[future] initialized_contracts: anyhow::Result<(Contract, Account, Contract)>,
) -> anyhow::Result<()> {
let (contract, _, _) =
initialized_contracts.await?;
let res = contract
.call("storage_unregister")
.args_json((Some(true),))
.max_gas()
.deposit(ONE_YOCTO)
.transact()
.await?;
assert!(res.is_success());
let res = contract.call("ft_total_supply").view().await?;
assert_eq!(res.json::<U128>()?.0, 0);
Ok(())
}
#[rstest]
#[tokio::test]
async fn simulate_transfer_call_with_burned_amount(
#[future] initialized_contracts: anyhow::Result<(Contract, Account, Contract)>,
) -> anyhow::Result<()> {
let transfer_amount = U128::from(NearToken::from_near(100).as_yoctonear());
let (contract, _, defi_contract) =
initialized_contracts.await?;
// defi contract must be registered as a FT account
register_user(&contract, defi_contract.id()).await?;
// root invests in defi by calling `ft_transfer_call`
let res = contract
.batch()
.call(
Function::new("ft_transfer_call")
.args_json((
defi_contract.id(),
transfer_amount,
Option::<String>::None,
"10",
))
.deposit(ONE_YOCTO)
.gas(near_sdk::Gas::from_tgas(150)),
)
.call(
Function::new("storage_unregister")
.args_json((Some(true),))
.deposit(ONE_YOCTO)
.gas(near_sdk::Gas::from_tgas(150)),
)
.transact()
.await?;
assert!(res.is_success());
let logs = res.logs();
let expected = format!("Account @{} burned {}", contract.id(), 10);
assert!(logs.len() >= 2);
assert!(logs.contains(&"The account of the sender was deleted"));
assert!(logs.contains(&(expected.as_str())));
match res.receipt_outcomes()[5].clone().into_result()? {
ValueOrReceiptId::Value(val) => {
let used_amount = val.json::<U128>()?;
assert_eq!(used_amount, transfer_amount);
}
_ => panic!("Unexpected receipt id"),
}
assert!(res.json::<bool>()?);
let res = contract.call("ft_total_supply").view().await?;
assert_eq!(res.json::<U128>()?.0, transfer_amount.0 - 10);
let defi_balance = contract
.call("ft_balance_of")
.args_json((defi_contract.id(),))
.view()
.await?
.json::<U128>()?;
assert_eq!(defi_balance.0, transfer_amount.0 - 10);
Ok(())
}
#[rstest]
#[tokio::test]
async fn simulate_transfer_call_with_immediate_return_and_no_refund(
initial_balance: U128,
#[future] initialized_contracts: anyhow::Result<(Contract, Account, Contract)>,
) -> anyhow::Result<()> {
let transfer_amount = U128::from(NearToken::from_near(100).as_yoctonear());
let (contract, _, defi_contract) =
initialized_contracts.await?;
// defi contract must be registered as a FT account
register_user(&contract, defi_contract.id()).await?;
// root invests in defi by calling `ft_transfer_call`
let res = contract
.call("ft_transfer_call")
.args_json((
defi_contract.id(),
transfer_amount,
Option::<String>::None,
"take-my-money",
))
.max_gas()
.deposit(ONE_YOCTO)
.transact()
.await?;
assert!(res.is_success());
let root_balance = contract
.call("ft_balance_of")
.args_json((contract.id(),))
.view()
.await?
.json::<U128>()?;
let defi_balance = contract
.call("ft_balance_of")
.args_json((defi_contract.id(),))
.view()
.await?
.json::<U128>()?;
assert_eq!(initial_balance.0 - transfer_amount.0, root_balance.0);
assert_eq!(transfer_amount.0, defi_balance.0);
Ok(())
}
#[rstest]
#[tokio::test]
async fn simulate_transfer_call_when_called_contract_not_registered_with_ft(
initial_balance: U128,
#[future] initialized_contracts: anyhow::Result<(Contract, Account, Contract)>,
) -> anyhow::Result<()> {
let transfer_amount = U128::from(NearToken::from_near(100).as_yoctonear());
let (contract, _, defi_contract) =
initialized_contracts.await?;
// call fails because DEFI contract is not registered as FT user
let res = contract
.call("ft_transfer_call")
.args_json((
defi_contract.id(),
transfer_amount,
Option::<String>::None,
"take-my-money",
))
.max_gas()
.deposit(ONE_YOCTO)
.transact()
.await?;
assert!(res.is_failure());
// balances remain unchanged
let root_balance = contract
.call("ft_balance_of")
.args_json((contract.id(),))
.view()
.await?
.json::<U128>()?;
let defi_balance = contract
.call("ft_balance_of")
.args_json((defi_contract.id(),))
.view()
.await?
.json::<U128>()?;
assert_eq!(initial_balance.0, root_balance.0);
assert_eq!(0, defi_balance.0);
Ok(())
}
#[rstest]
#[tokio::test]
async fn simulate_transfer_call_with_promise_and_refund(
initial_balance: U128,
#[future] initialized_contracts: anyhow::Result<(Contract, Account, Contract)>,
) -> anyhow::Result<()> {
let refund_amount = U128::from(NearToken::from_near(50).as_yoctonear());
let transfer_amount = U128::from(NearToken::from_near(100).as_yoctonear());
let (contract, _, defi_contract) =
initialized_contracts.await?;
// defi contract must be registered as a FT account
register_user(&contract, defi_contract.id()).await?;
let res = contract
.call("ft_transfer_call")
.args_json((
defi_contract.id(),
transfer_amount,
Option::<String>::None,
refund_amount.0.to_string(),
))
.max_gas()
.deposit(ONE_YOCTO)
.transact()
.await?;
assert!(res.is_success());
let root_balance = contract
.call("ft_balance_of")
.args_json((contract.id(),))
.view()
.await?
.json::<U128>()?;
let defi_balance = contract
.call("ft_balance_of")
.args_json((defi_contract.id(),))
.view()
.await?
.json::<U128>()?;
assert_eq!(
initial_balance.0 - transfer_amount.0 + refund_amount.0,
root_balance.0
);
assert_eq!(transfer_amount.0 - refund_amount.0, defi_balance.0);
Ok(())
}
#[rstest]
#[tokio::test]
async fn simulate_transfer_call_promise_panics_for_a_full_refund(
initial_balance: U128,
#[future] initialized_contracts: anyhow::Result<(Contract, Account, Contract)>,
) -> anyhow::Result<()> {
let transfer_amount = U128::from(NearToken::from_near(100).as_yoctonear());
let (contract, _, defi_contract) =
initialized_contracts.await?;
// defi contract must be registered as a FT account
register_user(&contract, defi_contract.id()).await?;
// root invests in defi by calling `ft_transfer_call`
let res = contract
.call("ft_transfer_call")
.args_json((
defi_contract.id(),
transfer_amount,
Option::<String>::None,
"no parsey as integer big panic oh no".to_string(),
))
.max_gas()
.deposit(ONE_YOCTO)
.transact()
.await?;
assert!(res.is_success());
let promise_failures = res.receipt_failures();
assert_eq!(promise_failures.len(), 1);
let failure = promise_failures[0].clone().into_result();
if let Err(err) = failure {
assert!(format!("{:?}", err).contains("ParseIntError"));
} else {
unreachable!();
}
// balances remain unchanged
let root_balance = contract
.call("ft_balance_of")
.args_json((contract.id(),))
.view()
.await?
.json::<U128>()?;
let defi_balance = contract
.call("ft_balance_of")
.args_json((defi_contract.id(),))
.view()
.await?
.json::<U128>()?;
assert_eq!(initial_balance, root_balance);
assert_eq!(0, defi_balance.0);
Ok(())
}