-
Notifications
You must be signed in to change notification settings - Fork 0
/
gingerkiwi
78 lines (69 loc) · 1.94 KB
/
gingerkiwi
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
use ethers_core::types::{Address, U256};
use serde::{Deserialize, Serialize};
use structopt::StructOpt;
#[derive(Debug, StructOpt)]
#[structopt(name = "KIWI")]
struct Opt {
#[structopt(long)]
pub sender: Address,
}
#[derive(Serialize, Deserialize, Debug)]
struct Token {
name: String,
symbol: String,
total_supply: U256,
decimals: u8,
balances: Vec<(Address, U256)>,
}
impl Token {
fn new(name: &str, symbol: &str, total_supply: U256, decimals: u8) -> Self {
Self {
name: name.to_owned(),
symbol: symbol.to_owned(),
total_supply,
decimals,
balances: vec![],
}
}
fn balance_of(&self, owner: &Address) -> U256 {
self.balances
.iter()
.find(|(a, _)| a == owner)
.map(|(_, b)| *b)
.unwrap_or_default()
}
fn transfer(&mut self, from: &Address, to: &Address, value: U256) -> bool {
let from_balance = self.balance_of(from);
if from_balance < value {
return false;
}
let to_balance = self.balance_of(to);
self.balances = self
.balances
.iter()
.map(|(a, b)| {
if a == from {
(*a, b - value)
} else if a == to {
(*a, b + value)
} else {
(*a, *b)
}
})
.collect();
true
}
}
fn main() {
let opt = Opt::from_args();
let mut token = Token::new("Ginger Cat", "KIWI", 100_000_000.into(), 18);
let sender = opt.sender;
let recipient = Address::random();
let transfer_amount = 10_000.into();
let success = token.transfer(&sender, &recipient, transfer_amount);
if success {
println!("Successfully transferred {} KIWI from {} to {}", transfer_amount, sender, recipient);
} else {
println!("Transfer failed");
}
}