lib.rs 9.78 KB
Newer Older
Ricardo Rius's avatar
Ricardo Rius committed
1
// Copyright 2019-2020 Parity Technologies (UK) Ltd.
2
//
3 4 5
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
6
//
7
//     http://www.apache.org/licenses/LICENSE-2.0
8
//
9 10 11 12 13
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
14 15 16

#![cfg_attr(not(feature = "std"), no_std)]

17
use ink_lang as ink;
18 19 20

#[ink::contract(version = "0.1.0")]
mod erc20 {
21 22
    use ink_core::storage;

23 24 25 26 27 28 29 30
    #[ink(storage)]
    struct Erc20 {
        total_supply: storage::Value<Balance>,
        balances: storage::HashMap<AccountId, Balance>,
        allowances: storage::HashMap<(AccountId, AccountId), Balance>,
    }

    #[ink(event)]
31
    struct Transfer {
32 33 34 35 36
        #[ink(topic)]
        from: Option<AccountId>,
        #[ink(topic)]
        to: Option<AccountId>,
        #[ink(topic)]
37
        value: Balance,
38 39 40
    }

    #[ink(event)]
41
    struct Approval {
42 43 44 45 46
        #[ink(topic)]
        owner: AccountId,
        #[ink(topic)]
        spender: AccountId,
        #[ink(topic)]
47
        value: Balance,
48 49 50 51 52 53 54 55
    }

    impl Erc20 {
        #[ink(constructor)]
        fn new(&mut self, initial_supply: Balance) {
            let caller = self.env().caller();
            self.total_supply.set(initial_supply);
            self.balances.insert(caller, initial_supply);
56
            self.env().emit_event(Transfer {
57 58
                from: None,
                to: Some(caller),
59
                value: initial_supply,
60 61 62 63 64 65 66 67 68 69 70 71 72 73
            });
        }

        #[ink(message)]
        fn total_supply(&self) -> Balance {
            *self.total_supply
        }

        #[ink(message)]
        fn balance_of(&self, owner: AccountId) -> Balance {
            self.balance_of_or_zero(&owner)
        }

        #[ink(message)]
74 75
        fn allowance(&self, owner: AccountId, spender: AccountId) -> Balance {
            self.allowance_of_or_zero(&owner, &spender)
76 77 78
        }

        #[ink(message)]
79
        fn transfer(&mut self, to: AccountId, value: Balance) -> bool {
80
            let from = self.env().caller();
81
            self.transfer_from_to(from, to, value)
82 83 84
        }

        #[ink(message)]
85
        fn approve(&mut self, spender: AccountId, value: Balance) -> bool {
86
            let owner = self.env().caller();
87 88
            self.allowances.insert((owner, spender), value);
            self.env().emit_event(Approval {
89 90
                owner,
                spender,
91
                value,
92 93 94 95 96 97 98 99 100
            });
            true
        }

        #[ink(message)]
        fn transfer_from(
            &mut self,
            from: AccountId,
            to: AccountId,
101
            value: Balance,
102 103 104
        ) -> bool {
            let caller = self.env().caller();
            let allowance = self.allowance_of_or_zero(&from, &caller);
105
            if allowance < value {
Hero Bird's avatar
Hero Bird committed
106
                return false
107
            }
108 109
            self.allowances.insert((from, caller), allowance - value);
            self.transfer_from_to(from, to, value)
110 111 112 113 114 115
        }

        fn transfer_from_to(
            &mut self,
            from: AccountId,
            to: AccountId,
116
            value: Balance,
117 118
        ) -> bool {
            let from_balance = self.balance_of_or_zero(&from);
119
            if from_balance < value {
Hero Bird's avatar
Hero Bird committed
120
                return false
121
            }
122
            self.balances.insert(from.clone(), from_balance - value);
123
            let to_balance = self.balance_of_or_zero(&to);
124 125
            self.balances.insert(to.clone(), to_balance + value);
            self.env().emit_event(Transfer {
126 127
                from: Some(from),
                to: Some(to),
128
                value,
129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144
            });
            true
        }

        fn balance_of_or_zero(&self, owner: &AccountId) -> Balance {
            *self.balances.get(owner).unwrap_or(&0)
        }

        fn allowance_of_or_zero(
            &self,
            owner: &AccountId,
            spender: &AccountId,
        ) -> Balance {
            *self.allowances.get(&(*owner, *spender)).unwrap_or(&0)
        }
    }
Ricardo Rius's avatar
Ricardo Rius committed
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

    /// Unit tests.
    #[cfg(test)]
    mod tests {
        /// Imports all the definitions from the outer scope so we can use them here.
        use super::*;
        use ink_core::env;

        /// The default constructor does its job.
        #[test]
        fn new_works() {
            // Constructor works.
            let _erc20 = Erc20::new(100);
            // Transfer event triggered during initial contruction.
            assert_eq!(1, env::test::recorded_events().count());
        }

        /// The total supply was applied.
        #[test]
        fn total_supply_works() {
            // Constructor works.
            let erc20 = Erc20::new(100);
            // Transfer event triggered during initial contruction.
            assert_eq!(env::test::recorded_events().count(), 1);
            // Get the token total supply.
            assert_eq!(erc20.total_supply(), 100);
        }

        /// Get the actual balance of an account.
        #[test]
        fn balance_of_works() {
            // Constructor works
            let erc20 = Erc20::new(100);
            // Transfer event triggered during initial contruction
            assert_eq!(env::test::recorded_events().count(), 1);
            let accounts = env::test::default_accounts::<env::DefaultEnvTypes>()
                .expect("Cannot get accounts");
            // Alice owns all the tokens on deployment
            assert_eq!(erc20.balance_of(accounts.alice), 100);
            // Bob does not owns tokens
            assert_eq!(erc20.balance_of(accounts.bob), 0);
        }

        #[test]
        fn transfer_works() {
            // Constructor works.
            let mut erc20 = Erc20::new(100);
            // Transfer event triggered during initial contruction.
            assert_eq!(1, env::test::recorded_events().count());
            let accounts = env::test::default_accounts::<env::DefaultEnvTypes>()
                .expect("Cannot get accounts");

            assert_eq!(erc20.balance_of(accounts.bob), 0);
            // Alice transfers 10 tokens to Bob.
            assert_eq!(erc20.transfer(accounts.bob, 10), true);
            // The second Transfer event takes place.
            assert_eq!(2, env::test::recorded_events().count());
            // Bob owns 10 tokens.
            assert_eq!(erc20.balance_of(accounts.bob), 10);
        }

        #[test]
        fn invalid_transfer_should_fail() {
            // Constructor works.
            let mut erc20 = Erc20::new(100);
            // Transfer event triggered during initial contruction.
            assert_eq!(env::test::recorded_events().count(), 1);
            let accounts = env::test::default_accounts::<env::DefaultEnvTypes>()
                .expect("Cannot get accounts");

            assert_eq!(erc20.balance_of(accounts.bob), 0);
            // Get contract address.
            let callee =
                env::account_id::<env::DefaultEnvTypes>().unwrap_or([0x0; 32].into());
            // Create call
            let mut data =
                env::call::CallData::new(env::call::Selector::from_str("balance_of"));
            data.push_arg(&accounts.bob);
            // Push the new execution context to set Bob as caller
            assert_eq!(
                env::test::push_execution_context::<env::DefaultEnvTypes>(
                    accounts.bob,
                    callee,
                    1000000,
                    1000000,
                    data
                ),
                ()
            );

            // Bob fails to transfers 10 tokens to Eve.
            assert_eq!(erc20.transfer(accounts.eve, 10), false);
            // Alice owns all the tokens.
            assert_eq!(erc20.balance_of(accounts.alice), 100);
            assert_eq!(erc20.balance_of(accounts.bob), 0);
            assert_eq!(erc20.balance_of(accounts.eve), 0);
        }

        #[test]
        fn transfer_from_works() {
            // Constructor works.
            let mut erc20 = Erc20::new(100);
            // Transfer event triggered during initial contruction.
            assert_eq!(env::test::recorded_events().count(), 1);
            let accounts = env::test::default_accounts::<env::DefaultEnvTypes>()
                .expect("Cannot get accounts");

            // Bob fails to transfer tokens owned by Alice.
            assert_eq!(erc20.transfer_from(accounts.alice, accounts.eve, 10), false);
            // Alice approves Bob for token transfers on her behalf.
            assert_eq!(erc20.approve(accounts.bob, 10), true);

            // The approve event takes place.
            assert_eq!(env::test::recorded_events().count(), 2);

            // Get contract address.
            let callee =
                env::account_id::<env::DefaultEnvTypes>().unwrap_or([0x0; 32].into());
            // Create call.
            let mut data =
                env::call::CallData::new(env::call::Selector::from_str("balance_of"));
            data.push_arg(&accounts.bob);
            // Push the new execution context to set Bob as caller.
            assert_eq!(
                env::test::push_execution_context::<env::DefaultEnvTypes>(
                    accounts.bob,
                    callee,
                    1000000,
                    1000000,
                    data
                ),
                ()
            );

            // Bob transfers tokens from Alice to Eve.
            assert_eq!(erc20.transfer_from(accounts.alice, accounts.eve, 10), true);
            // The third event takes place.
            assert_eq!(env::test::recorded_events().count(), 3);
            // Eve owns tokens.
            assert_eq!(erc20.balance_of(accounts.eve), 10);
        }
    }
287
}