forked from anza-xyz/move
-
Notifications
You must be signed in to change notification settings - Fork 0
/
BasicCoin.move
69 lines (56 loc) · 2.48 KB
/
BasicCoin.move
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
/// This module defines a minimal Coin and Balance.
module NamedAddr::BasicCoin {
use std::signer;
/// Address of the owner of this module
const MODULE_OWNER: address = @NamedAddr;
/// Error codes
const ENOT_MODULE_OWNER: u64 = 0;
const EINSUFFICIENT_BALANCE: u64 = 1;
const EALREADY_HAS_BALANCE: u64 = 2;
struct Coin has store {
value: u64
}
/// Struct representing the balance of each address.
struct Balance has key {
coin: Coin
}
/// Publish an empty balance resource under `account`'s address. This function must be called before
/// minting or transferring to the account.
public fun publish_balance(account: &signer) {
// TODO: add an assert to check that `account` doesn't already have a `Balance` resource.
let empty_coin = Coin { value: 0 };
move_to(account, Balance { coin: empty_coin });
}
/// Initialize this module.
public fun mint(module_owner: &signer, mint_addr: address, amount: u64) {
// Only the owner of the module can initialize this module
assert!(signer::address_of(module_owner) == MODULE_OWNER, ENOT_MODULE_OWNER);
// Deposit `amount` of tokens to `mint_addr`'s balance
deposit(mint_addr, Coin { value: amount });
}
/// Returns the balance of `owner`.
public fun balance_of(owner: address): u64 acquires Balance {
borrow_global<Balance>(owner).coin.value
}
/// Transfers `amount` of tokens from `from` to `to`.
public fun transfer(from: &signer, to: address, amount: u64) acquires Balance {
let check = withdraw(signer::address_of(from), amount);
deposit(to, check);
}
/// Withdraw `amount` number of tokens from the balance under `addr`.
fun withdraw(addr: address, amount: u64) : Coin acquires Balance {
let balance = balance_of(addr);
// balance must be greater than the withdraw amount
assert!(balance >= amount, EINSUFFICIENT_BALANCE);
let balance_ref = &mut borrow_global_mut<Balance>(addr).coin.value;
*balance_ref = balance - amount;
Coin { value: amount }
}
/// Deposit `amount` number of tokens to the balance under `addr`.
fun deposit(_addr: address, check: Coin) {
// TODO: follow the implementation of `withdraw` and implement me!
let Coin { value: _amount } = check; // unpacks the check
// Get a mutable reference of addr's balance's coin value
// Increment the value by `amount`
}
}