Repository: DA0-DA0/dao-contracts
Pull request #223 (2022-03-25 20:56:21)

main -> v1 contracts
Needed as stake-cw20 had some changes, this allows us to use the hooks.


Patch:
diff --git a/contracts/cw20-staked-balance-voting/src/contract.rs b/contracts/cw20-staked-balance-voting/src/contract.rs
index bbafdda7..7ccf250c 100644
--- a/contracts/cw20-staked-balance-voting/src/contract.rs
+++ b/contracts/cw20-staked-balance-voting/src/contract.rs
@@ -70,9 +70,10 @@ pub fn instantiate(
                         admin: Some(info.sender.to_string()),
                         label: env.contract.address.to_string(),
                         msg: to_binary(&stake_cw20::msg::InstantiateMsg {
-                            admin: Some(info.sender.to_string()),
+                            owner: Some(info.sender.to_string()),
                             unstaking_duration,
                             token_address: address.to_string(),
+                            manager: None,
                         })?,
                     };
                     let msg = SubMsg::reply_on_success(msg, INSTANTIATE_STAKING_REPLY_ID);
@@ -251,9 +252,10 @@ pub fn reply(deps: DepsMut, env: Env, msg: Reply) -> Result<Response, ContractEr
                         admin: Some(dao.to_string()),
                         label: env.contract.address.to_string(),
                         msg: to_binary(&stake_cw20::msg::InstantiateMsg {
-                            admin: Some(dao.to_string()),
+                            owner: Some(dao.to_string()),
                             unstaking_duration,
                             token_address: token.to_string(),
+                            manager: None,
                         })?,
                     };
                     let msg = SubMsg::reply_on_success(msg, INSTANTIATE_STAKING_REPLY_ID);
diff --git a/contracts/cw3-dao/schema/proposal_list_response.json b/contracts/cw3-dao/schema/proposal_list_response.json
index 81d531cf..0b0a36b7 100644
--- a/contracts/cw3-dao/schema/proposal_list_response.json
+++ b/contracts/cw3-dao/schema/proposal_list_response.json
@@ -271,6 +271,7 @@
         "id",
         "msgs",
         "proposer",
+        "start_height",
         "status",
         "threshold",
         "title"
@@ -299,6 +300,12 @@
         "proposer": {
           "$ref": "#/definitions/Addr"
         },
+        "start_height": {
+          "description": "The block height the proposal was created at. This can be cross referenced with staked_balance_at_height queries to determine an addresses's voting power for this proposal.",
+          "type": "integer",
+          "format": "uint64",
+          "minimum": 0.0
+        },
         "status": {
           "$ref": "#/definitions/Status"
         },
diff --git a/contracts/cw3-dao/schema/proposal_response.json b/contracts/cw3-dao/schema/proposal_response.json
index 7d65e22a..3802099b 100644
--- a/contracts/cw3-dao/schema/proposal_response.json
+++ b/contracts/cw3-dao/schema/proposal_response.json
@@ -10,6 +10,7 @@
     "id",
     "msgs",
     "proposer",
+    "start_height",
     "status",
     "threshold",
     "title"
@@ -38,6 +39,12 @@
     "proposer": {
       "$ref": "#/definitions/Addr"
     },
+    "start_height": {
+      "description": "The block height the proposal was created at. This can be cross referenced with staked_balance_at_height queries to determine an addresses's voting power for this proposal.",
+      "type": "integer",
+      "format": "uint64",
+      "minimum": 0.0
+    },
     "status": {
       "$ref": "#/definitions/Status"
     },
diff --git a/contracts/cw3-dao/src/contract.rs b/contracts/cw3-dao/src/contract.rs
index 9ab780b1..c34e7818 100644
--- a/contracts/cw3-dao/src/contract.rs
+++ b/contracts/cw3-dao/src/contract.rs
@@ -3,7 +3,9 @@ use crate::helpers::{
     get_and_check_limit, get_deposit_message, get_proposal_deposit_refund_message,
     get_staked_balance, get_total_staked_supply, get_voting_power_at_height, map_proposal,
 };
-use crate::msg::{ExecuteMsg, GovTokenMsg, InstantiateMsg, ProposeMsg, QueryMsg, VoteMsg};
+use crate::msg::{
+    ExecuteMsg, GovTokenMsg, InstantiateMsg, ProposeMsg, QueryMsg, StakingContractMsg, VoteMsg,
+};
 use crate::query::{
     ConfigResponse, Cw20BalancesResponse, ProposalListResponse, ProposalResponse,
     ThresholdResponse, TokenListResponse, VoteInfo, VoteListResponse, VoteResponse,
@@ -11,8 +13,7 @@ use crate::query::{
 };
 use crate::state::{
     next_id, Ballot, Config, Proposal, Votes, BALLOTS, CONFIG, DAO_PAUSED, GOV_TOKEN, PROPOSALS,
-    STAKING_CONTRACT, STAKING_CONTRACT_CODE_ID, STAKING_CONTRACT_UNSTAKING_DURATION,
-    TREASURY_TOKENS,
+    STAKING_CONTRACT, STAKING_CONTRACT_DETAILS, TREASURY_TOKENS,
 };
 use cosmwasm_std::{
     entry_point, to_binary, Addr, Binary, CosmosMsg, Decimal, Deps, DepsMut, Empty, Env,
@@ -67,14 +68,14 @@ pub fn instantiate(
 
     let mut msgs: Vec<SubMsg> = vec![];
 
+    let staking_contract = msg.staking_contract;
+
     match msg.gov_token {
         GovTokenMsg::InstantiateNewCw20 {
             cw20_code_id,
-            stake_contract_code_id,
             label,
             initial_dao_balance,
             msg,
-            unstaking_duration,
         } => {
             // Check that someone has an initial balance to be able to vote in the DAO
             if msg.initial_balances.is_empty() {
@@ -92,8 +93,8 @@ pub fn instantiate(
             }
 
             // Save info for use in reply SubMsgs
-            STAKING_CONTRACT_CODE_ID.save(deps.storage, &stake_contract_code_id)?;
-            STAKING_CONTRACT_UNSTAKING_DURATION.save(deps.storage, &unstaking_duration)?;
+
+            STAKING_CONTRACT_DETAILS.save(deps.storage, &staking_contract)?;
 
             // Instantiate new Gov Token with DAO as admin and minter
             let msg = WasmMsg::Instantiate {
@@ -118,12 +119,7 @@ pub fn instantiate(
 
             msgs.append(&mut vec![msg]);
         }
-        GovTokenMsg::UseExistingCw20 {
-            addr,
-            stake_contract_code_id,
-            label,
-            unstaking_duration,
-        } => {
+        GovTokenMsg::UseExistingCw20 { addr, label } => {
             let cw20_addr = Cw20Contract(
                 deps.api
                     .addr_validate(&addr)
@@ -136,22 +132,44 @@ pub fn instantiate(
             // Save gov token
             GOV_TOKEN.save(deps.storage, &cw20_addr.addr())?;
 
-            // Instantiate staking contract with DAO as admin
-            let msg = WasmMsg::Instantiate {
-                code_id: stake_contract_code_id,
-                funds: vec![],
-                admin: Some(env.contract.address.to_string()),
-                label,
-                msg: to_binary(&stake_cw20::msg::InstantiateMsg {
-                    admin: Some(env.contract.address.to_string()),
+            match staking_contract {
+                StakingContractMsg::InstantiateNewStakingContract {
+                    staking_contract_code_id,
                     unstaking_duration,
-                    token_address: cw20_addr.addr().to_string(),
-                })?,
-            };
+                } => {
+                    let msg = WasmMsg::Instantiate {
+                        code_id: staking_contract_code_id,
+                        funds: vec![],
+                        admin: Some(env.contract.address.to_string()),
+                        label,
+                        msg: to_binary(&stake_cw20::msg::InstantiateMsg {
+                            owner: Some(env.contract.address.to_string()),
+                            manager: None,
+                            unstaking_duration,
+                            token_address: cw20_addr.addr().to_string(),
+                        })?,
+                    };
+                    let msg = SubMsg::reply_on_success(msg, INSTANTIATE_STAKING_CONTRACT_REPLY_ID);
 
-            let msg = SubMsg::reply_on_success(msg, INSTANTIATE_STAKING_CONTRACT_REPLY_ID);
+                    msgs.append(&mut vec![msg]);
+                }
+                StakingContractMsg::UseExistingStakingContract { addr } => {
+                    // Validate the address
+                    let staking_contract_addr = deps.api.addr_validate(&addr)?;
 
-            msgs.append(&mut vec![msg]);
+                    let resp: stake_cw20::msg::GetConfigResponse = deps.querier.query_wasm_smart(
+                        &staking_contract_addr,
+                        &stake_cw20::msg::QueryMsg::GetConfig {},
+                    )?;
+
+                    if cw20_addr.addr() != resp.token_address {
+                        return Err(ContractError::StakingContractMismatch {});
+                    }
+
+                    // Save the validated address
+                    STAKING_CONTRACT.save(deps.storage, &staking_contract_addr)?;
+                }
+            }
         }
     };
 
@@ -763,24 +781,36 @@ pub fn reply(deps: DepsMut, env: Env, msg: Reply) -> Result<Response, ContractEr
                     // Save gov token
                     GOV_TOKEN.save(deps.storage, &cw20_addr)?;
 
-                    // Instantiate staking contract with DAO as admin
-                    let code_id = STAKING_CONTRACT_CODE_ID.load(deps.storage)?;
-                    let unstaking_duration =
-                        STAKING_CONTRACT_UNSTAKING_DURATION.load(deps.storage)?;
-                    let msg = WasmMsg::Instantiate {
-                        code_id,
-                        funds: vec![],
-                        admin: Some(env.contract.address.to_string()),
-                        label: env.contract.address.to_string(),
-                        msg: to_binary(&stake_cw20::msg::InstantiateMsg {
-                            admin: Some(env.contract.address.to_string()),
+                    // Load staking contract details
+                    let staking_contract = STAKING_CONTRACT_DETAILS.load(deps.storage)?;
+                    match staking_contract {
+                        // Create a new staking contract
+                        StakingContractMsg::InstantiateNewStakingContract {
+                            staking_contract_code_id,
                             unstaking_duration,
-                            token_address: cw20_addr.to_string(),
-                        })?,
-                    };
-                    let msg = SubMsg::reply_on_success(msg, INSTANTIATE_STAKING_CONTRACT_REPLY_ID);
-
-                    Ok(Response::new().add_submessage(msg))
+                        } => {
+                            let msg = WasmMsg::Instantiate {
+                                code_id: staking_contract_code_id,
+                                funds: vec![],
+                                admin: Some(env.contract.address.to_string()),
+                                label: env.contract.address.to_string(),
+                                msg: to_binary(&stake_cw20::msg::InstantiateMsg {
+                                    owner: Some(env.contract.address.to_string()),
+                                    manager: None,
+                                    unstaking_duration,
+                                    token_address: cw20_addr.to_string(),
+                                })?,
+                            };
+                            let msg = SubMsg::reply_on_success(
+                                msg,
+                                INSTANTIATE_STAKING_CONTRACT_REPLY_ID,
+                            );
+                            Ok(Response::new().add_submessage(msg))
+                        }
+                        StakingContractMsg::UseExistingStakingContract { addr: _addr } => {
+                            Err(ContractError::CannotUseExistingStakingContract {})
+                        }
+                    }
                 }
                 Err(_) => Err(ContractError::InstantiateGovTokenError {}),
             }
@@ -792,7 +822,7 @@ pub fn reply(deps: DepsMut, env: Env, msg: Reply) -> Result<Response, ContractEr
                     // Validate contract address
                     let staking_contract_addr = deps.api.addr_validate(&res.contract_address)?;
 
-                    // Save gov token
+                    // Save staking contract addr
                     STAKING_CONTRACT.save(deps.storage, &staking_contract_addr)?;
 
                     Ok(Response::new())
diff --git a/contracts/cw3-dao/src/error.rs b/contracts/cw3-dao/src/error.rs
index 43b9c777..5077f0d0 100644
--- a/contracts/cw3-dao/src/error.rs
+++ b/contracts/cw3-dao/src/error.rs
@@ -53,4 +53,10 @@ pub enum ContractError {
 
     #[error("DAO is paused")]
     Paused {},
+
+    #[error("Cannot use an existing staking contract with a new CW20")]
+    CannotUseExistingStakingContract {},
+
+    #[error("Staking contract CW20 and DAO CW20 do not match")]
+    StakingContractMismatch {},
 }
diff --git a/contracts/cw3-dao/src/msg.rs b/contracts/cw3-dao/src/msg.rs
index 5a01606a..264f0a63 100644
--- a/contracts/cw3-dao/src/msg.rs
+++ b/contracts/cw3-dao/src/msg.rs
@@ -17,6 +17,8 @@ pub struct InstantiateMsg {
     pub description: String,
     /// Set an existing governance token or launch a new one
     pub gov_token: GovTokenMsg,
+    /// Set an existing staking contract or instantiate an new one
+    pub staking_contract: StakingContractMsg,
     /// Voting params configuration
     pub threshold: Threshold,
     /// The amount of time a proposal can be voted on before expiring
@@ -38,19 +40,25 @@ pub enum GovTokenMsg {
     // Instantiate a new cw20 token with the DAO as minter
     InstantiateNewCw20 {
         cw20_code_id: u64,
-        stake_contract_code_id: u64,
         label: String,
         initial_dao_balance: Option<Uint128>,
         msg: GovTokenInstantiateMsg,
-        unstaking_duration: Option<Duration>,
     },
     /// Use an existing cw20 token
-    UseExistingCw20 {
-        addr: String,
-        label: String,
-        stake_contract_code_id: u64,
+    UseExistingCw20 { addr: String, label: String },
+}
+
+#[derive(Serialize, Deserialize, Clone, PartialEq, JsonSchema, Debug)]
+#[serde(rename_all = "snake_case")]
+#[allow(clippy::large_enum_variant)]
+pub enum StakingContractMsg {
+    /// Create a new staking contract
+    InstantiateNewStakingContract {
+        staking_contract_code_id: u64,
         unstaking_duration: Option<Duration>,
     },
+    /// Use an existing already instantiated staking contract
+    UseExistingStakingContract { addr: String },
 }
 
 #[derive(Serialize, Deserialize, JsonSchema, Debug, Clone, PartialEq)]
diff --git a/contracts/cw3-dao/src/state.rs b/contracts/cw3-dao/src/state.rs
index 9d4dc818..1fddb3de 100644
--- a/contracts/cw3-dao/src/state.rs
+++ b/contracts/cw3-dao/src/state.rs
@@ -1,4 +1,4 @@
-use crate::msg::Threshold;
+use crate::msg::{StakingContractMsg, Threshold};
 use cosmwasm_std::{
     Addr, BlockInfo, CosmosMsg, Decimal, Empty, StdError, StdResult, Storage, Uint128,
 };
@@ -180,9 +180,8 @@ pub const STAKING_CONTRACT: Item<Addr> = Item::new("staking_contract");
 pub const GOV_TOKEN: Item<Addr> = Item::new("gov_token");
 
 // Stores staking contract CODE ID and Unbonding time for use in a reply
-pub const STAKING_CONTRACT_CODE_ID: Item<u64> = Item::new("staking_contract_code_id");
-pub const STAKING_CONTRACT_UNSTAKING_DURATION: Item<Option<Duration>> =
-    Item::new("staking_contract_unstaking_duration");
+pub const STAKING_CONTRACT_DETAILS: Item<StakingContractMsg> =
+    Item::new("staking_contract_details");
 
 // Multiple-item map
 pub const BALLOTS: Map<(u64, &Addr), Ballot> = Map::new("votes");
diff --git a/contracts/stake-cw20/examples/schema.rs b/contracts/stake-cw20/examples/schema.rs
index 65fdd74d..bf77c2c8 100644
--- a/contracts/stake-cw20/examples/schema.rs
+++ b/contracts/stake-cw20/examples/schema.rs
@@ -8,7 +8,7 @@ use cw20::{
     TokenInfoResponse,
 };
 use stake_cw20::msg::{
-    ClaimsResponse, ExecuteMsg, GetConfigResponse, InstantiateMsg, QueryMsg,
+    ClaimsResponse, ExecuteMsg, GetConfigResponse, GetHooksResponse, InstantiateMsg, QueryMsg,
     StakedBalanceAtHeightResponse, StakedValueResponse, TotalStakedAtHeightResponse,
     TotalValueResponse,
 };
@@ -27,6 +27,7 @@ fn main() {
     export_schema(&schema_for!(StakedValueResponse), &out_dir);
     export_schema(&schema_for!(TotalValueResponse), &out_dir);
     export_schema(&schema_for!(GetConfigResponse), &out_dir);
+    export_schema(&schema_for!(GetHooksResponse), &out_dir);
     export_schema(&schema_for!(ClaimsResponse), &out_dir);
     export_schema(&schema_for!(AllowanceResponse), &out_dir);
     export_schema(&schema_for!(BalanceResponse), &out_dir);
diff --git a/contracts/stake-cw20/schema/execute_msg.json b/contracts/stake-cw20/schema/execute_msg.json
index 4476cfb4..9ba41e93 100644
--- a/contracts/stake-cw20/schema/execute_msg.json
+++ b/contracts/stake-cw20/schema/execute_msg.json
@@ -55,16 +55,6 @@
         "update_config": {
           "type": "object",
           "properties": {
-            "admin": {
-              "anyOf": [
-                {
-                  "$ref": "#/definitions/Addr"
-                },
-                {
-                  "type": "null"
-                }
-              ]
-            },
             "duration": {
               "anyOf": [
                 {
@@ -74,6 +64,58 @@
                   "type": "null"
                 }
               ]
+            },
+            "manager": {
+              "type": [
+                "string",
+                "null"
+              ]
+            },
+            "owner": {
+              "type": [
+                "string",
+                "null"
+              ]
+            }
+          }
+        }
+      },
+      "additionalProperties": false
+    },
+    {
+      "type": "object",
+      "required": [
+        "add_hook"
+      ],
+      "properties": {
+        "add_hook": {
+          "type": "object",
+          "required": [
+            "addr"
+          ],
+          "properties": {
+            "addr": {
+              "type": "string"
+            }
+          }
+        }
+      },
+      "additionalProperties": false
+    },
+    {
+      "type": "object",
+      "required": [
+        "remove_hook"
+      ],
+      "properties": {
+        "remove_hook": {
+          "type": "object",
+          "required": [
+            "addr"
+          ],
+          "properties": {
+            "addr": {
+              "type": "string"
             }
           }
         }
@@ -82,10 +124,6 @@
     }
   ],
   "definitions": {
-    "Addr": {
-      "description": "A human readable address.\n\nIn Cosmos, this is typically bech32 encoded. But for multi-chain smart contracts no assumptions should be made other than being UTF-8 encoded and of reasonable length.\n\nThis type represents a validated address. It can be created in the following ways 1. Use `Addr::unchecked(input)` 2. Use `let checked: Addr = deps.api.addr_validate(input)?` 3. Use `let checked: Addr = deps.api.addr_humanize(canonical_addr)?` 4. Deserialize from JSON. This must only be done from JSON that was validated before such as a contract's state. `Addr` must not be used in messages sent by the user because this would result in unvalidated instances.\n\nThis type is immutable. If you really need to mutate it (Really? Are you sure?), create a mutable copy using `let mut mutable = Addr::to_string()` and operate on that `String` instance.",
-      "type": "string"
-    },
     "Binary": {
       "description": "Binary is a wrapper around Vec<u8> to add base64 de/serialization with serde. It also adds some helper methods to help encode inline.\n\nThis is only needed as serde-json-{core,wasm} has a horrible encoding for Vec<u8>",
       "type": "string"
diff --git a/contracts/stake-cw20/schema/get_config_response.json b/contracts/stake-cw20/schema/get_config_response.json
index 1f1817a8..c673bbf0 100644
--- a/contracts/stake-cw20/schema/get_config_response.json
+++ b/contracts/stake-cw20/schema/get_config_response.json
@@ -6,18 +6,20 @@
     "token_address"
   ],
   "properties": {
-    "admin": {
-      "anyOf": [
-        {
-          "$ref": "#/definitions/Addr"
-        },
-        {
-          "type": "null"
-        }
+    "manager": {
+      "type": [
+        "string",
+        "null"
+      ]
+    },
+    "owner": {
+      "type": [
+        "string",
+        "null"
       ]
     },
     "token_address": {
-      "$ref": "#/definitions/Addr"
+      "type": "string"
     },
     "unstaking_duration": {
       "anyOf": [
@@ -31,10 +33,6 @@
     }
   },
   "definitions": {
-    "Addr": {
-      "description": "A human readable address.\n\nIn Cosmos, this is typically bech32 encoded. But for multi-chain smart contracts no assumptions should be made other than being UTF-8 encoded and of reasonable length.\n\nThis type represents a validated address. It can be created in the following ways 1. Use `Addr::unchecked(input)` 2. Use `let checked: Addr = deps.api.addr_validate(input)?` 3. Use `let checked: Addr = deps.api.addr_humanize(canonical_addr)?` 4. Deserialize from JSON. This must only be done from JSON that was validated before such as a contract's state. `Addr` must not be used in messages sent by the user because this would result in unvalidated instances.\n\nThis type is immutable. If you really need to mutate it (Really? Are you sure?), create a mutable copy using `let mut mutable = Addr::to_string()` and operate on that `String` instance.",
-      "type": "string"
-    },
     "Duration": {
       "description": "Duration is a delta of time. You can add it to a BlockInfo or Expiration to move that further in the future. Note that an height-based Duration and a time-based Expiration cannot be combined",
       "oneOf": [
diff --git a/contracts/stake-cw20/schema/get_hooks_response.json b/contracts/stake-cw20/schema/get_hooks_response.json
new file mode 100644
index 00000000..96bf4c56
--- /dev/null
+++ b/contracts/stake-cw20/schema/get_hooks_response.json
@@ -0,0 +1,16 @@
+{
+  "$schema": "http://json-schema.org/draft-07/schema#",
+  "title": "GetHooksResponse",
+  "type": "object",
+  "required": [
+    "hooks"
+  ],
+  "properties": {
+    "hooks": {
+      "type": "array",
+      "items": {
+        "type": "string"
+      }
+    }
+  }
+}
diff --git a/contracts/stake-cw20/schema/instantiate_msg.json b/contracts/stake-cw20/schema/instantiate_msg.json
index 8e053696..9543aeeb 100644
--- a/contracts/stake-cw20/schema/instantiate_msg.json
+++ b/contracts/stake-cw20/schema/instantiate_msg.json
@@ -6,18 +6,20 @@
     "token_address"
   ],
   "properties": {
-    "admin": {
-      "anyOf": [
-        {
-          "$ref": "#/definitions/Addr"
-        },
-        {
-          "type": "null"
-        }
+    "manager": {
+      "type": [
+        "string",
+        "null"
+      ]
+    },
+    "owner": {
+      "type": [
+        "string",
+        "null"
       ]
     },
     "token_address": {
-      "$ref": "#/definitions/Addr"
+      "type": "string"
     },
     "unstaking_duration": {
       "anyOf": [
@@ -31,10 +33,6 @@
     }
   },
   "definitions": {
-    "Addr": {
-      "description": "A human readable address.\n\nIn Cosmos, this is typically bech32 encoded. But for multi-chain smart contracts no assumptions should be made other than being UTF-8 encoded and of reasonable length.\n\nThis type represents a validated address. It can be created in the following ways 1. Use `Addr::unchecked(input)` 2. Use `let checked: Addr = deps.api.addr_validate(input)?` 3. Use `let checked: Addr = deps.api.addr_humanize(canonical_addr)?` 4. Deserialize from JSON. This must only be done from JSON that was validated before such as a contract's state. `Addr` must not be used in messages sent by the user because this would result in unvalidated instances.\n\nThis type is immutable. If you really need to mutate it (Really? Are you sure?), create a mutable copy using `let mut mutable = Addr::to_string()` and operate on that `String` instance.",
-      "type": "string"
-    },
     "Duration": {
       "description": "Duration is a delta of time. You can add it to a BlockInfo or Expiration to move that further in the future. Note that an height-based Duration and a time-based Expiration cannot be combined",
       "oneOf": [
diff --git a/contracts/stake-cw20/schema/query_msg.json b/contracts/stake-cw20/schema/query_msg.json
index b735b7f0..60ae2172 100644
--- a/contracts/stake-cw20/schema/query_msg.json
+++ b/contracts/stake-cw20/schema/query_msg.json
@@ -115,6 +115,18 @@
         }
       },
       "additionalProperties": false
+    },
+    {
+      "type": "object",
+      "required": [
+        "get_hooks"
+      ],
+      "properties": {
+        "get_hooks": {
+          "type": "object"
+        }
+      },
+      "additionalProperties": false
     }
   ]
 }
diff --git a/contracts/stake-cw20/src/contract.rs b/contracts/stake-cw20/src/contract.rs
index 65db79b3..4d4e9227 100644
--- a/contracts/stake-cw20/src/contract.rs
+++ b/contracts/stake-cw20/src/contract.rs
@@ -8,12 +8,15 @@ use cosmwasm_std::{
 
 use cw20::Cw20ReceiveMsg;
 
+use crate::hooks::{stake_hook_msgs, unstake_hook_msgs};
 use crate::msg::{
-    ExecuteMsg, GetConfigResponse, InstantiateMsg, QueryMsg, ReceiveMsg,
+    ExecuteMsg, GetConfigResponse, GetHooksResponse, InstantiateMsg, QueryMsg, ReceiveMsg,
     StakedBalanceAtHeightResponse, StakedValueResponse, TotalStakedAtHeightResponse,
     TotalValueResponse,
 };
-use crate::state::{Config, BALANCE, CLAIMS, CONFIG, MAX_CLAIMS, STAKED_BALANCES, STAKED_TOTAL};
+use crate::state::{
+    Config, BALANCE, CLAIMS, CONFIG, HOOKS, MAX_CLAIMS, STAKED_BALANCES, STAKED_TOTAL,
+};
 use crate::ContractError;
 use cw2::set_contract_version;
 pub use cw20_base::allowances::{
@@ -39,15 +42,20 @@ pub fn instantiate(
     _info: MessageInfo,
     msg: InstantiateMsg,
 ) -> Result<Response<Empty>, ContractError> {
-    let admin = match msg.admin {
-        Some(admin) => Some(deps.api.addr_validate(admin.as_str())?),
+    let owner = match msg.owner {
+        Some(owner) => Some(deps.api.addr_validate(owner.as_str())?),
+        None => None,
+    };
+
+    let manager = match msg.manager {
+        Some(manager) => Some(deps.api.addr_validate(manager.as_str())?),
         None => None,
     };
 
-    let token_address = deps.api.addr_validate(&msg.token_address)?;
     let config = Config {
-        admin,
-        token_address,
+        owner,
+        manager,
+        token_address: deps.api.addr_validate(&*msg.token_address)?,
         unstaking_duration: msg.unstaking_duration,
     };
     CONFIG.save(deps.storage, &config)?;
@@ -67,42 +75,59 @@ pub fn execute(
         ExecuteMsg::Receive(msg) => execute_receive(deps, env, info, msg),
         ExecuteMsg::Unstake { amount } => execute_unstake(deps, env, info, amount),
         ExecuteMsg::Claim {} => execute_claim(deps, env, info),
-        ExecuteMsg::UpdateConfig { admin, duration } => {
-            execute_update_config(info, deps, admin, duration)
-        }
+        ExecuteMsg::UpdateConfig {
+            owner,
+            manager,
+            duration,
+        } => execute_update_config(info, deps, owner, manager, duration),
+        ExecuteMsg::AddHook { addr } => execute_add_hook(deps, env, info, addr),
+        ExecuteMsg::RemoveHook { addr } => execute_remove_hook(deps, env, info, addr),
     }
 }
 
 pub fn execute_update_config(
     info: MessageInfo,
     deps: DepsMut,
-    new_admin: Option<String>,
+    new_owner: Option<String>,
+    new_manager: Option<String>,
     duration: Option<Duration>,
 ) -> Result<Response, ContractError> {
+    let new_owner = new_owner
+        .map(|new_owner| deps.api.addr_validate(&*new_owner))
+        .transpose()?;
+    let new_manager = new_manager
+        .map(|new_manager| deps.api.addr_validate(&*new_manager))
+        .transpose()?;
     let mut config: Config = CONFIG.load(deps.storage)?;
-    match config.admin {
-        None => Err(ContractError::NoAdminConfigured {}),
-        Some(current_admin) => {
-            if info.sender != current_admin {
-                return Err(ContractError::Unauthorized {
-                    expected: current_admin,
-                    received: info.sender,
-                });
-            }
+    if Some(info.sender.clone()) != config.owner && Some(info.sender.clone()) != config.manager {
+        return Err(ContractError::Unauthorized {});
+    };
+    if Some(info.sender) != config.owner && new_owner != config.owner {
+        return Err(ContractError::OnlyOwnerCanChangeOwner {});
+    };
 
-            config.admin = new_admin.map(|a| deps.api.addr_validate(&a)).transpose()?;
-            config.unstaking_duration = duration;
-
-            CONFIG.save(deps.storage, &config)?;
-            Ok(Response::new().add_attribute(
-                "admin",
-                config
-                    .admin
-                    .map(|a| a.to_string())
-                    .unwrap_or_else(|| "None".to_string()),
-            ))
-        }
-    }
+    config.owner = new_owner;
+    config.manager = new_manager;
+
+    config.unstaking_duration = duration;
+
+    CONFIG.save(deps.storage, &config)?;
+    Ok(Response::new()
+        .add_attribute("action", "update_config")
+        .add_attribute(
+            "owner",
+            config
+                .owner
+                .map(|a| a.to_string())
+                .unwrap_or_else(|| "None".to_string()),
+        )
+        .add_attribute(
+            "manager",
+            config
+                .manager
+                .map(|a| a.to_string())
+                .unwrap_or_else(|| "None".to_string()),
+        ))
 }
 
 pub fn execute_receive(
@@ -121,7 +146,7 @@ pub fn execute_receive(
     let msg: ReceiveMsg = from_binary(&wrapper.msg)?;
     let sender = deps.api.addr_validate(&wrapper.sender)?;
     match msg {
-        ReceiveMsg::Stake {} => execute_stake(deps, env, &sender, wrapper.amount),
+        ReceiveMsg::Stake {} => execute_stake(deps, env, sender, wrapper.amount),
         ReceiveMsg::Fund {} => execute_fund(deps, env, &sender, wrapper.amount),
     }
 }
@@ -129,7 +154,7 @@ pub fn execute_receive(
 pub fn execute_stake(
     deps: DepsMut,
     env: Env,
-    sender: &Addr,
+    sender: Addr,
     amount: Uint128,
 ) -> Result<Response, ContractError> {
     let balance = BALANCE.load(deps.storage).unwrap_or_default();
@@ -145,7 +170,7 @@ pub fn execute_stake(
     };
     STAKED_BALANCES.update(
         deps.storage,
-        sender,
+        &sender,
         env.block.height,
         |bal| -> StdResult<Uint128> { Ok(bal.unwrap_or_default().checked_add(amount_to_stake)?) },
     )?;
@@ -160,7 +185,9 @@ pub fn execute_stake(
         deps.storage,
         &balance.checked_add(amount).map_err(StdError::overflow)?,
     )?;
+    let hook_msgs = stake_hook_msgs(deps.storage, sender.clone(), amount_to_stake)?;
     Ok(Response::new()
+        .add_submessages(hook_msgs)
         .add_attribute("action", "stake")
         .add_attribute("from", sender)
         .add_attribute("amount", amount))
@@ -197,6 +224,7 @@ pub fn execute_unstake(
             .checked_sub(amount_to_claim)
             .map_err(StdError::overflow)?,
     )?;
+    let hook_msgs = unstake_hook_msgs(deps.storage, info.sender.clone(), amount)?;
     match config.unstaking_duration {
         None => {
             let cw_send_msg = cw20::Cw20ExecuteMsg::Transfer {
@@ -210,6 +238,7 @@ pub fn execute_unstake(
             };
             Ok(Response::new()
                 .add_message(wasm_msg)
+                .add_submessages(hook_msgs)
                 .add_attribute("action", "unstake")
                 .add_attribute("from", info.sender)
                 .add_attribute("amount", amount)
@@ -229,6 +258,7 @@ pub fn execute_unstake(
             )?;
             Ok(Response::new()
                 .add_attribute("action", "unstake")
+                .add_submessages(hook_msgs)
                 .add_attribute("from", info.sender)
                 .add_attribute("amount", amount)
                 .add_attribute("claim_duration", format!("{}", duration)))
@@ -279,6 +309,40 @@ pub fn execute_fund(
         .add_attribute("amount", amount))
 }
 
+pub fn execute_add_hook(
+    deps: DepsMut,
+    _env: Env,
+    info: MessageInfo,
+    addr: String,
+) -> Result<Response, ContractError> {
+    let addr = deps.api.addr_validate(&addr)?;
+    let config: Config = CONFIG.load(deps.storage)?;
+    if config.owner != Some(info.sender.clone()) && config.manager != Some(info.sender) {
+        return Err(ContractError::Unauthorized {});
+    };
+    HOOKS.add_hook(deps.storage, addr.clone())?;
+    Ok(Response::new()
+        .add_attribute("action", "add_hook")
+        .add_attribute("hook", addr))
+}
+
+pub fn execute_remove_hook(
+    deps: DepsMut,
+    _env: Env,
+    info: MessageInfo,
+    addr: String,
+) -> Result<Response, ContractError> {
+    let addr = deps.api.addr_validate(&addr)?;
+    let config: Config = CONFIG.load(deps.storage)?;
+    if config.owner != Some(info.sender.clone()) && config.manager != Some(info.sender) {
+        return Err(ContractError::Unauthorized {});
+    };
+    HOOKS.remove_hook(deps.storage, addr.clone())?;
+    Ok(Response::new()
+        .add_attribute("action", "remove_hook")
+        .add_attribute("hook", addr))
+}
+
 #[cfg_attr(not(feature = "library"), entry_point)]
 pub fn query(deps: Deps, env: Env, msg: QueryMsg) -> StdResult<Binary> {
     match msg {
@@ -292,6 +356,7 @@ pub fn query(deps: Deps, env: Env, msg: QueryMsg) -> StdResult<Binary> {
         QueryMsg::StakedValue { address } => to_binary(&query_staked_value(deps, env, address)?),
         QueryMsg::TotalValue {} => to_binary(&query_total_value(deps, env)?),
         QueryMsg::Claims { address } => to_binary(&query_claims(deps, address)?),
+        QueryMsg::GetHooks {} => to_binary(&query_hooks(deps)?),
     }
 }
 
@@ -354,9 +419,10 @@ pub fn query_total_value(deps: Deps, _env: Env) -> StdResult<TotalValueResponse>
 pub fn query_config(deps: Deps) -> StdResult<GetConfigResponse> {
     let config = CONFIG.load(deps.storage)?;
     Ok(GetConfigResponse {
-        admin: config.admin,
+        owner: config.owner.map(|a| a.to_string()),
+        manager: config.manager.map(|a| a.to_string()),
         unstaking_duration: config.unstaking_duration,
-        token_address: config.token_address,
+        token_address: config.token_address.to_string(),
     })
 }
 
@@ -364,6 +430,12 @@ pub fn query_claims(deps: Deps, address: String) -> StdResult<ClaimsResponse> {
     CLAIMS.query_claims(deps, &deps.api.addr_validate(&address)?)
 }
 
+pub fn query_hooks(deps: Deps) -> StdResult<GetHooksResponse> {
+    Ok(GetHooksResponse {
+        hooks: HOOKS.query_hooks(deps)?.hooks,
+    })
+}
+
 #[cfg(test)]
 mod tests {
     use std::borrow::BorrowMut;
@@ -382,6 +454,7 @@ mod tests {
     use cw_multi_test::{next_block, App, AppResponse, Contract, ContractWrapper, Executor};
 
     use anyhow::Result as AnyResult;
+
     use cw_controllers::{Claim, ClaimsResponse};
     use cw_utils::Expiration::AtHeight;
 
@@ -447,7 +520,8 @@ mod tests {
     ) -> Addr {
         let staking_code_id = app.store_code(contract_staking());
         let msg = crate::msg::InstantiateMsg {
-            admin: Some("owner".to_string()),
+            owner: Some("owner".to_string()),
+            manager: Some("manager".to_string()),
             token_address: cw20.to_string(),
             unstaking_duration,
         };
@@ -551,11 +625,13 @@ mod tests {
         app: &mut App,
         staking_addr: &Addr,
         info: MessageInfo,
-        admin: Option<Addr>,
+        owner: Option<Addr>,
+        manager: Option<Addr>,
         duration: Option<Duration>,
     ) -> AnyResult<AppResponse> {
         let msg = ExecuteMsg::UpdateConfig {
-            admin: admin.map(|a| a.to_string()),
+            owner: owner.map(|a| a.to_string()),
+            manager: manager.map(|a| a.to_string()),
             duration,
         };
         app.execute_contract(info.sender, staking_addr.clone(), &msg, &[])
@@ -601,34 +677,99 @@ mod tests {
             &staking_addr,
             info,
             Some(Addr::unchecked("owner2")),
+            None,
             Some(Duration::Height(100)),
         )
         .unwrap();
 
         let config = query_config(&app, &staking_addr);
-        assert_eq!(config.admin, Some(Addr::unchecked("owner2")));
+        assert_eq!(config.owner, Some("owner2".to_string()));
         assert_eq!(config.unstaking_duration, Some(Duration::Height(100)));
 
-        // Try updating admin with original owner, which is now invalid
+        // Try updating owner with original owner, which is now invalid
         let info = mock_info("owner", &[]);
         let _err = update_config(
             &mut app,
             &staking_addr,
             info,
             Some(Addr::unchecked("owner3")),
+            None,
             Some(Duration::Height(100)),
         )
         .unwrap_err();
 
-        // Remove admin
+        // Add manager
+        let info = mock_info("owner2", &[]);
+        let _env = mock_env();
+        update_config(
+            &mut app,
+            &staking_addr,
+            info,
+            Some(Addr::unchecked("owner2")),
+            Some(Addr::unchecked("manager")),
+            Some(Duration::Height(100)),
+        )
+        .unwrap();
+
+        let config = query_config(&app, &staking_addr);
+        assert_eq!(config.owner, Some("owner2".to_string()));
+        assert_eq!(config.manager, Some("manager".to_string()));
+
+        // Manager can update unstaking duration
+        let info = mock_info("manager", &[]);
+        let _env = mock_env();
+        update_config(
+            &mut app,
+            &staking_addr,
+            info,
+            Some(Addr::unchecked("owner2")),
+            Some(Addr::unchecked("manager")),
+            Some(Duration::Height(50)),
+        )
+        .unwrap();
+        let config = query_config(&app, &staking_addr);
+        assert_eq!(config.owner, Some("owner2".to_string()));
+        assert_eq!(config.unstaking_duration, Some(Duration::Height(50)));
+
+        // Manager cannot update owner
+        let info = mock_info("manager", &[]);
+        let _env = mock_env();
+        update_config(
+            &mut app,
+            &staking_addr,
+            info,
+            Some(Addr::unchecked("manager")),
+            Some(Addr::unchecked("manager")),
+            Some(Duration::Height(50)),
+        )
+        .unwrap_err();
+
+        // Manager can update manager
+        let info = mock_info("owner2", &[]);
+        let _env = mock_env();
+        update_config(
+            &mut app,
+            &staking_addr,
+            info,
+            Some(Addr::unchecked("owner2")),
+            None,
+            Some(Duration::Height(50)),
+        )
+        .unwrap();
+
+        let config = query_config(&app, &staking_addr);
+        assert_eq!(config.owner, Some("owner2".to_string()));
+        assert_eq!(config.manager, None);
+
+        // Remove owner
         let info = mock_info("owner2", &[]);
         let _env = mock_env();
-        // Test update admin
         update_config(
             &mut app,
             &staking_addr,
             info,
             None,
+            None,
             Some(Duration::Height(100)),
         )
         .unwrap();
@@ -636,18 +777,33 @@ mod tests {
         // Assert no further updates can be made
         let info = mock_info("owner2", &[]);
         let _env = mock_env();
-        // Test update admin
         let err: ContractError = update_config(
             &mut app,
             &staking_addr,
             info,
             None,
+            None,
+            Some(Duration::Height(100)),
+        )
+        .unwrap_err()
+        .downcast()
+        .unwrap();
+        assert_eq!(err, ContractError::Unauthorized {});
+
+        let info = mock_info("manager", &[]);
+        let _env = mock_env();
+        let err: ContractError = update_config(
+            &mut app,
+            &staking_addr,
+            info,
+            None,
+            None,
             Some(Duration::Height(100)),
         )
         .unwrap_err()
         .downcast()
         .unwrap();
-        assert_eq!(err, ContractError::NoAdminConfigured {})
+        assert_eq!(err, ContractError::Unauthorized {})
     }
 
     #[test]
diff --git a/contracts/stake-cw20/src/error.rs b/contracts/stake-cw20/src/error.rs
index afc84712..98094e75 100644
--- a/contracts/stake-cw20/src/error.rs
+++ b/contracts/stake-cw20/src/error.rs
@@ -12,9 +12,13 @@ pub enum ContractError {
     #[error("Invalid token")]
     InvalidToken { received: Addr, expected: Addr },
     #[error("Unauthorized")]
-    Unauthorized { received: Addr, expected: Addr },
+    Unauthorized {},
     #[error("Too many outstanding claims. Claim some tokens before unstaking more.")]
     TooManyClaims {},
     #[error("No admin configured")]
     NoAdminConfigured {},
+    #[error("{0}")]
+    HookError(#[from] cw_controllers::HookError),
+    #[error("Only owner can change owner")]
+    OnlyOwnerCanChangeOwner {},
 }
diff --git a/contracts/stake-cw20/src/hooks.rs b/contracts/stake-cw20/src/hooks.rs
new file mode 100644
index 00000000..5a5e024e
--- /dev/null
+++ b/contracts/stake-cw20/src/hooks.rs
@@ -0,0 +1,55 @@
+use crate::state::HOOKS;
+use cosmwasm_std::{to_binary, Addr, StdResult, Storage, SubMsg, Uint128, WasmMsg};
+use schemars::JsonSchema;
+use serde::{Deserialize, Serialize};
+
+// This is just a helper to properly serialize the above message
+#[derive(Serialize, Deserialize, Clone, PartialEq, JsonSchema, Debug)]
+#[serde(rename_all = "snake_case")]
+pub enum StakeChangedHookMsg {
+    Stake { addr: Addr, amount: Uint128 },
+    Unstake { addr: Addr, amount: Uint128 },
+}
+
+pub fn stake_hook_msgs(
+    storage: &dyn Storage,
+    addr: Addr,
+    amount: Uint128,
+) -> StdResult<Vec<SubMsg>> {
+    let msg = to_binary(&StakeChangedExecuteMsg::StakeChangeHook(
+        StakeChangedHookMsg::Stake { addr, amount },
+    ))?;
+    HOOKS.prepare_hooks(storage, |a| {
+        let execute = WasmMsg::Execute {
+            contract_addr: a.to_string(),
+            msg: msg.clone(),
+            funds: vec![],
+        };
+        Ok(SubMsg::new(execute))
+    })
+}
+
+pub fn unstake_hook_msgs(
+    storage: &dyn Storage,
+    addr: Addr,
+    amount: Uint128,
+) -> StdResult<Vec<SubMsg>> {
+    let msg = to_binary(&StakeChangedExecuteMsg::StakeChangeHook(
+        StakeChangedHookMsg::Unstake { addr, amount },
+    ))?;
+    HOOKS.prepare_hooks(storage, |a| {
+        let execute = WasmMsg::Execute {
+            contract_addr: a.to_string(),
+            msg: msg.clone(),
+            funds: vec![],
+        };
+        Ok(SubMsg::new(execute))
+    })
+}
+
+// This is just a helper to properly serialize the above message
+#[derive(Serialize, Deserialize, Clone, PartialEq, JsonSchema, Debug)]
+#[serde(rename_all = "snake_case")]
+enum StakeChangedExecuteMsg {
+    StakeChangeHook(StakeChangedHookMsg),
+}
diff --git a/contracts/stake-cw20/src/lib.rs b/contracts/stake-cw20/src/lib.rs
index dfedc9dc..af953d2e 100644
--- a/contracts/stake-cw20/src/lib.rs
+++ b/contracts/stake-cw20/src/lib.rs
@@ -1,5 +1,6 @@
 pub mod contract;
 mod error;
+pub mod hooks;
 pub mod msg;
 pub mod state;
 
diff --git a/contracts/stake-cw20/src/msg.rs b/contracts/stake-cw20/src/msg.rs
index e0b65b18..affe2269 100644
--- a/contracts/stake-cw20/src/msg.rs
+++ b/contracts/stake-cw20/src/msg.rs
@@ -1,4 +1,4 @@
-use cosmwasm_std::{Addr, Uint128};
+use cosmwasm_std::Uint128;
 use cw20::Cw20ReceiveMsg;
 use schemars::JsonSchema;
 use serde::{Deserialize, Serialize};
@@ -9,7 +9,10 @@ pub use cw_controllers::ClaimsResponse;
 
 #[derive(Serialize, Deserialize, JsonSchema, Debug, Clone, PartialEq)]
 pub struct InstantiateMsg {
-    pub admin: Option<String>,
+    // Owner can update all configs including changing the owner. This will generally be a DAO.
+    pub owner: Option<String>,
+    // Manager can update all configs except changing the owner. This will generally be an operations multisig for a DAO.
+    pub manager: Option<String>,
     pub token_address: String,
     pub unstaking_duration: Option<Duration>,
 }
@@ -23,10 +26,18 @@ pub enum ExecuteMsg {
     },
     Claim {},
     UpdateConfig {
-        admin: Option<String>,
+        owner: Option<String>,
+        manager: Option<String>,
         duration: Option<Duration>,
     },
+    AddHook {
+        addr: String,
+    },
+    RemoveHook {
+        addr: String,
+    },
 }
+
 #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]
 #[serde(rename_all = "snake_case")]
 pub enum ReceiveMsg {
@@ -52,6 +63,7 @@ pub enum QueryMsg {
     Claims {
         address: String,
     },
+    GetHooks {},
 }
 
 #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]
@@ -83,7 +95,14 @@ pub struct TotalValueResponse {
 #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]
 #[serde(rename_all = "snake_case")]
 pub struct GetConfigResponse {
-    pub admin: Option<Addr>,
-    pub token_address: Addr,
+    pub owner: Option<String>,
+    pub manager: Option<String>,
+    pub token_address: String,
     pub unstaking_duration: Option<Duration>,
 }
+
+#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]
+#[serde(rename_all = "snake_case")]
+pub struct GetHooksResponse {
+    pub hooks: Vec<String>,
+}
diff --git a/contracts/stake-cw20/src/state.rs b/contracts/stake-cw20/src/state.rs
index 6d74e5ea..99230614 100644
--- a/contracts/stake-cw20/src/state.rs
+++ b/contracts/stake-cw20/src/state.rs
@@ -3,12 +3,14 @@ use serde::{Deserialize, Serialize};
 
 use cosmwasm_std::{Addr, Uint128};
 use cw_controllers::Claims;
+use cw_controllers::Hooks;
 use cw_storage_plus::{Item, SnapshotItem, SnapshotMap, Strategy};
 use cw_utils::Duration;
 
 #[derive(Serialize, Deserialize, Clone, PartialEq, JsonSchema, Debug)]
 pub struct Config {
-    pub admin: Option<Addr>,
+    pub owner: Option<Addr>,
+    pub manager: Option<Addr>,
     pub token_address: Addr,
     pub unstaking_duration: Option<Duration>,
 }
@@ -35,3 +37,6 @@ pub const MAX_CLAIMS: u64 = 100;
 pub const CLAIMS: Claims = Claims::new("claims");
 
 pub const BALANCE: Item<Uint128> = Item::new("balance");
+
+// Hooks to contracts that will receive staking and unstaking messages
+pub const HOOKS: Hooks = Hooks::new("hooks");
diff --git a/docker/app.toml b/docker/app.toml
deleted file mode 100644
index cde97ac6..00000000
--- a/docker/app.toml
+++ /dev/null
@@ -1,152 +0,0 @@
-# This is a TOML config file.
-# For more information, see https://github.com/toml-lang/toml
-
-###############################################################################
-###                           Base Configuration                            ###
-###############################################################################
-
-# The minimum gas prices a validator is willing to accept for processing a
-# transaction. A transaction's fees must meet the minimum of any denomination
-# specified in this config (e.g. 0.25token1;0.0001token2).
-minimum-gas-prices = "0.025ujunox"
-
-# default: the last 100 states are kept in addition to every 500th state; pruning at 10 block intervals
-# nothing: all historic states will be saved, nothing will be deleted (i.e. archiving node)
-# everything: all saved states will be deleted, storing only the current state; pruning at 10 block intervals
-# custom: allow pruning options to be manually specified through 'pruning-keep-recent', 'pruning-keep-every', and 'pruning-interval'
-pruning = "default"
-
-# These are applied if and only if the pruning strategy is custom.
-pruning-keep-recent = "0"
-pruning-keep-every = "0"
-pruning-interval = "0"
-
-# HaltHeight contains a non-zero block height at which a node will gracefully
-# halt and shutdown that can be used to assist upgrades and testing.
-#
-# Note: Commitment of state will be attempted on the corresponding block.
-halt-height = 0
-
-# HaltTime contains a non-zero minimum block time (in Unix seconds) at which
-# a node will gracefully halt and shutdown that can be used to assist upgrades
-# and testing.
-#
-# Note: Commitment of state will be attempted on the corresponding block.
-halt-time = 0
-
-# MinRetainBlocks defines the minimum block height offset from the current
-# block being committed, such that all blocks past this offset are pruned
-# from Tendermint. It is used as part of the process of determining the
-# ResponseCommit.RetainHeight value during ABCI Commit. A value of 0 indicates
-# that no blocks should be pruned.
-#
-# This configuration value is only responsible for pruning Tendermint blocks.
-# It has no bearing on application state pruning which is determined by the
-# "pruning-*" configurations.
-#
-# Note: Tendermint block pruning is dependant on this parameter in conunction
-# with the unbonding (safety threshold) period, state pruning and state sync
-# snapshot parameters to determine the correct minimum value of
-# ResponseCommit.RetainHeight.
-min-retain-blocks = 0
-
-# InterBlockCache enables inter-block caching.
-inter-block-cache = true
-
-# IndexEvents defines the set of events in the form {eventType}.{attributeKey},
-# which informs Tendermint what to index. If empty, all events will be indexed.
-#
-# Example:
-# ["message.sender", "message.recipient"]
-index-events = []
-
-###############################################################################
-###                         Telemetry Configuration                         ###
-###############################################################################
-
-[telemetry]
-
-# Prefixed with keys to separate services.
-service-name = ""
-
-# Enabled enables the application telemetry functionality. When enabled,
-# an in-memory sink is also enabled by default. Operators may also enabled
-# other sinks such as Prometheus.
-enabled = false
-
-# Enable prefixing gauge values with hostname.
-enable-hostname = false
-
-# Enable adding hostname to labels.
-enable-hostname-label = false
-
-# Enable adding service to labels.
-enable-service-label = false
-
-# PrometheusRetentionTime, when positive, enables a Prometheus metrics sink.
-prometheus-retention-time = 0
-
-# GlobalLabels defines a global set of name/value label tuples applied to all
-# metrics emitted using the wrapper functions defined in telemetry package.
-#
-# Example:
-# [["chain_id", "cosmoshub-1"]]
-global-labels = [
-]
-
-###############################################################################
-###                           API Configuration                             ###
-###############################################################################
-
-[api]
-
-# Enable defines if the API server should be enabled.
-enable = true
-
-# Swagger defines if swagger documentation should automatically be registered.
-swagger = true
-
-# Address defines the API server to listen on.
-address = "tcp://0.0.0.0:1317"
-
-# MaxOpenConnections defines the number of maximum open connections.
-max-open-connections = 1000
-
-# RPCReadTimeout defines the Tendermint RPC read timeout (in seconds).
-rpc-read-timeout = 10
-
-# RPCWriteTimeout defines the Tendermint RPC write timeout (in seconds).
-rpc-write-timeout = 0
-
-# RPCMaxBodyBytes defines the Tendermint maximum response body (in bytes).
-rpc-max-body-bytes = 1000000
-
-# EnableUnsafeCORS defines if CORS should be enabled (unsafe - use it at your own risk).
-enabled-unsafe-cors = true
-
-###############################################################################
-###                           gRPC Configuration                            ###
-###############################################################################
-
-[grpc]
-
-# Enable defines if the gRPC server should be enabled.
-enable = true
-
-# Address defines the gRPC server address to bind to.
-address = "0.0.0.0:9090"
-
-###############################################################################
-###                        State Sync Configuration                         ###
-###############################################################################
-
-# State sync snapshots allow other nodes to rapidly join the network without replaying historical
-# blocks, instead downloading and applying a snapshot of the application state at a given height.
-[state-sync]
-
-# snapshot-interval specifies the block interval at which local state sync snapshots are
-# taken (0 to disable). Must be a multiple of pruning-keep-every.
-snapshot-interval = 0
-
-# snapshot-keep-recent specifies the number of recent snapshots to keep and serve (0 to keep all).
-snapshot-keep-recent = 2
diff --git a/docker/config.toml b/docker/config.toml
deleted file mode 100644
index aa95e820..00000000
--- a/docker/config.toml
+++ /dev/null
@@ -1,401 +0,0 @@
-# This is a TOML config file.
-# For more information, see https://github.com/toml-lang/toml
-
-# NOTE: Any path below can be absolute (e.g. "/var/myawesomeapp/data") or
-# relative to the home directory (e.g. "data"). The home directory is
-# "$HOME/.tendermint" by default, but could be changed via $TMHOME env variable
-# or --home cmd flag.
-
-#######################################################################
-###                   Main Base Config Options                      ###
-#######################################################################
-
-# TCP or UNIX socket address of the ABCI application,
-# or the name of an ABCI application compiled in with the Tendermint binary
-proxy_app = "tcp://127.0.0.1:26658"
-
-# A custom human readable name for this node
-moniker = "node001"
-
-# If this node is many blocks behind the tip of the chain, FastSync
-# allows them to catchup quickly by downloading blocks in parallel
-# and verifying their commits
-fast_sync = true
-
-# Database backend: goleveldb | cleveldb | boltdb | rocksdb | badgerdb
-# * goleveldb (github.com/syndtr/goleveldb - most popular implementation)
-#   - pure go
-#   - stable
-# * cleveldb (uses levigo wrapper)
-#   - fast
-#   - requires gcc
-#   - use cleveldb build tag (go build -tags cleveldb)
-# * boltdb (uses etcd's fork of bolt - github.com/etcd-io/bbolt)
-#   - EXPERIMENTAL
-#   - may be faster is some use-cases (random reads - indexer)
-#   - use boltdb build tag (go build -tags boltdb)
-# * rocksdb (uses github.com/tecbot/gorocksdb)
-#   - EXPERIMENTAL
-#   - requires gcc
-#   - use rocksdb build tag (go build -tags rocksdb)
-# * badgerdb (uses github.com/dgraph-io/badger)
-#   - EXPERIMENTAL
-#   - use badgerdb build tag (go build -tags badgerdb)
-db_backend = "goleveldb"
-
-# Database directory
-db_dir = "data"
-
-# Output level for logging, including package level options
-log_level = "info"
-
-# Output format: 'plain' (colored text) or 'json'
-log_format = "plain"
-
-##### additional base config options #####
-
-# Path to the JSON file containing the initial validator set and other meta data
-genesis_file = "config/genesis.json"
-
-# Path to the JSON file containing the private key to use as a validator in the consensus protocol
-priv_validator_key_file = "config/priv_validator_key.json"
-
-# Path to the JSON file containing the last sign state of a validator
-priv_validator_state_file = "data/priv_validator_state.json"
-
-# TCP or UNIX socket address for Tendermint to listen on for
-# connections from an external PrivValidator process
-priv_validator_laddr = ""
-
-# Path to the JSON file containing the private key to use for node authentication in the p2p protocol
-node_key_file = "config/node_key.json"
-
-# Mechanism to connect to the ABCI application: socket | grpc
-abci = "socket"
-
-# If true, query the ABCI app on connecting to a new peer
-# so the app can decide if we should keep the connection or not
-filter_peers = false
-
-
-#######################################################################
-###                 Advanced Configuration Options                  ###
-#######################################################################
-
-#######################################################
-###       RPC Server Configuration Options          ###
-#######################################################
-[rpc]
-
-# TCP or UNIX socket address for the RPC server to listen on
-laddr = "tcp://127.0.0.1:26657"
-
-# A list of origins a cross-domain request can be executed from
-# Default value '[]' disables cors support
-# Use '["*"]' to allow any origin
-cors_allowed_origins = ["*"]
-
-# A list of methods the client is allowed to use with cross-domain requests
-cors_allowed_methods = ["HEAD", "GET", "POST", ]
-
-# A list of non simple headers the client is allowed to use with cross-domain requests
-cors_allowed_headers = ["Origin", "Accept", "Content-Type", "X-Requested-With", "X-Server-Time", ]
-
-# TCP or UNIX socket address for the gRPC server to listen on
-# NOTE: This server only supports /broadcast_tx_commit
-grpc_laddr = ""
-
-# Maximum number of simultaneous connections.
-# Does not include RPC (HTTP&WebSocket) connections. See max_open_connections
-# If you want to accept a larger number than the default, make sure
-# you increase your OS limits.
-# 0 - unlimited.
-# Should be < {ulimit -Sn} - {MaxNumInboundPeers} - {MaxNumOutboundPeers} - {N of wal, db and other open files}
-# 1024 - 40 - 10 - 50 = 924 = ~900
-grpc_max_open_connections = 900
-
-# Activate unsafe RPC commands like /dial_seeds and /unsafe_flush_mempool
-unsafe = false
-
-# Maximum number of simultaneous connections (including WebSocket).
-# Does not include gRPC connections. See grpc_max_open_connections
-# If you want to accept a larger number than the default, make sure
-# you increase your OS limits.
-# 0 - unlimited.
-# Should be < {ulimit -Sn} - {MaxNumInboundPeers} - {MaxNumOutboundPeers} - {N of wal, db and other open files}
-# 1024 - 40 - 10 - 50 = 924 = ~900
-max_open_connections = 900
-
-# Maximum number of unique clientIDs that can /subscribe
-# If you're using /broadcast_tx_commit, set to the estimated maximum number
-# of broadcast_tx_commit calls per block.
-max_subscription_clients = 100
-
-# Maximum number of unique queries a given client can /subscribe to
-# If you're using GRPC (or Local RPC client) and /broadcast_tx_commit, set to
-# the estimated # maximum number of broadcast_tx_commit calls per block.
-max_subscriptions_per_client = 5
-
-# How long to wait for a tx to be committed during /broadcast_tx_commit.
-# WARNING: Using a value larger than 10s will result in increasing the
-# global HTTP write timeout, which applies to all connections and endpoints.
-# See https://github.com/tendermint/tendermint/issues/3435
-timeout_broadcast_tx_commit = "10s"
-
-# Maximum size of request body, in bytes
-max_body_bytes = 1000000
-
-# Maximum size of request header, in bytes
-max_header_bytes = 1048576
-
-# The path to a file containing certificate that is used to create the HTTPS server.
-# Might be either absolute path or path related to Tendermint's config directory.
-# If the certificate is signed by a certificate authority,
-# the certFile should be the concatenation of the server's certificate, any intermediates,
-# and the CA's certificate.
-# NOTE: both tls_cert_file and tls_key_file must be present for Tendermint to create HTTPS server.
-# Otherwise, HTTP server is run.
-tls_cert_file = ""
-
-# The path to a file containing matching private key that is used to create the HTTPS server.
-# Might be either absolute path or path related to Tendermint's config directory.
-# NOTE: both tls-cert-file and tls-key-file must be present for Tendermint to create HTTPS server.
-# Otherwise, HTTP server is run.
-tls_key_file = ""
-
-# pprof listen address (https://golang.org/pkg/net/http/pprof)
-pprof_laddr = "localhost:6060"
-
-#######################################################
-###           P2P Configuration Options             ###
-#######################################################
-[p2p]
-
-# Address to listen for incoming connections
-laddr = "tcp://0.0.0.0:26656"
-
-# Address to advertise to peers for them to dial
-# If empty, will use the same port as the laddr,
-# and will introspect on the listener or use UPnP
-# to figure out the address. ip and port are required
-# example: 159.89.10.97:26656
-external_address = ""
-
-# Comma separated list of seed nodes to connect to
-seeds = ""
-
-# Comma separated list of nodes to keep persistent connections to
-persistent_peers = ""
-
-# UPNP port forwarding
-upnp = false
-
-# Path to address book
-addr_book_file = "config/addrbook.json"
-
-# Set true for strict address routability rules
-# Set false for private or local networks
-addr_book_strict = true
-
-# Maximum number of inbound peers
-max_num_inbound_peers = 40
-
-# Maximum number of outbound peers to connect to, excluding persistent peers
-max_num_outbound_peers = 10
-
-# List of node IDs, to which a connection will be (re)established ignoring any existing limits
-unconditional_peer_ids = ""
-
-# Maximum pause when redialing a persistent peer (if zero, exponential backoff is used)
-persistent_peers_max_dial_period = "0s"
-
-# Time to wait before flushing messages out on the connection
-flush_throttle_timeout = "100ms"
-
-# Maximum size of a message packet payload, in bytes
-max_packet_msg_payload_size = 1024
-
-# Rate at which packets can be sent, in bytes/second
-send_rate = 5120000
-
-# Rate at which packets can be received, in bytes/second
-recv_rate = 5120000
-
-# Set true to enable the peer-exchange reactor
-pex = true
-
-# Seed mode, in which node constantly crawls the network and looks for
-# peers. If another node asks it for addresses, it responds and disconnects.
-#
-# Does not work if the peer-exchange reactor is disabled.
-seed_mode = false
-
-# Comma separated list of peer IDs to keep private (will not be gossiped to other peers)
-private_peer_ids = ""
-
-# Toggle to disable guard against peers connecting from the same ip.
-allow_duplicate_ip = false
-
-# Peer connection configuration.
-handshake_timeout = "20s"
-dial_timeout = "3s"
-
-#######################################################
-###          Mempool Configuration Option          ###
-#######################################################
-[mempool]
-
-recheck = true
-broadcast = true
-wal_dir = ""
-
-# Maximum number of transactions in the mempool
-size = 5000
-
-# Limit the total size of all txs in the mempool.
-# This only accounts for raw transactions (e.g. given 1MB transactions and
-# max_txs_bytes=5MB, mempool will only accept 5 transactions).
-max_txs_bytes = 1073741824
-
-# Size of the cache (used to filter transactions we saw earlier) in transactions
-cache_size = 10000
-
-# Do not remove invalid transactions from the cache (default: false)
-# Set to true if it's not possible for any invalid transaction to become valid
-# again in the future.
-keep-invalid-txs-in-cache = false
-
-# Maximum size of a single transaction.
-# NOTE: the max size of a tx transmitted over the network is {max_tx_bytes}.
-max_tx_bytes = 1048576
-
-# Maximum size of a batch of transactions to send to a peer
-# Including space needed by encoding (one varint per transaction).
-# XXX: Unused due to https://github.com/tendermint/tendermint/issues/5796
-max_batch_bytes = 0
-
-#######################################################
-###         State Sync Configuration Options        ###
-#######################################################
-[statesync]
-# State sync rapidly bootstraps a new node by discovering, fetching, and restoring a state machine
-# snapshot from peers instead of fetching and replaying historical blocks. Requires some peers in
-# the network to take and serve state machine snapshots. State sync is not attempted if the node
-# has any local state (LastBlockHeight > 0). The node will have a truncated block history,
-# starting from the height of the snapshot.
-enable = false
-
-# RPC servers (comma-separated) for light client verification of the synced state machine and
-# retrieval of state data for node bootstrapping. Also needs a trusted height and corresponding
-# header hash obtained from a trusted source, and a period during which validators can be trusted.
-#
-# For Cosmos SDK-based chains, trust_period should usually be about 2/3 of the unbonding time (~2
-# weeks) during which they can be financially punished (slashed) for misbehavior.
-rpc_servers = ""
-trust_height = 0
-trust_hash = ""
-trust_period = "168h0m0s"
-
-# Time to spend discovering snapshots before initiating a restore.
-discovery_time = "15s"
-
-# Temporary directory for state sync snapshot chunks, defaults to the OS tempdir (typically /tmp).
-# Will create a new, randomly named directory within, and remove it when done.
-temp_dir = ""
-
-# The timeout duration before re-requesting a chunk, possibly from a different
-# peer (default: 1 minute).
-chunk_request_timeout = "10s"
-
-# The number of concurrent chunk fetchers to run (default: 1).
-chunk_fetchers = "4"
-
-#######################################################
-###       Fast Sync Configuration Connections       ###
-#######################################################
-[fastsync]
-
-# Fast Sync version to use:
-#   1) "v0" (default) - the legacy fast sync implementation
-#   2) "v1" - refactor of v0 version for better testability
-#   2) "v2" - complete redesign of v0, optimized for testability & readability
-version = "v0"
-
-#######################################################
-###         Consensus Configuration Options         ###
-#######################################################
-[consensus]
-
-wal_file = "data/cs.wal/wal"
-
-# How long we wait for a proposal block before prevoting nil
-timeout_propose = "3s"
-# How much timeout_propose increases with each round
-timeout_propose_delta = "500ms"
-# How long we wait after receiving +2/3 prevotes for “anything” (ie. not a single block or nil)
-timeout_prevote = "1s"
-# How much the timeout_prevote increases with each round
-timeout_prevote_delta = "500ms"
-# How long we wait after receiving +2/3 precommits for “anything” (ie. not a single block or nil)
-timeout_precommit = "1s"
-# How much the timeout_precommit increases with each round
-timeout_precommit_delta = "500ms"
-# How long we wait after committing a block, before starting on the new
-# height (this gives us a chance to receive some more precommits, even
-# though we already have +2/3).
-timeout_commit = "5s"
-
-# How many blocks to look back to check existence of the node's consensus votes before joining consensus
-# When non-zero, the node will panic upon restart
-# if the same consensus key was used to sign {double_sign_check_height} last blocks.
-# So, validators should stop the state machine, wait for some blocks, and then restart the state machine to avoid panic.
-double_sign_check_height = 0
-
-# Make progress as soon as we have all the precommits (as if TimeoutCommit = 0)
-skip_timeout_commit = false
-
-# EmptyBlocks mode and possible interval between empty blocks
-create_empty_blocks = true
-create_empty_blocks_interval = "0s"
-
-# Reactor sleep duration parameters
-peer_gossip_sleep_duration = "100ms"
-peer_query_maj23_sleep_duration = "2s"
-
-#######################################################
-###   Transaction Indexer Configuration Options     ###
-#######################################################
-[tx_index]
-
-# What indexer to use for transactions
-#
-# The application will set which txs to index. In some cases a node operator will be able
-# to decide which txs to index based on configuration set in the application.
-#
-# Options:
-#   1) "null"
-#   2) "kv" (default) - the simplest possible indexer, backed by key-value storage (defaults to levelDB; see DBBackend).
-# 		- When "kv" is chosen "tx.height" and "tx.hash" will always be indexed.
-indexer = "kv"
-
-#######################################################
-###       Instrumentation Configuration Options     ###
-#######################################################
-[instrumentation]
-
-# When true, Prometheus metrics are served under /metrics on
-# PrometheusListenAddr.
-# Check out the documentation for the list of available metrics.
-prometheus = false
-
-# Address to listen for Prometheus collector(s) connections
-prometheus_listen_addr = ":26660"
-
-# Maximum number of simultaneous connections.
-# If you want to accept a larger number than the default, make sure
-# you increase your OS limits.
-# 0 - unlimited.
-max_open_connections = 3
-
-# Instrumentation namespace
-namespace = "tendermint"
diff --git a/scripts/deploy_local.sh b/scripts/deploy_local.sh
index 82b74439..8178b587 100644
--- a/scripts/deploy_local.sh
+++ b/scripts/deploy_local.sh
@@ -4,12 +4,17 @@
 
 ## CONFIG
 # NOTE: you will need to update these to deploy on different network
-IMAGE_TAG="v2.1.0" # moneta
-BINARY='docker exec -i cosmwasm junod'
+IMAGE_TAG=${2:-"v2.3.0-beta.1"} # lupercalia beta - this allows you to pass in an image, e.g. pr-156 as arg 2
+CONTAINER_NAME="cosmwasm"
+BINARY="docker exec -i $CONTAINER_NAME junod"
 DENOM='ujunox'
 CHAIN_ID='testing'
 RPC='http://localhost:26657/'
 TXFLAG="--gas-prices 0.1$DENOM --gas auto --gas-adjustment 1.5 -y -b block --chain-id $CHAIN_ID --node $RPC"
+BLOCK_GAS_LIMIT=${GAS_LIMIT:-100000000} # should mirror mainnet
+
+echo "Building $IMAGE_TAG"
+echo "Configured Block Gas Limit: $BLOCK_GAS_LIMIT"
 
 if [ "$1" = "" ]
 then
@@ -17,28 +22,19 @@ then
   exit
 fi
 
-# Deploy junod in Docker
-docker kill cosmwasm
-
+# kill any orphans
+docker kill $CONTAINER_NAME
 docker volume rm -f junod_data
 
 # Run junod setup script
-docker run --rm -it \
-    -e STAKE_TOKEN=$DENOM \
+docker run --rm -d --name $CONTAINER_NAME \
     -e PASSWORD=xxxxxxxxx \
+    -e STAKE_TOKEN=$DENOM \
+    -e GAS_LIMIT="$GAS_LIMIT" \
+    -e UNSAFE_CORS=true \
+    -p 1317:1317 -p 26656:26656 -p 26657:26657 \
     --mount type=volume,source=junod_data,target=/root \
-    ghcr.io/cosmoscontracts/juno:$IMAGE_TAG /opt/setup_junod.sh $1
-
-# Add custom app.toml to junod_data volume
-docker run -v junod_data:/root --name helper busybox true
-docker cp docker/app.toml helper:/root/.juno/config/app.toml
-docker cp docker/config.toml helper:/root/.juno/config/config.toml
-docker rm helper
-
-# Start junod
-docker run --rm -d --name cosmwasm -p 26657:26657 -p 26656:26656 -p 1317:1317 \
-    --mount type=volume,source=junod_data,target=/root \
-    ghcr.io/cosmoscontracts/juno:$IMAGE_TAG /opt/run_junod.sh
+    ghcr.io/cosmoscontracts/juno:$IMAGE_TAG /opt/setup_and_run.sh $1
 
 # Compile code
 docker run --rm -v "$(pwd)":/code \
@@ -96,7 +92,6 @@ CW3_DAO_INIT='{
   "gov_token": {
     "instantiate_new_cw20": {
       "cw20_code_id": '$CW20_CODE',
-      "stake_contract_code_id": '$STAKE_CW20_CODE',
       "label": "DAO DAO v0.1.1",
       "initial_dao_balance": "1000000000",
       "msg": {
@@ -107,6 +102,11 @@ CW3_DAO_INIT='{
       }
     }
   },
+  "staking_contract": {
+    "instantiate_new_staking_contract": {
+      "staking_contract_code_id": '$STAKE_CW20_CODE'
+    }
+  },
   "threshold": {
     "absolute_percentage": {
         "percentage": "0.5"
@@ -115,11 +115,13 @@ CW3_DAO_INIT='{
   "max_voting_period": {
     "height": 100
   },
-  "proposal_deposit_amount": "0"
+  "proposal_deposit_amount": "0",
+  "only_members_execute": false,
+  "automatically_add_cw20s": true
 }'
 echo $CW3_DAO_INIT | jq .
 
-echo xxxxxxxxx | $BINARY tx wasm instantiate "$CW3_DAO_CODE" "$CW3_DAO_INIT" --from validator --label "DAO DAO" $TXFLAG --output json
+echo xxxxxxxxx | $BINARY tx wasm instantiate "$CW3_DAO_CODE" "$CW3_DAO_INIT" --from validator --label "DAO DAO" $TXFLAG --output json --no-admin
 
 CW3_DAO_CONTRACT=$($BINARY q wasm list-contract-by-code $CW3_DAO_CODE --output json | jq -r '.contracts[-1]')
 


Test patch:
diff --git a/contracts/cw3-dao/src/tests.rs b/contracts/cw3-dao/src/tests.rs
index cb6ec621..83e21f4e 100644
--- a/contracts/cw3-dao/src/tests.rs
+++ b/contracts/cw3-dao/src/tests.rs
@@ -2,7 +2,7 @@ use crate::contract::{CONTRACT_NAME, CONTRACT_VERSION};
 use crate::error::ContractError;
 use crate::msg::{
     ExecuteMsg, GovTokenInstantiateMsg, GovTokenMsg, InstantiateMsg, ProposeMsg, QueryMsg,
-    Threshold, VoteMsg,
+    StakingContractMsg, Threshold, VoteMsg,
 };
 use crate::query::{
     ConfigResponse, Cw20BalancesResponse, ProposalListResponse, ProposalResponse,
@@ -104,8 +104,10 @@ fn instantiate_dao(
         description: "a great DAO!".to_string(),
         gov_token: GovTokenMsg::UseExistingCw20 {
             addr: cw20.to_string(),
-            stake_contract_code_id: staking_code_id,
             label: "dao-dao".to_string(),
+        },
+        staking_contract: StakingContractMsg::InstantiateNewStakingContract {
+            staking_contract_code_id: staking_code_id,
             unstaking_duration: None,
         },
         threshold,
@@ -264,8 +266,10 @@ fn test_instantiate_works() {
         description: "a great DAO!".to_string(),
         gov_token: GovTokenMsg::UseExistingCw20 {
             addr: cw20_addr.to_string(),
-            stake_contract_code_id,
             label: "dao-dao".to_string(),
+        },
+        staking_contract: StakingContractMsg::InstantiateNewStakingContract {
+            staking_contract_code_id: stake_contract_code_id,
             unstaking_duration: None,
         },
         threshold: Threshold::AbsolutePercentage {
@@ -317,7 +321,6 @@ fn instantiate_new_gov_token() {
         description: "a great DAO!".to_string(),
         gov_token: GovTokenMsg::InstantiateNewCw20 {
             cw20_code_id,
-            stake_contract_code_id,
             label: String::from("DAO DAO"),
             initial_dao_balance: Some(Uint128::new(1000000)),
             msg: GovTokenInstantiateMsg {
@@ -327,6 +330,9 @@ fn instantiate_new_gov_token() {
                 initial_balances: vec![],
                 marketing: None,
             },
+        },
+        staking_contract: StakingContractMsg::InstantiateNewStakingContract {
+            staking_contract_code_id: stake_contract_code_id,
             unstaking_duration: None,
         },
         threshold: Threshold::ThresholdQuorum {
@@ -378,7 +384,6 @@ fn instantiate_new_gov_token() {
         description: "a great DAO!".to_string(),
         gov_token: GovTokenMsg::InstantiateNewCw20 {
             cw20_code_id,
-            stake_contract_code_id,
             label: String::from("DAO DAO"),
             initial_dao_balance: None,
             msg: GovTokenInstantiateMsg {
@@ -388,6 +393,9 @@ fn instantiate_new_gov_token() {
                 initial_balances: initial_balances.clone(),
                 marketing: None,
             },
+        },
+        staking_contract: StakingContractMsg::InstantiateNewStakingContract {
+            staking_contract_code_id: stake_contract_code_id,
             unstaking_duration: None,
         },
         threshold: Threshold::ThresholdQuorum {
@@ -519,7 +527,6 @@ fn instantiate_new_gov_token() {
         description: "a great DAO!".to_string(),
         gov_token: GovTokenMsg::InstantiateNewCw20 {
             cw20_code_id,
-            stake_contract_code_id,
             label: String::from("DAO DAO"),
             initial_dao_balance: Some(Uint128::new(1000)),
             msg: GovTokenInstantiateMsg {
@@ -529,6 +536,9 @@ fn instantiate_new_gov_token() {
                 initial_balances,
                 marketing: None,
             },
+        },
+        staking_contract: StakingContractMsg::InstantiateNewStakingContract {
+            staking_contract_code_id: stake_contract_code_id,
             unstaking_duration: None,
         },
         threshold: Threshold::ThresholdQuorum {
@@ -573,6 +583,221 @@ fn instantiate_new_gov_token() {
     );
 }
 
+#[test]
+fn instantiate_staking_contract() {
+    let mut app = mock_app();
+    let dao_code_id = app.store_code(contract_dao());
+    let cw20_code_id = app.store_code(contract_cw20_gov());
+    let staking_code_id = app.store_code(contract_staking());
+
+    let max_voting_period = Duration::Time(1234567);
+    let threshold = Threshold::ThresholdQuorum {
+        threshold: Decimal::percent(51),
+        quorum: Decimal::percent(10),
+    };
+
+    // Setup test case, we want to use the cw20_addr and
+    // staking_addr in later tests.
+    // This also tests the case of using an existing cw20
+    // and instantiating a new staking contract
+    let (_dao_addr, cw20_addr, staking_addr) = setup_test_case(
+        &mut app,
+        threshold,
+        max_voting_period,
+        coins(100, NATIVE_TOKEN_DENOM),
+        None,
+        None,
+    );
+
+    // Instantiate with a new staking contract, with a new CW20
+    let initial_balances = vec![
+        Cw20Coin {
+            address: OWNER.to_string(),
+            amount: Uint128::new(INITIAL_BALANCE),
+        },
+        Cw20Coin {
+            address: VOTER1.to_string(),
+            amount: Uint128::new(INITIAL_BALANCE),
+        },
+        Cw20Coin {
+            address: VOTER2.to_string(),
+            amount: Uint128::new(INITIAL_BALANCE),
+        },
+        Cw20Coin {
+            address: VOTER3.to_string(),
+            amount: Uint128::new(INITIAL_BALANCE * 2),
+        },
+        Cw20Coin {
+            address: POWER_VOTER.to_string(),
+            amount: Uint128::new(INITIAL_BALANCE * 5),
+        },
+    ];
+    let msg = InstantiateMsg {
+        name: "dao-dao".to_string(),
+        description: "a great DAO!".to_string(),
+        gov_token: GovTokenMsg::InstantiateNewCw20 {
+            cw20_code_id,
+            label: String::from("DAO DAO"),
+            initial_dao_balance: Some(Uint128::new(1000000)),
+            msg: GovTokenInstantiateMsg {
+                name: String::from("DAO DAO"),
+                symbol: String::from("DAO"),
+                decimals: 6,
+                initial_balances: initial_balances.clone(),
+                marketing: None,
+            },
+        },
+        staking_contract: StakingContractMsg::InstantiateNewStakingContract {
+            staking_contract_code_id: staking_code_id,
+            unstaking_duration: None,
+        },
+        threshold: Threshold::AbsolutePercentage {
+            percentage: Decimal::percent(51),
+        },
+        max_voting_period,
+        proposal_deposit_amount: Uint128::zero(),
+        refund_failed_proposals: None,
+        image_url: None,
+        only_members_execute: true,
+        automatically_add_cw20s: true,
+    };
+    app.instantiate_contract(
+        dao_code_id,
+        Addr::unchecked(OWNER),
+        &msg,
+        &[],
+        "cw3-dao",
+        None,
+    )
+    .unwrap();
+
+    // Instantiate with an existing staking contract, with a new CW20
+    // Expect an error as this is an invalid combination
+    let msg = InstantiateMsg {
+        name: "dao-dao".to_string(),
+        description: "a great DAO!".to_string(),
+        gov_token: GovTokenMsg::InstantiateNewCw20 {
+            cw20_code_id,
+            label: String::from("DAO DAO"),
+            initial_dao_balance: Some(Uint128::new(1000000)),
+            msg: GovTokenInstantiateMsg {
+                name: String::from("DAO DAO"),
+                symbol: String::from("DAO"),
+                decimals: 6,
+                initial_balances: initial_balances.clone(),
+                marketing: None,
+            },
+        },
+        staking_contract: StakingContractMsg::UseExistingStakingContract {
+            addr: staking_addr.to_string(),
+        },
+        threshold: Threshold::AbsolutePercentage {
+            percentage: Decimal::percent(51),
+        },
+        max_voting_period,
+        proposal_deposit_amount: Uint128::zero(),
+        refund_failed_proposals: None,
+        image_url: None,
+        only_members_execute: true,
+        automatically_add_cw20s: true,
+    };
+    app.instantiate_contract(
+        dao_code_id,
+        Addr::unchecked(OWNER),
+        &msg,
+        &[],
+        "cw3-dao",
+        None,
+    )
+    .unwrap_err();
+
+    // Create another CW20 to use to test for staking contract
+    // mismatch error
+    let msg = cw20_base::msg::InstantiateMsg {
+        name: String::from("Other"),
+        symbol: String::from("OTHER"),
+        decimals: 6,
+        initial_balances,
+        mint: None,
+        marketing: None,
+    };
+    let other_cw20_addr = app
+        .instantiate_contract(
+            cw20_code_id,
+            Addr::unchecked(OWNER),
+            &msg,
+            &[],
+            "cw20",
+            None,
+        )
+        .unwrap();
+
+    // Instantiate a DAO with an existing CW20 (other_cw20_addr) and an existing staking contract
+    // (staking_addr). We expect this to error as the CW20 address does not match the CW20
+    // address in the staking contract (queried by the GetConfig route)
+    let msg = InstantiateMsg {
+        name: "dao-dao".to_string(),
+        description: "a great DAO!".to_string(),
+        gov_token: GovTokenMsg::UseExistingCw20 {
+            addr: other_cw20_addr.to_string(),
+            label: "dao-dao".to_string(),
+        },
+        staking_contract: StakingContractMsg::UseExistingStakingContract {
+            addr: staking_addr.to_string(),
+        },
+        threshold: Threshold::AbsolutePercentage {
+            percentage: Decimal::percent(51),
+        },
+        max_voting_period,
+        proposal_deposit_amount: Uint128::zero(),
+        refund_failed_proposals: None,
+        image_url: None,
+        only_members_execute: true,
+        automatically_add_cw20s: true,
+    };
+    let _err = app
+        .instantiate_contract(
+            dao_code_id,
+            Addr::unchecked(OWNER),
+            &msg,
+            &[],
+            "cw3-dao",
+            None,
+        )
+        .unwrap_err();
+
+    // Now lets use an existing staking contract, using an existing CW20
+    let msg = InstantiateMsg {
+        name: "dao-dao".to_string(),
+        description: "a great DAO!".to_string(),
+        gov_token: GovTokenMsg::UseExistingCw20 {
+            addr: cw20_addr.to_string(),
+            label: "dao-dao".to_string(),
+        },
+        staking_contract: StakingContractMsg::UseExistingStakingContract {
+            addr: staking_addr.to_string(),
+        },
+        threshold: Threshold::AbsolutePercentage {
+            percentage: Decimal::percent(51),
+        },
+        max_voting_period,
+        proposal_deposit_amount: Uint128::zero(),
+        refund_failed_proposals: None,
+        image_url: None,
+        only_members_execute: true,
+        automatically_add_cw20s: true,
+    };
+    app.instantiate_contract(
+        dao_code_id,
+        Addr::unchecked(OWNER),
+        &msg,
+        &[],
+        "cw3-dao",
+        None,
+    )
+    .unwrap();
+}
+
 #[test]
 fn test_propose_works() {
     let mut app = mock_app();