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
//! ERC20 token standard implementation.
use crate::erc20::errors::Error;
use crate::erc20::events::*;
use odra::prelude::*;
use odra::{casper_types::U256, Address, Mapping, Var};

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

#[odra::module]
impl Erc20 {
    /// Initializes the contract with the given metadata and initial supply.
    pub fn init(
        &mut self,
        symbol: String,
        name: String,
        decimals: u8,
        initial_supply: Option<U256>
    ) {
        let caller = self.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() {
                self.env().emit_event(Transfer {
                    from: None,
                    to: Some(caller),
                    amount: initial_supply
                });
            }
        }
    }

    /// Transfers tokens from the caller to the recipient.
    pub fn transfer(&mut self, recipient: &Address, amount: &U256) {
        let caller = self.env().caller();
        self.raw_transfer(&caller, recipient, amount);
    }

    /// Transfers tokens from the owner to the recipient using the spender's allowance.
    pub fn transfer_from(&mut self, owner: &Address, recipient: &Address, amount: &U256) {
        let spender = self.env().caller();

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

    /// Approves the spender to spend the given amount of tokens on behalf of the caller.
    pub fn approve(&mut self, spender: &Address, amount: &U256) {
        let owner = self.env().caller();

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

    /// Returns the name of the token.
    pub fn name(&self) -> String {
        self.name.get_or_revert_with(Error::NameNotSet)
    }

    /// Returns the symbol of the token.
    pub fn symbol(&self) -> String {
        self.symbol.get_or_revert_with(Error::SymbolNotSet)
    }

    /// Returns the number of decimals the token uses.
    pub fn decimals(&self) -> u8 {
        self.decimals.get_or_revert_with(Error::DecimalsNotSet)
    }

    /// Returns the total supply of the token.
    pub fn total_supply(&self) -> U256 {
        self.total_supply.get_or_default()
    }

    /// Returns the balance of the given address.
    pub fn balance_of(&self, address: &Address) -> U256 {
        self.balances.get_or_default(address)
    }

    /// Returns the amount of tokens the owner has allowed the spender to spend.
    pub fn allowance(&self, owner: &Address, spender: &Address) -> U256 {
        self.allowances.get_or_default(&(*owner, *spender))
    }

    /// Mints new tokens and assigns them to the given address.
    pub fn mint(&mut self, address: &Address, amount: &U256) {
        self.total_supply.add(*amount);
        self.balances.add(address, *amount);

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

    /// Burns the given amount of tokens from the given address.
    pub fn burn(&mut self, address: &Address, amount: &U256) {
        if self.balance_of(address) < *amount {
            self.env().revert(Error::InsufficientBalance);
        }
        self.total_supply.subtract(*amount);
        self.balances.subtract(address, *amount);

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

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

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

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

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

        self.env().emit_event(Approval {
            owner: *owner,
            spender: *spender,
            value: allowance - *amount
        });
    }
}

/// ERC20 Events
pub mod events {
    use odra::casper_event_standard;
    use odra::{casper_types::U256, Address};

    /// Transfer event
    #[odra::event]
    pub struct Transfer {
        /// Sender of the tokens.
        pub from: Option<Address>,
        /// Recipient of the tokens.
        pub to: Option<Address>,
        /// Amount of tokens transferred.
        pub amount: U256
    }

    /// Approval event
    #[odra::event]
    pub struct Approval {
        /// Owner of the tokens.
        pub owner: Address,
        /// Spender of the tokens.
        pub spender: Address,
        /// Amount of tokens approved.
        pub value: U256
    }
}

/// ERC20 Errors
pub mod errors {
    /// ERC20 errors
    #[odra::odra_error]
    pub enum Error {
        /// Insufficient balance
        InsufficientBalance = 30_000,
        /// Insufficient allowance
        InsufficientAllowance = 30_001,
        /// Name not set
        NameNotSet = 30_002,
        /// Symbol not set
        SymbolNotSet = 30_003,
        /// Decimals not set
        DecimalsNotSet = 30_004
    }
}

#[cfg(test)]
mod tests {
    use super::{
        errors::Error,
        events::{Approval, Transfer},
        Erc20HostRef, Erc20InitArgs
    };
    use odra::{
        casper_types::U256,
        host::{Deployer, HostEnv, HostRef},
        prelude::*
    };

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

    fn setup() -> (HostEnv, Erc20HostRef) {
        let env = odra_test::env();
        (
            env.clone(),
            Erc20HostRef::deploy(
                &env,
                Erc20InitArgs {
                    symbol: SYMBOL.to_string(),
                    name: NAME.to_string(),
                    decimals: DECIMALS,
                    initial_supply: Some(INITIAL_SUPPLY.into())
                }
            )
        )
    }

    #[test]
    fn initialization() {
        // When deploy a contract with the initial supply.
        let (env, 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!(env.emitted_event(
            erc20.address(),
            &Transfer {
                from: None,
                to: Some(env.get_account(0)),
                amount: INITIAL_SUPPLY.into()
            }
        ));
    }

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

        // When transfer tokens to a recipient.
        let sender = env.get_account(0);
        let recipient = 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!(env.emitted_event(
            erc20.address(),
            &Transfer {
                from: Some(sender),
                to: Some(recipient),
                amount
            }
        ));
    }

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

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

        // Then an error occurs.
        assert!(erc20.try_transfer(&recipient, &amount).is_err());
    }

    #[test]
    fn transfer_from_and_approval_work() {
        let (env, mut erc20) = setup();

        let (owner, recipient, spender) =
            (env.get_account(0), env.get_account(1), 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!(env.emitted_event(
            erc20.address(),
            &Approval {
                owner,
                spender,
                value: approved_amount
            }
        ));

        // Spender transfers tokens from Owner to Recipient.
        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!(env.emitted_event(
            erc20.address(),
            &Approval {
                owner,
                spender,
                value: approved_amount - transfer_amount
            }
        ));
        assert!(env.emitted_event(
            erc20.address(),
            &Transfer {
                from: Some(owner),
                to: Some(recipient),
                amount: transfer_amount
            }
        ));
    }

    #[test]
    fn transfer_from_error() {
        // Given a new instance.
        let (env, mut erc20) = setup();

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

        // Then transfer fails.
        assert_eq!(
            erc20.try_transfer_from(&owner, &recipient, &amount),
            Err(Error::InsufficientAllowance.into())
        );
    }
}