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
use odra::prelude::string::String;
use odra::{
    contract_env,
    types::{event::OdraEvent, Address, U256},
    Mapping, UnwrapOrRevert, Variable
};

use self::{
    errors::Error,
    events::{Approval, Transfer}
};

#[odra::module(events = [Approval, Transfer])]
pub struct Erc20 {
    decimals: Variable<u8>,
    symbol: Variable<String>,
    name: Variable<String>,
    total_supply: Variable<U256>,
    balances: Mapping<Address, U256>,
    allowances: Mapping<Address, Mapping<Address, U256>>
}

#[odra::module]
impl Erc20 {
    #[odra(init)]
    pub fn init(
        &mut self,
        symbol: String,
        name: String,
        decimals: u8,
        initial_supply: &Option<U256>
    ) {
        let caller = contract_env::caller();

        self.symbol.set(symbol);
        self.name.set(name);
        self.decimals.set(decimals);

        if let Some(initial_supply) = *initial_supply {
            self.total_supply.set(initial_supply);
            self.balances.set(&caller, initial_supply);

            if !initial_supply.is_zero() {
                Transfer {
                    from: None,
                    to: Some(caller),
                    amount: initial_supply
                }
                .emit();
            }
        }
    }

    pub fn transfer(&mut self, recipient: &Address, amount: &U256) {
        let caller = contract_env::caller();
        self.raw_transfer(&caller, recipient, amount);
    }

    pub fn transfer_from(&mut self, owner: &Address, recipient: &Address, amount: &U256) {
        let spender = contract_env::caller();

        self.spend_allowance(owner, &spender, amount);
        self.raw_transfer(owner, recipient, amount);
    }

    pub fn approve(&mut self, spender: &Address, amount: &U256) {
        let owner = contract_env::caller();

        self.allowances.get_instance(&owner).set(spender, *amount);
        Approval {
            owner,
            spender: *spender,
            value: *amount
        }
        .emit();
    }

    pub fn name(&self) -> String {
        self.name.get().unwrap_or_revert_with(Error::NameNotSet)
    }

    pub fn symbol(&self) -> String {
        self.symbol.get().unwrap_or_revert_with(Error::SymbolNotSet)
    }

    pub fn decimals(&self) -> u8 {
        self.decimals
            .get()
            .unwrap_or_revert_with(Error::DecimalsNotSet)
    }

    pub fn total_supply(&self) -> U256 {
        self.total_supply.get_or_default()
    }

    pub fn balance_of(&self, address: &Address) -> U256 {
        self.balances.get_or_default(address)
    }

    pub fn allowance(&self, owner: &Address, spender: &Address) -> U256 {
        self.allowances.get_instance(owner).get_or_default(spender)
    }

    pub fn mint(&mut self, address: &Address, amount: &U256) {
        self.total_supply.add(*amount);
        self.balances.add(address, *amount);

        Transfer {
            from: None,
            to: Some(*address),
            amount: *amount
        }
        .emit();
    }

    pub fn burn(&mut self, address: &Address, amount: &U256) {
        if self.balance_of(address) < *amount {
            contract_env::revert(Error::InsufficientBalance);
        }
        self.total_supply.subtract(*amount);
        self.balances.subtract(address, *amount);

        Transfer {
            from: Some(*address),
            to: None,
            amount: *amount
        }
        .emit();
    }
}

impl Erc20 {
    fn raw_transfer(&mut self, owner: &Address, recipient: &Address, amount: &U256) {
        if *amount > self.balances.get_or_default(owner) {
            contract_env::revert(Error::InsufficientBalance)
        }

        self.balances.subtract(owner, *amount);
        self.balances.add(recipient, *amount);

        Transfer {
            from: Some(*owner),
            to: Some(*recipient),
            amount: *amount
        }
        .emit();
    }

    fn spend_allowance(&mut self, owner: &Address, spender: &Address, amount: &U256) {
        let allowance = self.allowances.get_instance(owner).get_or_default(spender);
        if allowance < *amount {
            contract_env::revert(Error::InsufficientAllowance)
        }
        self.allowances
            .get_instance(owner)
            .subtract(spender, *amount);
        Approval {
            owner: *owner,
            spender: *spender,
            value: allowance - *amount
        }
        .emit();
    }
}

pub mod events {
    use odra::types::{casper_types::U256, Address};
    use odra::Event;

    #[derive(Event, Eq, PartialEq, Debug)]
    pub struct Transfer {
        pub from: Option<Address>,
        pub to: Option<Address>,
        pub amount: U256
    }

    #[derive(Event, Eq, PartialEq, Debug)]
    pub struct Approval {
        pub owner: Address,
        pub spender: Address,
        pub value: U256
    }
}

pub mod errors {
    use odra::execution_error;

    execution_error! {
        pub enum Error {
            InsufficientBalance => 30_000,
            InsufficientAllowance => 30_001,
            NameNotSet => 30_002,
            SymbolNotSet => 30_003,
            DecimalsNotSet => 30_004,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::{
        errors::Error,
        events::{Approval, Transfer},
        Erc20Deployer, Erc20Ref
    };
    use odra::prelude::string::ToString;
    use odra::{assert_events, test_env, types::casper_types::U256};

    const NAME: &str = "Plascoin";
    const SYMBOL: &str = "PLS";
    const DECIMALS: u8 = 10;
    const INITIAL_SUPPLY: u32 = 10_000;

    fn setup() -> Erc20Ref {
        Erc20Deployer::init(
            SYMBOL.to_string(),
            NAME.to_string(),
            DECIMALS,
            &Some(INITIAL_SUPPLY.into())
        )
    }

    #[test]
    fn initialization() {
        // When deploy a contract with the initial supply.
        let erc20 = setup();

        // Then the contract has the metadata set.
        assert_eq!(erc20.symbol(), SYMBOL.to_string());
        assert_eq!(erc20.name(), NAME.to_string());
        assert_eq!(erc20.decimals(), DECIMALS);

        // Then the total supply is updated.
        assert_eq!(erc20.total_supply(), INITIAL_SUPPLY.into());

        // Then a Transfer event was emitted.
        assert_events!(
            erc20,
            Transfer {
                from: None,
                to: Some(test_env::get_account(0)),
                amount: INITIAL_SUPPLY.into()
            }
        );
    }

    #[test]
    fn transfer_works() {
        // Given a new contract.
        let mut erc20 = setup();

        // When transfer tokens to a recipient.
        let sender = test_env::get_account(0);
        let recipient = test_env::get_account(1);
        let amount = 1_000.into();
        erc20.transfer(&recipient, &amount);

        // Then the sender balance is deducted.
        assert_eq!(
            erc20.balance_of(&sender),
            U256::from(INITIAL_SUPPLY) - amount
        );

        // Then the recipient balance is updated.
        assert_eq!(erc20.balance_of(&recipient), amount);

        // Then Transfer event was emitted.
        assert_events!(
            erc20,
            Transfer {
                from: Some(sender),
                to: Some(recipient),
                amount
            }
        );
    }

    #[test]
    fn transfer_error() {
        test_env::assert_exception(Error::InsufficientBalance, || {
            // Given a new contract.
            let mut erc20 = setup();

            // When the transfer amount exceeds the sender balance.
            let recipient = test_env::get_account(1);
            let amount = U256::from(INITIAL_SUPPLY) + U256::one();

            // Then an error occurs.
            erc20.transfer(&recipient, &amount)
        });
    }

    #[test]
    fn transfer_from_and_approval_work() {
        let mut erc20 = setup();
        let (owner, recipient, spender) = (
            test_env::get_account(0),
            test_env::get_account(1),
            test_env::get_account(2)
        );
        let approved_amount = 3_000.into();
        let transfer_amount = 1_000.into();

        assert_eq!(erc20.balance_of(&owner), U256::from(INITIAL_SUPPLY));

        // Owner approves Spender.
        erc20.approve(&spender, &approved_amount);

        // Allowance was recorded.
        assert_eq!(erc20.allowance(&owner, &spender), approved_amount);
        assert_events!(
            erc20,
            Approval {
                owner,
                spender,
                value: approved_amount
            }
        );

        // Spender transfers tokens from Owner to Recipient.
        test_env::set_caller(spender);
        erc20.transfer_from(&owner, &recipient, &transfer_amount);

        // Tokens are transferred and allowance decremented.
        assert_eq!(
            erc20.balance_of(&owner),
            U256::from(INITIAL_SUPPLY) - transfer_amount
        );
        assert_eq!(erc20.balance_of(&recipient), transfer_amount);
        assert_events!(
            erc20,
            Approval {
                owner,
                spender,
                value: approved_amount - transfer_amount
            },
            Transfer {
                from: Some(owner),
                to: Some(recipient),
                amount: transfer_amount
            }
        );
    }

    #[test]
    fn transfer_from_error() {
        test_env::assert_exception(Error::InsufficientAllowance, || {
            // Given a new instance.
            let mut erc20 = setup();

            // When the spender's allowance is zero.
            let (owner, spender, recipient) = (
                test_env::get_account(0),
                test_env::get_account(1),
                test_env::get_account(2)
            );
            let amount = 1_000.into();
            test_env::set_caller(spender);

            // Then transfer fails.
            erc20.transfer_from(&owner, &recipient, &amount)
        });
    }
}