lib.rs 11.4 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
//! A smart contract which demonstrates behavior of the `self.env().transfer()` function.
//! It transfers some of it's balance to the caller.

#![cfg_attr(not(feature = "std"), no_std)]
#![allow(clippy::new_without_default)]

use ink_lang as ink;

#[ink::contract]
pub mod give_me {
    /// No storage is needed for this simple contract.
    #[ink(storage)]
    pub struct GiveMe {}

    /// The error types.
16
    #[derive(Debug, PartialEq, Eq, scale::Encode, scale::Decode)]
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
    #[cfg_attr(feature = "std", derive(scale_info::TypeInfo))]
    pub enum Error {
        /// Returned if the transfer failed.
        TransferFailed,
        /// Insufficient funds to execute transfer.
        InsufficientFunds,
        /// Transfer failed because it would have brought the contract's
        /// balance below the subsistence threshold.
        /// This is necessary to keep enough funds in the contract to
        /// allow for a tombstone to be created.
        BelowSubsistenceThreshold,
    }

    impl GiveMe {
        /// Creates a new instance of this contract.
        #[ink(constructor)]
        pub fn new() -> Self {
            Self {}
        }

        /// Transfers `value` amount of tokens to the caller.
        ///
        /// # Errors
        ///
41
42
43
44
        /// - Panics in case the requested transfer exceeds the contract balance.
        /// - Panics in case the requested transfer would have brought the
        ///   contract balance below the subsistence threshold.
        /// - Panics in case the transfer failed for another reason.
45
        #[ink(message)]
46
        pub fn give_me(&mut self, value: Balance) {
47
48
            ink_env::debug_println!("requested value: {}", value);
            ink_env::debug_println!("contract balance: {}", self.env().balance());
49
50
51
52
53
54
55
56
57
58
59
60

            assert!(value <= self.env().balance(), "insufficient funds!");

            match self.env().transfer(self.env().caller(), value) {
                Err(ink_env::Error::BelowSubsistenceThreshold) => {
                    panic!(
                        "requested transfer would have brought contract\
                        below subsistence threshold!"
                    )
                }
                Err(_) => panic!("transfer failed!"),
                Ok(_) => {}
61
62
            }
        }
63

64
65
66
        /// Asserts that the token amount sent as payment with this call
        /// is exactly `10`. This method will fail otherwise, and the
        /// transaction would then be reverted.
67
68
69
70
71
        ///
        /// # Note
        ///
        /// The method needs to be annotated with `payable`; only then it is
        /// allowed to receive value as part of the call.
72
        #[ink(message, payable, selector = 0xCAFEBABE)]
73
        pub fn was_it_ten(&self) {
74
            ink_env::debug_println!(
75
76
77
78
79
80
81
                "received payment: {}",
                self.env().transferred_balance()
            );
            assert!(
                self.env().transferred_balance() == 10,
                "payment was not ten"
            );
82
        }
83
84
    }

85
    #[cfg(not(feature = "ink-experimental-engine"))]
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
    #[cfg(test)]
    mod tests {
        use super::*;

        use ink_env::{
            call,
            test,
        };
        use ink_lang as ink;

        #[ink::test]
        fn transfer_works() {
            // given
            let contract_balance = 100;
            let accounts = default_accounts();
            let mut give_me = create_contract(contract_balance);

            // when
            set_sender(accounts.eve);
            set_balance(accounts.eve, 0);
106
            give_me.give_me(80);
107
108
109
110
111
112

            // then
            assert_eq!(get_balance(accounts.eve), 80);
        }

        #[ink::test]
113
        #[should_panic(expected = "insufficient funds!")]
114
115
116
117
118
119
120
121
        fn transfer_fails_insufficient_funds() {
            // given
            let contract_balance = 100;
            let accounts = default_accounts();
            let mut give_me = create_contract(contract_balance);

            // when
            set_sender(accounts.eve);
122
            give_me.give_me(120);
123
124

            // then
125
            // `give_me` must already have panicked here
126
127
        }

128
129
130
131
        #[ink::test]
        fn test_transferred_value() {
            // given
            let accounts = default_accounts();
132
            let give_me = create_contract(100);
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153

            // when
            set_sender(accounts.eve);
            let mut data = ink_env::test::CallData::new(ink_env::call::Selector::new([
                0xCA, 0xFE, 0xBA, 0xBE,
            ]));
            data.push_arg(&accounts.eve);
            let mock_transferred_balance = 10;

            // Push the new execution context which sets Eve as caller and
            // the `mock_transferred_balance` as the value which the contract
            // will see as transferred to it.
            ink_env::test::push_execution_context::<ink_env::DefaultEnvironment>(
                accounts.eve,
                contract_id(),
                1000000,
                mock_transferred_balance,
                data,
            );

            // then
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
            // there must be no panic
            give_me.was_it_ten();
        }

        #[ink::test]
        #[should_panic(expected = "payment was not ten")]
        fn test_transferred_value_must_fail() {
            // given
            let accounts = default_accounts();
            let give_me = create_contract(100);

            // when
            set_sender(accounts.eve);
            let mut data = ink_env::test::CallData::new(ink_env::call::Selector::new([
                0xCA, 0xFE, 0xBA, 0xBE,
            ]));
            data.push_arg(&accounts.eve);
            let mock_transferred_balance = 13;

            // Push the new execution context which sets Eve as caller and
            // the `mock_transferred_balance` as the value which the contract
            // will see as transferred to it.
            ink_env::test::push_execution_context::<ink_env::DefaultEnvironment>(
                accounts.eve,
                contract_id(),
                1000000,
                mock_transferred_balance,
                data,
            );

            // then
            give_me.was_it_ten();
186
187
        }

188
189
190
191
192
193
        /// Creates a new instance of `GiveMe` with `initial_balance`.
        ///
        /// Returns the `contract_instance`.
        fn create_contract(initial_balance: Balance) -> GiveMe {
            let accounts = default_accounts();
            set_sender(accounts.alice);
194
            set_balance(contract_id(), initial_balance);
195
196
197
            GiveMe::new()
        }

198
199
200
201
202
203
        fn contract_id() -> AccountId {
            ink_env::test::get_current_contract_account_id::<ink_env::DefaultEnvironment>(
            )
            .expect("Cannot get contract id")
        }

204
205
        fn set_sender(sender: AccountId) {
            let callee = ink_env::account_id::<ink_env::DefaultEnvironment>()
206
                .unwrap_or_else(|_| [0x0; 32].into());
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
            test::push_execution_context::<Environment>(
                sender,
                callee,
                1000000,
                1000000,
                test::CallData::new(call::Selector::new([0x00; 4])), // dummy
            );
        }

        fn default_accounts(
        ) -> ink_env::test::DefaultAccounts<ink_env::DefaultEnvironment> {
            ink_env::test::default_accounts::<ink_env::DefaultEnvironment>()
                .expect("Off-chain environment should have been initialized already")
        }

        fn set_balance(account_id: AccountId, balance: Balance) {
            ink_env::test::set_account_balance::<ink_env::DefaultEnvironment>(
                account_id, balance,
            )
            .expect("Cannot set account balance");
        }

        fn get_balance(account_id: AccountId) -> Balance {
            ink_env::test::get_account_balance::<ink_env::DefaultEnvironment>(account_id)
                .expect("Cannot set account balance")
        }
    }
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257

    #[cfg(feature = "ink-experimental-engine")]
    #[cfg(test)]
    mod tests_experimental_engine {
        use super::*;
        use ink_lang as ink;

        #[ink::test]
        fn transfer_works() {
            // given
            let contract_balance = 100;
            let accounts = default_accounts();
            let mut give_me = create_contract(contract_balance);

            // when
            set_sender(accounts.eve);
            set_balance(accounts.eve, 0);
            assert_eq!(give_me.give_me(80), Ok(()));

            // then
            assert_eq!(get_balance(accounts.eve), 80);
        }

        #[ink::test]
258
        #[should_panic(expected = "insufficient funds!")]
259
260
261
262
263
264
265
266
        fn transfer_fails_insufficient_funds() {
            // given
            let contract_balance = 100;
            let accounts = default_accounts();
            let mut give_me = create_contract(contract_balance);

            // when
            set_sender(accounts.eve);
267
            give_me.give_me(120);
268
269

            // then
270
            // `give_me` must already have panicked here
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
        }

        #[ink::test]
        fn test_transferred_value() {
            // given
            let accounts = default_accounts();
            let give_me = create_contract(100);

            // when
            // Push the new execution context which sets Eve as caller and
            // the `mock_transferred_balance` as the value which the contract
            // will see as transferred to it.
            set_sender(accounts.eve);
            ink_env::test::set_value_transferred::<ink_env::DefaultEnvironment>(10);

            // then
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
            // there must be no panic
            give_me.was_it_ten();
        }

        #[ink::test]
        #[should_panic(expected = "payment was not ten")]
        fn test_transferred_value_must_fail() {
            // given
            let accounts = default_accounts();
            let give_me = create_contract(100);

            // when
            // Push the new execution context which sets Eve as caller and
            // the `mock_transferred_balance` as the value which the contract
            // will see as transferred to it.
            set_sender(accounts.eve);
            ink_env::test::set_value_transferred::<ink_env::DefaultEnvironment>(13);

            // then
            give_me.was_it_ten();
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
        }

        /// Creates a new instance of `GiveMe` with `initial_balance`.
        ///
        /// Returns the `contract_instance`.
        fn create_contract(initial_balance: Balance) -> GiveMe {
            let accounts = default_accounts();
            set_sender(accounts.alice);
            set_balance(contract_id(), initial_balance);
            GiveMe::new()
        }

        fn contract_id() -> AccountId {
            ink_env::test::callee::<ink_env::DefaultEnvironment>()
        }

        fn set_sender(sender: AccountId) {
            ink_env::test::set_caller::<ink_env::DefaultEnvironment>(sender);
        }

        fn default_accounts(
        ) -> ink_env::test::DefaultAccounts<ink_env::DefaultEnvironment> {
            ink_env::test::default_accounts::<ink_env::DefaultEnvironment>()
        }

        fn set_balance(account_id: AccountId, balance: Balance) {
            ink_env::test::set_account_balance::<ink_env::DefaultEnvironment>(
                account_id, balance,
            )
        }

        fn get_balance(account_id: AccountId) -> Balance {
            ink_env::test::get_account_balance::<ink_env::DefaultEnvironment>(account_id)
                .expect("Cannot get account balance")
        }
    }
343
}