From 548332da4fb485553fbc1896f0e72446e35890cb Mon Sep 17 00:00:00 2001
From: shamardy <39480341+shamardy@users.noreply.github.com>
Date: Tue, 14 Aug 2018 21:43:54 +0200
Subject: [PATCH] Ensure total tokens in system is kept up to date (#428)

* Squashed commit of the following:

commit 802b219d86a63f2a68a2f2fbc406229d192ce99f
Author: shamardy <shamardy@yahoo.com>
Date:   Tue Aug 14 19:13:52 2018 +0200

    Removed set_bad_validators function

commit 53d17fc4c7798a5cf180bc8783213e0b50068ecc
Merge: 671c53a6 a079be3e
Author: shamardy <39480341+shamardy@users.noreply.github.com>
Date:   Tue Aug 14 18:00:56 2018 +0200

    Merge branch 'master' into Issue#303

commit 671c53a68f0357171d1bbbcd46f1ed7dd68755af
Author: shamardy <shamardy@yahoo.com>
Date:   Tue Aug 14 08:16:55 2018 +0200

    Updated test

commit 6c7d8f455841cfe1902e700d230844b393a2aa16
Author: shamardy <shamardy@yahoo.com>
Date:   Tue Aug 14 08:14:07 2018 +0200

    Squashed commit of the following:

    commit f5a74b4804bc1a244d35f679c2a60cffe556ca3c
    Author: shamardy <shamardy@yahoo.com>
    Date:   Tue Aug 14 07:30:36 2018 +0200

        Update Tests

    commit 39724da56d1782e9d5303ea8764dfdf8d7f517ec
    Author: shamardy <shamardy@yahoo.com>
    Date:   Tue Aug 14 06:45:34 2018 +0200

        fix

    commit 9d564c707fe5d0e4de005ab55c63c136722e6591
    Author: shamardy <shamardy@yahoo.com>
    Date:   Tue Aug 14 06:36:50 2018 +0200

        fix

    commit 0c2bad1da22488ea8cae2a6119a374bf9b628596
    Author: shamardy <shamardy@yahoo.com>
    Date:   Tue Aug 14 05:53:35 2018 +0200

        fix

    commit f7069b3784579a2d20b6298d021b0d99d3f9beb6
    Author: shamardy <shamardy@yahoo.com>
    Date:   Tue Aug 14 00:34:10 2018 +0200

        Function to set bad validators

    commit 7c9bb146ba7adacde29a11e16b0194a29d0d77c8
    Author: shamardy <shamardy@yahoo.com>
    Date:   Mon Aug 13 23:35:46 2018 +0200

        fix

    commit 641eb4267031478d60e4e1476231629052d10549
    Author: shamardy <shamardy@yahoo.com>
    Date:   Mon Aug 13 23:00:08 2018 +0200

        Edit

    commit 5981f5fd5ee65dac9c3e19275ae4647cb173d798
    Author: shamardy <shamardy@yahoo.com>
    Date:   Mon Aug 13 22:25:56 2018 +0200

        Edit fix

    commit db3dd37c435ddc5dad0f9dde56cf7be539a0e1d0
    Author: shamardy <shamardy@yahoo.com>
    Date:   Mon Aug 13 21:39:57 2018 +0200

        fix

    commit bdb34c4f14fd68b3d307980da1182075bc74f156
    Author: shamardy <shamardy@yahoo.com>
    Date:   Mon Aug 13 21:11:08 2018 +0200

        Edit for early exit slashing tests by adding bad validators manually

    commit 8134bc6d13f9bf81050d37e8db39e819342af023
    Author: shamardy <shamardy@yahoo.com>
    Date:   Mon Aug 13 15:06:57 2018 +0200

        Update header root to match storage root in wasm test

    commit ee893f65a653c8826bb177bcf378d795bd1b9351
    Author: shamardy <shamardy@yahoo.com>
    Date:   Sun Aug 12 15:27:57 2018 +0200

        Update header root to match storage root in test

    commit eb1fb61b928ca13b4ab1b76301b577154858f425
    Author: shamardy <shamardy@yahoo.com>
    Date:   Sun Aug 12 14:07:40 2018 +0200

        Update tests

    commit f27559b3364ffe1255b01e7d3f09d87fe5d9c3a2
    Author: shamardy <shamardy@yahoo.com>
    Date:   Sun Aug 12 13:14:13 2018 +0200

        Squashed commit of the following:

        commit ac244e219f6e4c5f1b19463f33ce2edb3b66f6c3
        Author: shamardy <shamardy@yahoo.com>
        Date:   Sun Aug 12 12:55:25 2018 +0200

            Edited Tests

        commit 93ac939024da55bb90479b3fcbaf82fc4407727f
        Author: shamardy <shamardy@yahoo.com>
        Date:   Sun Aug 12 12:08:47 2018 +0200

            Squashed commit of the following:

            commit 910ff83a3b0405546f0a7a1d8727e69ec22f2513
            Author: shamardy <shamardy@yahoo.com>
            Date:   Sun Aug 12 03:53:40 2018 +0200

                Edited Test

            commit 2758bc44007652fd05bab221df3f349fe7daeb6a
            Author: shamardy <shamardy@yahoo.com>
            Date:   Sun Aug 12 03:16:38 2018 +0200

                Check that block 4 is the final block in session

            commit 49f4043e0fb44118c833b3063f4820213d279bac
            Author: shamardy <shamardy@yahoo.com>
            Date:   Sun Aug 12 02:31:12 2018 +0200

                LastLengthChange should change to block number when setting length

            commit eb5873550810a25ca093a635405bb069a0610d10
            Author: shamardy <shamardy@yahoo.com>
            Date:   Sun Aug 12 00:17:22 2018 +0200

                Squashed commit of the following:

                commit 48fae25a49b0aa3294ab04651f0c2cb530994d9a
                Author: shamardy <shamardy@yahoo.com>
                Date:   Sat Aug 11 23:32:25 2018 +0200

                    Increase TotalStake by ReclaimRebate if NewAccountOutcome::GoodHint

                commit d1166230ad3dcda00cc6916efe5d0d18007ecc4f
                Author: shamardy <shamardy@yahoo.com>
                Date:   Fri Aug 10 01:45:48 2018 +0200

                    Updating set_free_balance_creating

                commit fbdabd802a618af5311d21c5ec7e4b25d50cd705
                Author: shamardy <shamardy@yahoo.com>
                Date:   Fri Aug 10 00:52:40 2018 +0200

                    fix for TotalStake tracking in transfer and set_free_balance_creating fn

                commit f26bb1d6faeab3bb9a997ea0498009bc25dae244
                Author: shamardy <shamardy@yahoo.com>
                Date:   Fri Aug 10 00:03:17 2018 +0200

                    Fix if account created on an old account with more balance

                commit f0952094de2b3ab8528fb42794d98504c647cc7a
                Author: shamardy <shamardy@yahoo.com>
                Date:   Thu Aug 9 22:32:48 2018 +0200

                    fix

                commit 28260e570c3b81b79cb390d097a7a941f44dfc0a
                Author: shamardy <shamardy@yahoo.com>
                Date:   Thu Aug 9 21:36:27 2018 +0200

                    fix totalstake update in set_free_balance_creating fn if account exists

                commit b72fd6fab556eb0ad653d805ee4c415cbf88561d
                Author: shamardy <shamardy@yahoo.com>
                Date:   Thu Aug 9 20:26:30 2018 +0200

                    TotalStake is updated in contract_transfer_max_depth function

                commit 2fa1cc27dc75229b941eba686a33fa6906f7b1a8
                Author: shamardy <shamardy@yahoo.com>
                Date:   Thu Aug 9 20:22:17 2018 +0200

                    Squashed commit of the following:

                    commit 7fbf74c5e55038b006d6ac57621ed42c00fdd0e4
                    Author: shamardy <shamardy@yahoo.com>
                    Date:   Thu Aug 9 19:08:49 2018 +0200

                        fix for tests with set_free_balance calls

                    commit c6b4196f853191467d8a99c9604ba692425bbbaa
                    Author: shamardy <shamardy@yahoo.com>
                    Date:   Thu Aug 9 18:28:03 2018 +0200

                        Update TotalStake where set_free_balance is called

                    commit e827abc5184d48728168fbb57be6e8f03a8504e9
                    Author: shamardy <shamardy@yahoo.com>
                    Date:   Thu Aug 9 16:57:36 2018 +0200

                        Update TotalStake where set_reserved_balance is called

                    commit f73bec9c1a8376360b992e39333d762892ca8735
                    Author: shamardy <shamardy@yahoo.com>
                    Date:   Fri Aug 3 16:44:59 2018 +0200

                        fix

                    commit 5a498c5f4660429f7a24c09e715f7b083266c93d
                    Author: shamardy <shamardy@yahoo.com>
                    Date:   Fri Aug 3 15:47:03 2018 +0200

                        Test for full_native_block_import_works to check storage root

                    commit 024249ca52ae7ef0f5d39e99c585617a3db1dc0c
                    Author: shamardy <shamardy@yahoo.com>
                    Date:   Fri Aug 3 14:38:07 2018 +0200

                        Use <FreeBalance<Test>>::insert in this fn to avoid TotalStake Overflow

                    commit d602839cd59dd8550c87ec2c0bf103c806daedab
                    Author: shamardy <shamardy@yahoo.com>
                    Date:   Fri Aug 3 13:59:47 2018 +0200

                        Removed <TotalStake<Test>>::put from tests

                    commit 38586043912b40c9004bb5232cb7ca3c01ec9144
                    Author: shamardy <shamardy@yahoo.com>
                    Date:   Fri Aug 3 13:56:15 2018 +0200

                        Replace Balance::insert in tests to set balance fn to update TotalStake

                    commit 170ab6f8cd152adbc525bcc32fa012e3c11b6177
                    Merge: 9b0b22bd 2230b61c
                    Author: shamardy <shamardy@yahoo.com>
                    Date:   Fri Aug 3 12:32:05 2018 +0200

                        Merge branch 'Issue#303' of https://github.com/shamardy/polkadot into Issue#303

                    commit 9b0b22bd2084083f610e4870d5866bbd8e8d7229
                    Author: shamardy <shamardy@yahoo.com>
                    Date:   Fri Aug 3 12:31:45 2018 +0200

                        Edit

                    commit 2230b61c261296f6d09d0ec5353c0f207b281a67
                    Merge: 2fe9c528 05f49f1d
                    Author: shamardy <39480341+shamardy@users.noreply.github.com>
                    Date:   Fri Aug 3 11:12:19 2018 +0200

                        Merge branch 'master' into Issue#303

                    commit 2fe9c528bef62b0f43ef98c5166408d7d048f513
                    Author: shamardy <shamardy@yahoo.com>
                    Date:   Fri Aug 3 11:09:08 2018 +0200

                        commented out some tests

                    commit a6c2d8412e1d8e409d4fe2ca6545be5e525d80b0
                    Author: shamardy <shamardy@yahoo.com>
                    Date:   Fri Aug 3 10:35:17 2018 +0200

                        fix

                    commit ceb34d873b48ea7debd878a78f57ce235acd6ee8
                    Author: shamardy <shamardy@yahoo.com>
                    Date:   Thu Aug 2 16:52:16 2018 +0200

                        Update

                    commit a363120bd1b72597deb6ee945f9c51d32a851b14
                    Author: shamardy <shamardy@yahoo.com>
                    Date:   Thu Aug 2 16:05:40 2018 +0200

                        Edit

                    commit e45a92847a4beb28aa6f876ec109585467f4d732
                    Author: shamardy <shamardy@yahoo.com>
                    Date:   Wed Aug 1 16:49:40 2018 +0200

                        Edit

                    commit 07c5dcec22e43d6ccb49b42356590fb370bbcfae
                    Author: shamardy <shamardy@yahoo.com>
                    Date:   Tue Jul 31 15:44:40 2018 +0200

                        Instead of update_total_stake => 2 functions to increase and decrease

                    commit 7eb03b29e429a86d206244779d383af9437f208d
                    Author: shamardy <shamardy@yahoo.com>
                    Date:   Tue Jul 31 14:24:36 2018 +0200

                        Removed update_total_stake from set_free_balance_creating

                    commit 234ff798c6a7e035c7d3f7a9a668e311f9940dc5
                    Author: shamardy <shamardy@yahoo.com>
                    Date:   Tue Jul 31 14:22:48 2018 +0200

                        Squashed commit of the following:

                        commit 8f2e421a731f353394c611dc6e93ad48ba811a1a
                        Author: shamardy <shamardy@yahoo.com>
                        Date:   Tue Jul 31 13:24:30 2018 +0200

                            added balances to trait Store

                        commit b64c3a99467895b042f6a30219caf87f8265fa90
                        Author: shamardy <shamardy@yahoo.com>
                        Date:   Tue Jul 31 12:52:16 2018 +0200

                            update_total_stake iterates through balances

                        commit bf503ecc6b3664a6be7eac6adef3f83f72e4a8fa
                        Author: shamardy <shamardy@yahoo.com>
                        Date:   Tue Jul 31 11:06:25 2018 +0200

                            Removed update_total_stake from inside transfer function for now to test

                        commit d91a8a666b5b52e1c77b72e3ae59040e71cd8d9c
                        Author: shamardy <shamardy@yahoo.com>
                        Date:   Mon Jul 30 21:26:09 2018 +0200

                            update_total_stake function fix

                        commit 2465361fe9f631ae790d3f24ef69f9972b6adae5
                        Author: shamardy <shamardy@yahoo.com>
                        Date:   Mon Jul 30 21:10:02 2018 +0200

                            fix

                        commit 2351f3532d6ba28491231bcb0717f8e76fc35629
                        Author: shamardy <shamardy@yahoo.com>
                        Date:   Mon Jul 30 19:36:21 2018 +0200

                            fix

                        commit 7139371e5c07cc41112468e82d7ec901e8361d60
                        Author: shamardy <shamardy@yahoo.com>
                        Date:   Mon Jul 30 18:38:50 2018 +0200

                            update

                        commit e6602d1f98190f35565d3c31e3b7a2d3df64607e
                        Author: shamardy <shamardy@yahoo.com>
                        Date:   Mon Jul 30 18:36:43 2018 +0200

                            Squashed commit of the following:

                            commit dcb597a60c960ff40623e98c6a1210f5df196794
                            Author: shamardy <shamardy@yahoo.com>
                            Date:   Mon Jul 30 18:31:49 2018 +0200

                                update

                            commit c41382eb135eda3bffa957e8887fcffd0388a745
                            Author: shamardy <shamardy@yahoo.com>
                            Date:   Mon Jul 30 18:23:59 2018 +0200

                                Update

                            commit f828c69e055489b69739b0ea082afa1ceca23b9c
                            Author: shamardy <shamardy@yahoo.com>
                            Date:   Mon Jul 30 18:12:18 2018 +0200

                                Created function to update total stake

                            commit e398a587edb7e57378bd61c9f9940aadfb94e82a
                            Author: shamardy <shamardy@yahoo.com>
                            Date:   Mon Jul 30 15:02:07 2018 +0200

                                TotalStake tracks transfer fees + added test for account removal

                            commit 0cfb26ce508578ce386bac5e02856cb6f298c6ba
                            Author: shamardy <shamardy@yahoo.com>
                            Date:   Mon Jul 30 14:21:06 2018 +0200

                                TotalStake tracks accounts removal when free/reserved balance is too low

                            commit 6054dcf171eddfbe58c4e01f2b32b6f576e3d9c7
                            Merge: 5740c8fc 6fa9c949
                            Author: shamardy <shamardy@yahoo.com>
                            Date:   Mon Jul 30 14:16:37 2018 +0200

                                Merge branch 'Issue#303' of https://github.com/shamardy/polkadot into Issue#303

                            commit 5740c8fc09cdac9ec2228a66626b1c1ecb5dbeaf
                            Author: shamardy <shamardy@yahoo.com>
                            Date:   Mon Jul 30 14:15:41 2018 +0200

                                Resolved merge conflict by incorporating both suggestions.

                            commit 6fa9c949b9257bccb7ee48c32af35182a4dbf5f8
                            Merge: 2b29fe85 8c527f29
                            Author: shamardy <39480341+shamardy@users.noreply.github.com>
                            Date:   Mon Jul 30 14:12:11 2018 +0200

                                Merge branch 'master' into Issue#303

                            commit 2b29fe85ff0802594ad203d430ec4653f980296d
                            Author: shamardy <shamardy@yahoo.com>
                            Date:   Mon Jul 30 13:48:48 2018 +0200

                                Squashed commit of the following:

                                commit 773cdb913f671f575cc2933b14f2e783f49ffd7e
                                Author: shamardy <shamardy@yahoo.com>
                                Date:   Mon Jul 30 13:13:21 2018 +0200

                                    Squashed commit of the following:

                                    commit 07dc1945c3b51438028494f7691343638d647a93
                                    Author: shamardy <shamardy@yahoo.com>
                                    Date:   Mon Jul 30 13:08:00 2018 +0200

                                        TotalStake tracks accounts removal when free/reserved balance is too low

                                    commit 1b04d3afab44c99751c389ac6cddd865c0f77015
                                    Author: shamardy <shamardy@yahoo.com>
                                    Date:   Thu Jul 26 21:29:35 2018 +0200

                                        Edited slashing reserved balance tests

                                    commit 52482d5ac5828e927afcd7f27010ef64c085353f
                                    Author: shamardy <shamardy@yahoo.com>
                                    Date:   Thu Jul 26 20:46:17 2018 +0200

                                        Edited some tests

                                    commit 7c98f96d2ea1952b241054581bc1430863e4aab4
                                    Author: shamardy <shamardy@yahoo.com>
                                    Date:   Thu Jul 26 20:11:54 2018 +0200

                                        TotalStake tracks slashing of reserved balance

                                    commit 1d9f942ede81281218c1b4f84201388cf0908a4e
                                    Author: shamardy <shamardy@yahoo.com>
                                    Date:   Thu Jul 26 18:43:36 2018 +0200

                                        Ensure total tokens in system is kept up to date

* Fix Test
---
 substrate/demo/executor/src/lib.rs            | 45 +++++++++--
 .../polkadot/test-parachains/adder/src/src    |  0
 .../substrate/runtime/contract/src/gas.rs     |  2 +
 .../substrate/runtime/contract/src/tests.rs   | 16 ++++
 .../substrate/runtime/staking/src/lib.rs      | 36 +++++++--
 .../substrate/runtime/staking/src/tests.rs    | 75 ++++++++++++++-----
 6 files changed, 143 insertions(+), 31 deletions(-)
 mode change 120000 => 100644 substrate/polkadot/test-parachains/adder/src/src

diff --git a/substrate/demo/executor/src/lib.rs b/substrate/demo/executor/src/lib.rs
index 5ebece1f609..346f26d1e07 100644
--- a/substrate/demo/executor/src/lib.rs
+++ b/substrate/demo/executor/src/lib.rs
@@ -247,7 +247,7 @@ mod tests {
 		construct_block(
 			1,
 			[69u8; 32].into(),
-			hex!("b97d52254fc967bb94bed485de6a738e9fad05decfda3453711677b8becf6d0a").into(),
+			hex!("c563199c60df7d914262b1775b284870f3a5da2f24b56d2c6288b37c815a6cd9").into(),
 			vec![BareExtrinsic {
 				signed: alice(),
 				index: 0,
@@ -260,7 +260,40 @@ mod tests {
 		construct_block(
 			2,
 			block1().1,
-			hex!("a1f018d2faa339f72f5ee29050b4670d971e2e271cc06c41ee9cbe1f4c6feec9").into(),
+			hex!("83f71d5475f63350825b0301de322233d3711a9f3fcfd74050d1534af47a36b3").into(),
+			vec![
+				BareExtrinsic {
+					signed: bob(),
+					index: 0,
+					function: Call::Staking(staking::Call::transfer(alice().into(), 5)),
+				},
+				BareExtrinsic {
+					signed: alice(),
+					index: 1,
+					function: Call::Staking(staking::Call::transfer(bob().into(), 15)),
+				}
+			]
+		)
+	}
+
+	fn block1_wasm() -> (Vec<u8>, Hash) {
+		construct_block(
+			1,
+			[69u8; 32].into(),
+			hex!("b97d52254fc967bb94bed485de6a738e9fad05decfda3453711677b8becf6d0a").into(),
+			vec![BareExtrinsic {
+				signed: alice(),
+				index: 0,
+				function: Call::Staking(staking::Call::transfer(bob().into(), 69)),
+			}]
+		)
+	}
+
+	fn block2_wasm() -> (Vec<u8>, Hash) {
+		construct_block(
+			2,
+			block1().1,
+			hex!("b820fe09935dba41d200b627c11bd7dd9ebff39c319dee18be3ee4f99fc1eab4").into(),
 			vec![
 				BareExtrinsic {
 					signed: bob(),
@@ -280,7 +313,7 @@ mod tests {
 		construct_block(
 			1,
 			[69u8; 32].into(),
-			hex!("41d07010f49aa29b2c9aca542cbaa6f59aafd3dda53cdf711c51ddb7d386912e").into(),
+			hex!("06d026c0d687ec583660a6052de6f89acdb24ea964d06be3831c837c3c426966").into(),
 			vec![BareExtrinsic {
 				signed: alice(),
 				index: 0,
@@ -312,14 +345,14 @@ mod tests {
 	fn full_wasm_block_import_works() {
 		let mut t = new_test_ext();
 
-		WasmExecutor::new(8).call(&mut t, COMPACT_CODE, "execute_block", &block1().0).unwrap();
+		WasmExecutor::new(8).call(&mut t, COMPACT_CODE, "execute_block", &block1_wasm().0).unwrap();
 
 		runtime_io::with_externalities(&mut t, || {
 			assert_eq!(Staking::voting_balance(&alice()), 41);
 			assert_eq!(Staking::voting_balance(&bob()), 69);
 		});
 
-		WasmExecutor::new(8).call(&mut t, COMPACT_CODE, "execute_block", &block2().0).unwrap();
+		WasmExecutor::new(8).call(&mut t, COMPACT_CODE, "execute_block", &block2_wasm().0).unwrap();
 
 		runtime_io::with_externalities(&mut t, || {
 			assert_eq!(Staking::voting_balance(&alice()), 30);
@@ -338,7 +371,7 @@ mod tests {
 	#[test]
 	fn native_big_block_import_succeeds() {
 		let mut t = new_test_ext();
-
+		
 		let r = Executor::with_heap_pages(8).call(&mut t, COMPACT_CODE, "execute_block", &block1big().0, true).0;
 		assert!(r.is_ok());
 	}
diff --git a/substrate/polkadot/test-parachains/adder/src/src b/substrate/polkadot/test-parachains/adder/src/src
deleted file mode 120000
index e8310385c56..00000000000
--- a/substrate/polkadot/test-parachains/adder/src/src
+++ /dev/null
@@ -1 +0,0 @@
-src
\ No newline at end of file
diff --git a/substrate/polkadot/test-parachains/adder/src/src b/substrate/polkadot/test-parachains/adder/src/src
new file mode 100644
index 00000000000..e8310385c56
--- /dev/null
+++ b/substrate/polkadot/test-parachains/adder/src/src
@@ -0,0 +1 @@
+src
\ No newline at end of file
diff --git a/substrate/substrate/runtime/contract/src/gas.rs b/substrate/substrate/runtime/contract/src/gas.rs
index 662ddc4fbd3..2f2b82d6b01 100644
--- a/substrate/substrate/runtime/contract/src/gas.rs
+++ b/substrate/substrate/runtime/contract/src/gas.rs
@@ -136,6 +136,7 @@ pub fn buy_gas<T: Trait>(
 		return Err("not enough funds for transaction fee");
 	}
 	<staking::Module<T>>::set_free_balance(transactor, b - cost);
+	<staking::Module<T>>::decrease_total_stake_by(cost);
 	Ok(GasMeter {
 		gas_left: gas_limit,
 		gas_price,
@@ -147,4 +148,5 @@ pub fn refund_unused_gas<T: Trait>(transactor: &T::AccountId, gas_meter: GasMete
 	let b = <staking::Module<T>>::free_balance(transactor);
 	let refund = <T::Gas as As<T::Balance>>::as_(gas_meter.gas_left) * gas_meter.gas_price;
 	<staking::Module<T>>::set_free_balance(transactor, b + refund);
+	<staking::Module<T>>::increase_total_stake_by(refund);
 }
diff --git a/substrate/substrate/runtime/contract/src/tests.rs b/substrate/substrate/runtime/contract/src/tests.rs
index f79b155cf5d..d9839dae264 100644
--- a/substrate/substrate/runtime/contract/src/tests.rs
+++ b/substrate/substrate/runtime/contract/src/tests.rs
@@ -162,7 +162,9 @@ fn contract_transfer() {
 		<CodeOf<Test>>::insert(1, code_transfer.to_vec());
 
 		Staking::set_free_balance(&0, 100_000_000);
+		Staking::increase_total_stake_by(100_000_000);
 		Staking::set_free_balance(&1, 11);
+		Staking::increase_total_stake_by(11);
 
 		assert_ok!(Contract::call(&0, 1, 3, 100_000, Vec::new()));
 
@@ -195,7 +197,9 @@ fn contract_transfer_oog() {
 		<CodeOf<Test>>::insert(1, code_transfer.to_vec());
 
 		Staking::set_free_balance(&0, 100_000_000);
+		Staking::increase_total_stake_by(100_000_000);
 		Staking::set_free_balance(&1, 11);
+		Staking::increase_total_stake_by(11);
 
 		assert_err!(
 			Contract::call(&0, 1, 3, 276, Vec::new()),
@@ -232,7 +236,9 @@ fn contract_transfer_max_depth() {
 		<CodeOf<Test>>::insert(CONTRACT_SHOULD_TRANSFER_TO, code_transfer.to_vec());
 
 		Staking::set_free_balance(&0, 100_000_000);
+		Staking::increase_total_stake_by(100_000_000);
 		Staking::set_free_balance(&CONTRACT_SHOULD_TRANSFER_TO, 11);
+		Staking::increase_total_stake_by(11);
 
 		assert_err!(
 			Contract::call(&0, CONTRACT_SHOULD_TRANSFER_TO, 3, 100_000, Vec::new()),
@@ -331,8 +337,10 @@ fn contract_create() {
 
 	with_externalities(&mut new_test_ext(0, 2), || {
 		Staking::set_free_balance(&0, 100_000_000);
+		Staking::increase_total_stake_by(100_000_000);
 		Staking::set_free_balance(&1, 0);
 		Staking::set_free_balance(&9, 30);
+		Staking::increase_total_stake_by(30);
 
 		<CodeOf<Test>>::insert(1, code_create.to_vec());
 
@@ -383,7 +391,9 @@ fn top_level_create() {
 		);
 
 		Staking::set_free_balance(&0, 100_000_000);
+		Staking::increase_total_stake_by(100_000_000);
 		Staking::set_free_balance(&derived_address, 30);
+		Staking::increase_total_stake_by(30);
 
 		assert_ok!(Contract::create(
 			&0,
@@ -423,6 +433,7 @@ fn refunds_unused_gas() {
 		<CodeOf<Test>>::insert(1, code_nop.to_vec());
 
 		Staking::set_free_balance(&0, 100_000_000);
+		Staking::increase_total_stake_by(100_000_000);
 
 		assert_ok!(Contract::call(&0, 1, 0, 100_000, Vec::new(),));
 
@@ -436,6 +447,7 @@ fn call_with_zero_value() {
 		<CodeOf<Test>>::insert(1, vec![]);
 
 		Staking::set_free_balance(&0, 100_000_000);
+		Staking::increase_total_stake_by(100_000_000);
 
 		assert_ok!(Contract::call(&0, 1, 0, 100_000, Vec::new(),));
 
@@ -449,6 +461,7 @@ fn create_with_zero_endowment() {
 
 	with_externalities(&mut new_test_ext(0, 2), || {
 		Staking::set_free_balance(&0, 100_000_000);
+		Staking::increase_total_stake_by(100_000_000);
 
 		assert_ok!(Contract::create(&0, 0, 100_000, code_nop, Vec::new(),));
 
@@ -467,10 +480,12 @@ fn account_removal_removes_storage() {
 		// Setup two accounts with free balance above than exsistential threshold.
 		{
 			Staking::set_free_balance(&1, 110);
+			Staking::increase_total_stake_by(110);
 			<StorageOf<Test>>::insert(1, b"foo".to_vec(), b"1".to_vec());
 			<StorageOf<Test>>::insert(1, b"bar".to_vec(), b"2".to_vec());
 
 			Staking::set_free_balance(&2, 110);
+			Staking::increase_total_stake_by(110);
 			<StorageOf<Test>>::insert(2, b"hello".to_vec(), b"3".to_vec());
 			<StorageOf<Test>>::insert(2, b"world".to_vec(), b"4".to_vec());
 		}
@@ -515,6 +530,7 @@ fn top_level_call_refunds_even_if_fails() {
 		<CodeOf<Test>>::insert(1, code_unreachable.to_vec());
 
 		Staking::set_free_balance(&0, 100_000_000);
+		Staking::increase_total_stake_by(100_000_000);
 
 		assert_err!(
 			Contract::call(&0, 1, 0, 100_000, Vec::new()),
diff --git a/substrate/substrate/runtime/staking/src/lib.rs b/substrate/substrate/runtime/staking/src/lib.rs
index b0bf08e96e3..bb89c2be8b3 100644
--- a/substrate/substrate/runtime/staking/src/lib.rs
+++ b/substrate/substrate/runtime/staking/src/lib.rs
@@ -302,7 +302,8 @@ impl<T: Trait> Module<T> {
 		};
 
 		if transactor != &dest {
-			Self::set_free_balance(transactor, new_from_balance);
+			Self::set_free_balance(transactor, new_from_balance);			
+			Self::decrease_total_stake_by(fee);
 			Self::set_free_balance_creating(&dest, new_to_balance);
 		}
 
@@ -424,6 +425,7 @@ impl<T: Trait> Module<T> {
 	/// In that case it will return `AccountKilled`.
 	pub fn set_reserved_balance(who: &T::AccountId, balance: T::Balance) -> UpdateBalanceOutcome {
 		if balance < Self::existential_deposit() {
+			<ReservedBalance<T>>::insert(who, balance);
 			Self::on_reserved_too_low(who);
 			UpdateBalanceOutcome::AccountKilled
 		} else {
@@ -443,6 +445,7 @@ impl<T: Trait> Module<T> {
 		// Commented out for no - but consider it instructive.
 		// assert!(!Self::voting_balance(who).is_zero());
 		if balance < Self::existential_deposit() {
+			<FreeBalance<T>>::insert(who, balance);
 			Self::on_free_too_low(who);
 			UpdateBalanceOutcome::AccountKilled
 		} else {
@@ -472,7 +475,7 @@ impl<T: Trait> Module<T> {
 		// value of which makes even the `free_balance` unspendable.
 		// TODO: enforce this for the other balance-altering functions.
 		if balance < ed {
-			Self::on_free_too_low(who);
+			Self::set_free_balance(who, balance);
 			UpdateBalanceOutcome::AccountKilled
 		} else {
 			if !<FreeBalance<T>>::exists(who) {
@@ -481,10 +484,12 @@ impl<T: Trait> Module<T> {
 					NewAccountOutcome::GoodHint => balance + <Module<T>>::reclaim_rebate(),
 					_ => balance,
 				};
-				<FreeBalance<T>>::insert(who, credit);
-			} else {
-				<FreeBalance<T>>::insert(who, balance);
+				Self::set_free_balance(who, credit);
+				Self::increase_total_stake_by(credit - balance);
+			} else {	
+				Self::set_free_balance(who, balance);
 			}
+
 			UpdateBalanceOutcome::Updated
 		}
 	}
@@ -498,6 +503,7 @@ impl<T: Trait> Module<T> {
 		let free_balance = Self::free_balance(who);
 		let free_slash = cmp::min(free_balance, value);
 		Self::set_free_balance(who, free_balance - free_slash);
+		Self::decrease_total_stake_by(free_slash);
 		if free_slash < value {
 			Self::slash_reserved(who, value - free_slash)
 		} else {
@@ -513,6 +519,7 @@ impl<T: Trait> Module<T> {
 			return Err("beneficiary account must pre-exist");
 		}
 		Self::set_free_balance(who, Self::free_balance(who) + value);
+		Self::increase_total_stake_by(value);
 		Ok(())
 	}
 
@@ -558,6 +565,7 @@ impl<T: Trait> Module<T> {
 		let b = Self::reserved_balance(who);
 		let slash = cmp::min(b, value);
 		Self::set_reserved_balance(who, b - slash);
+		Self::decrease_total_stake_by(slash);
 		if value == slash {
 			None
 		} else {
@@ -785,6 +793,7 @@ impl<T: Trait> Module<T> {
 
 	/// Kill an account's free portion.
 	fn on_free_too_low(who: &T::AccountId) {
+		Self::decrease_total_stake_by(Self::free_balance(who));
 		<FreeBalance<T>>::remove(who);
 		<Bondage<T>>::remove(who);
 		T::OnAccountKill::on_account_kill(who);
@@ -796,11 +805,25 @@ impl<T: Trait> Module<T> {
 
 	/// Kill an account's reserved portion.
 	fn on_reserved_too_low(who: &T::AccountId) {
+		Self::decrease_total_stake_by(Self::reserved_balance(who));
 		<ReservedBalance<T>>::remove(who);
 		if Self::free_balance(who).is_zero() {
 			<system::AccountNonce<T>>::remove(who);
 		}
 	}
+
+	/// Increase TotalStake by Value.
+	pub fn increase_total_stake_by(value: T::Balance) {
+		if <TotalStake<T>>::exists() {
+			<TotalStake<T>>::put(<Module<T>>::total_stake() + value);
+		}
+	}
+	/// Decrease TotalStake by Value.
+	pub fn decrease_total_stake_by(value: T::Balance) {
+		if <TotalStake<T>>::exists() {
+			<TotalStake<T>>::put(<Module<T>>::total_stake() - value);
+		}
+	}
 }
 
 impl<T: Trait> Executable for Module<T> {
@@ -832,7 +855,8 @@ impl<T: Trait> MakePayment<T::AccountId> for Module<T> {
 		if b < transaction_fee + Self::existential_deposit() {
 			return Err("not enough funds for transaction fee");
 		}
-		<FreeBalance<T>>::insert(transactor, b - transaction_fee);
+		Self::set_free_balance(transactor, b - transaction_fee);
+		Self::decrease_total_stake_by(transaction_fee);
 		Ok(())
 	}
 }
diff --git a/substrate/substrate/runtime/staking/src/tests.rs b/substrate/substrate/runtime/staking/src/tests.rs
index 36549d534f7..b8e11cd98ff 100644
--- a/substrate/substrate/runtime/staking/src/tests.rs
+++ b/substrate/substrate/runtime/staking/src/tests.rs
@@ -28,6 +28,7 @@ fn reward_should_work() {
 		assert_eq!(Staking::voting_balance(&10), 1);
 		assert_ok!(Staking::reward(&10, 10));
 		assert_eq!(Staking::voting_balance(&10), 11);
+		assert_eq!(<TotalStake<Test>>::get(), 112);
 	});
 }
 
@@ -408,7 +409,7 @@ fn staking_eras_work() {
 #[test]
 fn staking_balance_works() {
 	with_externalities(&mut new_test_ext(0, 1, 3, 1, false, 0), || {
-		<FreeBalance<Test>>::insert(1, 42);
+		Staking::set_free_balance(&1, 42);
 		assert_eq!(Staking::free_balance(&1), 42);
 		assert_eq!(Staking::reserved_balance(&1), 0);
 		assert_eq!(Staking::voting_balance(&1), 42);
@@ -421,7 +422,8 @@ fn staking_balance_works() {
 #[test]
 fn staking_balance_transfer_works() {
 	with_externalities(&mut new_test_ext(0, 1, 3, 1, false, 0), || {
-		<FreeBalance<Test>>::insert(1, 111);
+		Staking::set_free_balance(&1, 111);
+		Staking::increase_total_stake_by(111);
 		assert_ok!(Staking::transfer(&1, 2.into(), 69));
 		assert_eq!(Staking::voting_balance(&1), 42);
 		assert_eq!(Staking::voting_balance(&2), 69);
@@ -431,7 +433,7 @@ fn staking_balance_transfer_works() {
 #[test]
 fn staking_balance_transfer_when_bonded_should_not_work() {
 	with_externalities(&mut new_test_ext(0, 1, 3, 1, false, 0), || {
-		<FreeBalance<Test>>::insert(1, 111);
+		Staking::set_free_balance(&1, 111);
 		assert_ok!(Staking::stake(&1));
 		assert_noop!(Staking::transfer(&1, 2.into(), 69), "bondage too high to send value");
 	});
@@ -440,7 +442,7 @@ fn staking_balance_transfer_when_bonded_should_not_work() {
 #[test]
 fn reserving_balance_should_work() {
 	with_externalities(&mut new_test_ext(0, 1, 3, 1, false, 0), || {
-		<FreeBalance<Test>>::insert(1, 111);
+		Staking::set_free_balance(&1, 111);
 
 		assert_eq!(Staking::voting_balance(&1), 111);
 		assert_eq!(Staking::free_balance(&1), 111);
@@ -457,7 +459,7 @@ fn reserving_balance_should_work() {
 #[test]
 fn staking_balance_transfer_when_reserved_should_not_work() {
 	with_externalities(&mut new_test_ext(0, 1, 3, 1, false, 0), || {
-		<FreeBalance<Test>>::insert(1, 111);
+		Staking::set_free_balance(&1, 111);
 		assert_ok!(Staking::reserve(&1, 69));
 		assert_noop!(Staking::transfer(&1, 2.into(), 69), "balance too low to send value");
 	});
@@ -466,7 +468,7 @@ fn staking_balance_transfer_when_reserved_should_not_work() {
 #[test]
 fn deducting_balance_should_work() {
 	with_externalities(&mut new_test_ext(0, 1, 3, 1, false, 0), || {
-		<FreeBalance<Test>>::insert(1, 111);
+		Staking::set_free_balance(&1, 111);
 		assert_ok!(Staking::reserve(&1, 69));
 		assert_eq!(Staking::free_balance(&1), 42);
 	});
@@ -475,7 +477,7 @@ fn deducting_balance_should_work() {
 #[test]
 fn deducting_balance_when_bonded_should_not_work() {
 	with_externalities(&mut new_test_ext(0, 1, 3, 1, false, 0), || {
-		<FreeBalance<Test>>::insert(1, 111);
+		Staking::set_free_balance(&1, 111);
 		<Bondage<Test>>::insert(1, 2);
 		System::set_block_number(1);
 		assert_eq!(Staking::unlock_block(&1), LockStatus::LockedUntil(2));
@@ -486,8 +488,8 @@ fn deducting_balance_when_bonded_should_not_work() {
 #[test]
 fn refunding_balance_should_work() {
 	with_externalities(&mut new_test_ext(0, 1, 3, 1, false, 0), || {
-		<FreeBalance<Test>>::insert(1, 42);
-		<ReservedBalance<Test>>::insert(1, 69);
+		Staking::set_free_balance(&1, 42);
+		Staking::set_reserved_balance(&1, 69);
 		Staking::unreserve(&1, 69);
 		assert_eq!(Staking::free_balance(&1), 111);
 		assert_eq!(Staking::reserved_balance(&1), 0);
@@ -497,29 +499,33 @@ fn refunding_balance_should_work() {
 #[test]
 fn slashing_balance_should_work() {
 	with_externalities(&mut new_test_ext(0, 1, 3, 1, false, 0), || {
-		<FreeBalance<Test>>::insert(1, 111);
+		Staking::set_free_balance(&1, 111);
+		Staking::increase_total_stake_by(111);
 		assert_ok!(Staking::reserve(&1, 69));
 		assert!(Staking::slash(&1, 69).is_none());
 		assert_eq!(Staking::free_balance(&1), 0);
 		assert_eq!(Staking::reserved_balance(&1), 42);
+		assert_eq!(<TotalStake<Test>>::get(), 44);
 	});
 }
 
 #[test]
 fn slashing_incomplete_balance_should_work() {
 	with_externalities(&mut new_test_ext(0, 1, 3, 1, false, 0), || {
-		<FreeBalance<Test>>::insert(1, 42);
+		Staking::set_free_balance(&1, 42);
+		Staking::increase_total_stake_by(42);
 		assert_ok!(Staking::reserve(&1, 21));
 		assert!(Staking::slash(&1, 69).is_some());
 		assert_eq!(Staking::free_balance(&1), 0);
 		assert_eq!(Staking::reserved_balance(&1), 0);
+		assert_eq!(<TotalStake<Test>>::get(), 2);
 	});
 }
 
 #[test]
 fn unreserving_balance_should_work() {
 	with_externalities(&mut new_test_ext(0, 1, 3, 1, false, 0), || {
-		<FreeBalance<Test>>::insert(1, 111);
+		Staking::set_free_balance(&1, 111);
 		assert_ok!(Staking::reserve(&1, 111));
 		Staking::unreserve(&1, 42);
 		assert_eq!(Staking::reserved_balance(&1), 69);
@@ -530,30 +536,34 @@ fn unreserving_balance_should_work() {
 #[test]
 fn slashing_reserved_balance_should_work() {
 	with_externalities(&mut new_test_ext(0, 1, 3, 1, false, 0), || {
-		<FreeBalance<Test>>::insert(1, 111);
+		Staking::set_free_balance(&1, 111);
+		Staking::increase_total_stake_by(111);
 		assert_ok!(Staking::reserve(&1, 111));
 		assert!(Staking::slash_reserved(&1, 42).is_none());
 		assert_eq!(Staking::reserved_balance(&1), 69);
 		assert_eq!(Staking::free_balance(&1), 0);
+		assert_eq!(<TotalStake<Test>>::get(), 71);
 	});
 }
 
 #[test]
 fn slashing_incomplete_reserved_balance_should_work() {
 	with_externalities(&mut new_test_ext(0, 1, 3, 1, false, 0), || {
-		<FreeBalance<Test>>::insert(1, 111);
+		Staking::set_free_balance(&1, 111);
+		Staking::increase_total_stake_by(111);
 		assert_ok!(Staking::reserve(&1, 42));
 		assert!(Staking::slash_reserved(&1, 69).is_some());
 		assert_eq!(Staking::free_balance(&1), 69);
 		assert_eq!(Staking::reserved_balance(&1), 0);
+		assert_eq!(<TotalStake<Test>>::get(), 71);
 	});
 }
 
 #[test]
 fn transferring_reserved_balance_should_work() {
 	with_externalities(&mut new_test_ext(0, 1, 3, 1, false, 0), || {
-		<FreeBalance<Test>>::insert(1, 110);
-		<FreeBalance<Test>>::insert(2, 1);
+		Staking::set_free_balance(&1, 110);
+		Staking::set_free_balance(&2, 1);
 		assert_ok!(Staking::reserve(&1, 110));
 		assert_ok!(Staking::transfer_reserved(&1, &2, 41), None);
 		assert_eq!(Staking::reserved_balance(&1), 69);
@@ -566,7 +576,7 @@ fn transferring_reserved_balance_should_work() {
 #[test]
 fn transferring_reserved_balance_to_nonexistent_should_fail() {
 	with_externalities(&mut new_test_ext(0, 1, 3, 1, false, 0), || {
-		<FreeBalance<Test>>::insert(1, 111);
+		Staking::set_free_balance(&1, 111);
 		assert_ok!(Staking::reserve(&1, 111));
 		assert_noop!(Staking::transfer_reserved(&1, &2, 42), "beneficiary account must pre-exist");
 	});
@@ -575,8 +585,8 @@ fn transferring_reserved_balance_to_nonexistent_should_fail() {
 #[test]
 fn transferring_incomplete_reserved_balance_should_work() {
 	with_externalities(&mut new_test_ext(0, 1, 3, 1, false, 0), || {
-		<FreeBalance<Test>>::insert(1, 110);
-		<FreeBalance<Test>>::insert(2, 1);
+		Staking::set_free_balance(&1, 110);
+		Staking::set_free_balance(&2, 1);
 		assert_ok!(Staking::reserve(&1, 41));
 		assert!(Staking::transfer_reserved(&1, &2, 69).unwrap().is_some());
 		assert_eq!(Staking::reserved_balance(&1), 0);
@@ -599,5 +609,32 @@ fn transferring_too_high_value_should_not_panic() {
 
 		assert_eq!(Staking::free_balance(&1), u64::max_value());
 		assert_eq!(Staking::free_balance(&2), 1);
+		});
+}
+
+#[test]
+fn account_removal_on_free_too_low() {
+	with_externalities(&mut new_test_ext(100, 1, 3, 1, false, 0), || {
+		// Setup two accounts with free balance above the exsistential threshold.
+		{
+			Staking::set_free_balance(&1, 110);
+			Staking::increase_total_stake_by(110);
+
+			Staking::set_free_balance(&2, 110);
+			Staking::increase_total_stake_by(110);
+
+			assert_eq!(<TotalStake<Test>>::get(), 732);
+		}
+
+		// Transfer funds from account 1 of such amount that after this transfer
+		// the balance of account 1 will be below the exsistential threshold.
+		// This should lead to the removal of all balance of this account.
+		assert_ok!(Staking::transfer(&1, 2.into(), 20));
+
+		// Verify free balance removal of account 1.
+		assert_eq!(Staking::free_balance(&1), 0);
+		
+		// Verify that TotalStake tracks balance removal when free balance is too low.
+		assert_eq!(<TotalStake<Test>>::get(), 642);
 	});
 }
-- 
GitLab