Skip to content
Snippets Groups Projects
Commit e6c65647 authored by hianant2's avatar hianant2
Browse files

working first

parent 06475122
No related branches found
No related tags found
No related merge requests found
...@@ -57,7 +57,9 @@ deployAll() ...@@ -57,7 +57,9 @@ deployAll()
# deploy smart contract to all chains... # deploy smart contract to all chains...
wasmd tx wasm store $file --node $NODE_0 --from $USER --chain-id ibc-0 $GAS_FLAG --broadcast-mode block -y $KEYRING_0 wasmd tx wasm store $file --node $NODE_0 --from $USER --chain-id ibc-0 $GAS_FLAG --broadcast-mode block -y $KEYRING_0
sleep 1
wasmd tx wasm store $file --node $NODE_1 --from $USER --chain-id ibc-1 $GAS_FLAG --broadcast-mode block -y $KEYRING_1 wasmd tx wasm store $file --node $NODE_1 --from $USER --chain-id ibc-1 $GAS_FLAG --broadcast-mode block -y $KEYRING_1
sleep 1
wasmd tx wasm store $file --node $NODE_2 --from $USER --chain-id ibc-2 $GAS_FLAG --broadcast-mode block -y $KEYRING_2 wasmd tx wasm store $file --node $NODE_2 --from $USER --chain-id ibc-2 $GAS_FLAG --broadcast-mode block -y $KEYRING_2
#get code ids at each chain #get code ids at each chain
...@@ -86,12 +88,6 @@ deployAll() ...@@ -86,12 +88,6 @@ deployAll()
ibc_port_1=$(wasmd query wasm contract $contract_address_1 --node $NODE_1 --output --json | jq -r '.contract_info | .ibc_port_id') ibc_port_1=$(wasmd query wasm contract $contract_address_1 --node $NODE_1 --output --json | jq -r '.contract_info | .ibc_port_id')
ibc_port_2=$(wasmd query wasm contract $contract_address_2 --node $NODE_2 --output --json | jq -r '.contract_info | .ibc_port_id') ibc_port_2=$(wasmd query wasm contract $contract_address_2 --node $NODE_2 --output --json | jq -r '.contract_info | .ibc_port_id')
set +x
echo "------------------------------------------Addreses-------------------------------------------------------"
echo "Deployed with code id $code_id_0 on chain 0 Contract Address = $contract_address_0 ibc_port = $ibc_port_0"
echo "Deployed with code id $code_id_1 on chain 1 Contract Address = $contract_address_1 ibc_port = $ibc_port_1"
echo "Deployed with code id $code_id_2 on chain 2 Contract Address = $contract_address_2 ibc_port = $ibc_port_2"
echo "-----------------------------------------Link Setup-----------------------------------------------" echo "-----------------------------------------Link Setup-----------------------------------------------"
set -x set -x
rly tx link path01 --src-port $ibc_port_0 --dst-port $ibc_port_1 --order ordered --version trustboost-test rly tx link path01 --src-port $ibc_port_0 --dst-port $ibc_port_1 --order ordered --version trustboost-test
...@@ -99,6 +95,11 @@ deployAll() ...@@ -99,6 +95,11 @@ deployAll()
set +x set +x
sleep 2 sleep 2
set +x
echo "------------------------------------------Addreses-------------------------------------------------------"
echo "Deployed with code id $code_id_0 on chain 0 Contract Address = $contract_address_0 ibc_port = $ibc_port_0"
echo "Deployed with code id $code_id_1 on chain 1 Contract Address = $contract_address_1 ibc_port = $ibc_port_1"
echo "Deployed with code id $code_id_2 on chain 2 Contract Address = $contract_address_2 ibc_port = $ibc_port_2"
echo "-----------------------------------------Channels-----------------------------------------------" echo "-----------------------------------------Channels-----------------------------------------------"
set -x set -x
chan1=$(wasmd query ibc channel channels --node $NODE_0 --output --json | jq -r '.channels[-2] | .channel_id') chan1=$(wasmd query ibc channel channels --node $NODE_0 --output --json | jq -r '.channels[-2] | .channel_id')
...@@ -163,7 +164,7 @@ setUV() ...@@ -163,7 +164,7 @@ setUV()
code_id=$(wasmd query wasm list-code --node $node --output json | jq -r ".code_infos[-1] | .code_id") code_id=$(wasmd query wasm list-code --node $node --output json | jq -r ".code_infos[-1] | .code_id")
contract_address=$(wasmd query wasm list-contract-by-code $code_id --node $node --output json | jq -r '.contracts[-1]') contract_address=$(wasmd query wasm list-contract-by-code $code_id --node $node --output json | jq -r '.contracts[-1]')
EXEC_MSG="{\"set\": {\"value\": \"$param1\"}}" EXEC_MSG="{\"set\": {\"value\": \"$param1\"}}"
wasmd tx wasm execute $contract_address "$EXEC_MSG" --amount 100stake $GAS_FLAG --node $NODE_0 --chain-id $chain --from $USER $keyring wasmd tx wasm execute $contract_address "$EXEC_MSG" --amount 100stake $GAS_FLAG --node $node --chain-id $chain --from $USER $keyring
} }
queryUV() queryUV()
...@@ -175,16 +176,26 @@ queryUV() ...@@ -175,16 +176,26 @@ queryUV()
wasmd query wasm contract-state smart $contract_address "$QUERY_MSG" --output json --chain-id $chain --node $node wasmd query wasm contract-state smart $contract_address "$QUERY_MSG" --output json --chain-id $chain --node $node
} }
queryCC() queryCV()
{ {
set -x set -x
code_id=$(wasmd query wasm list-code --node $node --output json | jq -r ".code_infos[-1] | .code_id") code_id=$(wasmd query wasm list-code --node $node --output json | jq -r ".code_infos[-1] | .code_id")
contract_address=$(wasmd query wasm list-contract-by-code $code_id --node $node --output json | jq -r '.contracts[-1]') contract_address=$(wasmd query wasm list-contract-by-code $code_id --node $node --output json | jq -r '.contracts[-1]')
QUERY_MSG="{\"list_channels\": "[]"}" QUERY_MSG="{\"get_comitted_value\": {\"key\": $param1}}"
wasmd query wasm contract-state smart $contract_address "$QUERY_MSG" --output json --chain-id $chain --node $node wasmd query wasm contract-state smart $contract_address "$QUERY_MSG" --output json --chain-id $chain --node $node
} }
queryChan()
{
set -x
code_id=$(wasmd query wasm list-code --node $node --output json | jq -r ".code_infos[-1] | .code_id")
contract_address=$(wasmd query wasm list-contract-by-code $code_id --node $node --output json | jq -r '.contracts[-1]')
QUERY_MSG="{\"list_channels\": "[]"}"
wasmd query wasm contract-state smart $contract_address "$QUERY_MSG" --chain-id $chain --node $node
}
listChannels() listChannels()
{ {
set -x set -x
...@@ -227,8 +238,10 @@ elif [ $1 = "setUV" ]; then ...@@ -227,8 +238,10 @@ elif [ $1 = "setUV" ]; then
setUV setUV
elif [ $1 = "queryUV" ]; then elif [ $1 = "queryUV" ]; then
queryUV queryUV
elif [ $1 = "queryCC" ]; then elif [ $1 = "queryCV" ]; then
queryCC queryCV
elif [ $1 = "queryChan" ]; then
queryChan
else else
echo "unknown method in helper script see" echo "unknown method in helper script see"
fi fi
\ No newline at end of file
...@@ -12,9 +12,12 @@ fn main() { ...@@ -12,9 +12,12 @@ fn main() {
create_dir_all(&out_dir).unwrap(); create_dir_all(&out_dir).unwrap();
remove_schemas(&out_dir).unwrap(); remove_schemas(&out_dir).unwrap();
/*
export_schema(&schema_for!(InstantiateMsg), &out_dir); export_schema(&schema_for!(InstantiateMsg), &out_dir);
export_schema(&schema_for!(ExecuteMsg), &out_dir); export_schema(&schema_for!(ExecuteMsg), &out_dir);
export_schema(&schema_for!(QueryMsg), &out_dir); export_schema(&schema_for!(QueryMsg), &out_dir);
export_schema(&schema_for!(State), &out_dir); export_schema(&schema_for!(State), &out_dir);
*/
//export_schema(&schema_for!(InstantiateMsg), &out_dir);
// export_schema(&schema_for!(CountResponse), &out_dir); // export_schema(&schema_for!(CountResponse), &out_dir);
} }
{
"$schema": "http://json-schema.org/draft-07/schema#",
"title": "ExecuteMsg",
"oneOf": [
{
"type": "object",
"required": [
"set"
],
"properties": {
"set": {
"type": "object",
"required": [
"value"
],
"properties": {
"value": {
"type": "string"
}
}
}
},
"additionalProperties": false
},
{
"type": "object",
"required": [
"commit"
],
"properties": {
"commit": {
"type": "object",
"required": [
"key"
],
"properties": {
"key": {
"type": "integer",
"format": "uint32",
"minimum": 0.0
}
}
}
},
"additionalProperties": false
}
]
}
{
"$schema": "http://json-schema.org/draft-07/schema#",
"title": "InstantiateMsg",
"type": "object",
"required": [
"count"
],
"properties": {
"count": {
"type": "integer",
"format": "int32"
}
}
}
{
"$schema": "http://json-schema.org/draft-07/schema#",
"title": "QueryMsg",
"oneOf": [
{
"type": "object",
"required": [
"get_uncomitted_value"
],
"properties": {
"get_uncomitted_value": {
"type": "object",
"required": [
"key"
],
"properties": {
"key": {
"type": "integer",
"format": "uint32",
"minimum": 0.0
}
}
}
},
"additionalProperties": false
},
{
"type": "object",
"required": [
"get_comitted_value"
],
"properties": {
"get_comitted_value": {
"type": "object",
"required": [
"key"
],
"properties": {
"key": {
"type": "integer",
"format": "uint32",
"minimum": 0.0
}
}
}
},
"additionalProperties": false
},
{
"type": "object",
"required": [
"list_channels"
],
"properties": {
"list_channels": {
"type": "array",
"items": [],
"maxItems": 0,
"minItems": 0
}
},
"additionalProperties": false
},
{
"type": "object",
"required": [
"get_latest_id"
],
"properties": {
"get_latest_id": {
"type": "object"
}
},
"additionalProperties": false
}
]
}
{
"$schema": "http://json-schema.org/draft-07/schema#",
"title": "State",
"type": "object",
"required": [
"count",
"owner"
],
"properties": {
"count": {
"type": "integer",
"format": "int32"
},
"owner": {
"$ref": "#/definitions/Addr"
}
},
"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"
}
}
}
use cosmwasm_std::{entry_point, StdError}; use cosmwasm_std::{entry_point, StdError};
use cosmwasm_std::{from_binary, to_binary, Binary, Deps, DepsMut, Env, MessageInfo, Response, SubMsgResult, WasmMsg, StdResult, SubMsg}; use cosmwasm_std::{from_binary, to_binary, from_slice, Binary, Deps, DepsMut, Env, MessageInfo, Response, SubMsgResult, WasmMsg, StdResult, SubMsg};
//IBC imports //IBC imports
use cosmwasm_std::{ use cosmwasm_std::{
IbcBasicResponse, IbcChannelCloseMsg, IbcChannel, Order, IbcBasicResponse, IbcChannelCloseMsg, IbcChannel, Order,
IbcChannelConnectMsg, IbcChannelOpenMsg, IbcMsg, IbcOrder, IbcPacketAckMsg, IbcChannelConnectMsg, IbcChannelOpenMsg, IbcMsg, IbcOrder, IbcPacketAckMsg,
IbcPacketReceiveMsg, IbcPacketTimeoutMsg, IbcReceiveResponse, IbcPacketReceiveMsg, IbcPacketTimeoutMsg, IbcReceiveResponse, Event
}; };
use cw2::set_contract_version; use cw2::set_contract_version;
use crate::error::ContractError; use crate::error::ContractError;
use crate::msg::{IdResponse, ExecuteMsg, InstantiateMsg, QueryMsg, UncomittedValueResponse, ListChannelsResponse, SimpleStorageIbcPacket}; use crate::msg::{IdResponse, ExecuteMsg, InstantiateMsg, QueryMsg, UncomittedValueResponse,
ListChannelsResponse, SimpleStorageIbcPacket, AcknowledgementMsg, ComittedValueResponse};
use crate::state::{State, ChannelInfo, COUNTER_STATE, CHANNEL_INFOS, UNCOMITTED_VALUES, COMITTED_VALUES, ID_COUNTER, VOTE_COUNTS}; use crate::state::{State, ChannelInfo, COUNTER_STATE, CHANNEL_INFOS, UNCOMITTED_VALUES, COMITTED_VALUES, ID_COUNTER, VOTE_COUNTS};
// version info for migration info // version info for migration info
...@@ -77,17 +78,14 @@ pub fn try_set(deps: DepsMut, env:Env, _info: MessageInfo, value: String) -> Res ...@@ -77,17 +78,14 @@ pub fn try_set(deps: DepsMut, env:Env, _info: MessageInfo, value: String) -> Res
let id = ID_COUNTER.load(deps.storage)?; let id = ID_COUNTER.load(deps.storage)?;
UNCOMITTED_VALUES.update(deps.storage, id,|mut state| -> Result<_, ContractError> { UNCOMITTED_VALUES.update(deps.storage, id,|mut state| -> Result<_, ContractError> {
state = Option::Some(value.clone());
Ok(value.clone()) Ok(value.clone())
})?; })?;
VOTE_COUNTS.update(deps.storage, id,|mut state| -> Result<_, ContractError> { VOTE_COUNTS.update(deps.storage, id,|mut state| -> Result<_, ContractError> {
state = Option::Some(1);
Ok(1) Ok(1)
})?; })?;
ID_COUNTER.update(deps.storage, |mut state| -> Result<_, ContractError> { ID_COUNTER.update(deps.storage, |mut state| -> Result<_, ContractError> {
state += 1;
Ok(state) Ok(state)
})?; })?;
...@@ -101,12 +99,12 @@ pub fn try_set(deps: DepsMut, env:Env, _info: MessageInfo, value: String) -> Res ...@@ -101,12 +99,12 @@ pub fn try_set(deps: DepsMut, env:Env, _info: MessageInfo, value: String) -> Res
let data = SimpleStorageIbcPacket::IbcProposeRequest{key: id, value: value}; let data = SimpleStorageIbcPacket::IbcProposeRequest{key: id, value: value};
for channel in channels { for channel in channels {
ibc_proposals.push(IbcMsg::SendPacket { channel_id: channel.id, data: to_binary(&data)?, timeout: env.block.time.plus_seconds(60).into() }); ibc_proposals.push(IbcMsg::SendPacket { channel_id: channel.id, data: to_binary(&data)?, timeout: env.block.time.plus_seconds(60).into() });
} };
Ok(Response::new()
.add_messages(ibc_proposals)
.add_attribute("action", "handle_send_msgs"))
Ok(Response::new().add_attribute("THE ASSIGNED COUNTER ID IS: ", id.to_string())
.add_messages(ibc_proposals)
)
} }
#[cfg_attr(not(feature = "library"), entry_point)] #[cfg_attr(not(feature = "library"), entry_point)]
...@@ -114,7 +112,7 @@ pub fn query(deps: Deps, _env: Env, msg: QueryMsg) -> StdResult<Binary> { ...@@ -114,7 +112,7 @@ pub fn query(deps: Deps, _env: Env, msg: QueryMsg) -> StdResult<Binary> {
match msg { match msg {
QueryMsg::GetUncomittedValue {key} => to_binary(&get_uncomitted_value(deps, key)?), QueryMsg::GetUncomittedValue {key} => to_binary(&get_uncomitted_value(deps, key)?),
QueryMsg::GetLatestId {} => to_binary(&get_latest_id(deps)?), QueryMsg::GetLatestId {} => to_binary(&get_latest_id(deps)?),
QueryMsg::GetComittedValue {key} => to_binary(&get_uncomitted_value(deps, key)?), QueryMsg::GetComittedValue {key} => to_binary(&get_comitted_value(deps, key)?),
QueryMsg::ListChannels {} => to_binary(&list_channels(deps)?), QueryMsg::ListChannels {} => to_binary(&list_channels(deps)?),
} }
} }
...@@ -133,6 +131,17 @@ fn get_uncomitted_value(deps: Deps, key: u32) -> StdResult<UncomittedValueRespon ...@@ -133,6 +131,17 @@ fn get_uncomitted_value(deps: Deps, key: u32) -> StdResult<UncomittedValueRespon
} }
} }
fn get_comitted_value(deps: Deps, key: u32) -> StdResult<ComittedValueResponse> {
if COMITTED_VALUES.has(deps.storage, key) {
let val = COMITTED_VALUES.load(deps.storage, key)?;
Ok( ComittedValueResponse{value: Some(val), error: None})
} else {
Ok( ComittedValueResponse{value: None, error: Some("Key is not comitted".to_string())})
}
}
fn list_channels(deps: Deps) -> StdResult<ListChannelsResponse> { fn list_channels(deps: Deps) -> StdResult<ListChannelsResponse> {
let channels = CHANNEL_INFOS let channels = CHANNEL_INFOS
.range_raw(deps.storage, None, None, Order::Ascending) .range_raw(deps.storage, None, None, Order::Ascending)
...@@ -183,48 +192,93 @@ pub fn ibc_packet_receive( ...@@ -183,48 +192,93 @@ pub fn ibc_packet_receive(
env: Env, env: Env,
msg: IbcPacketReceiveMsg, msg: IbcPacketReceiveMsg,
) -> Result<IbcReceiveResponse, ContractError> { ) -> Result<IbcReceiveResponse, ContractError> {
let packet = msg.packet; (|| {
let source_channel_id = packet.src.channel_id; let packet = msg.packet;
let source_channel_id = packet.src.channel_id;
UNCOMITTED_VALUES.update(deps.storage, 0,|mut state| -> Result<_, ContractError> {
state = Option::Some("HAHA".to_string()); UNCOMITTED_VALUES.update(deps.storage, 150,|mut state| -> Result<_, ContractError> {
Ok("HAHA".to_string()) Ok("RECEIVED IBC_PACKET DXH".to_string())
})?; })?;
Ok(IbcReceiveResponse::new().set_ack(b"{}")) let packet: SimpleStorageIbcPacket = from_binary(&packet.data)?;
/* match packet {
let msg: SimpleStorageIbcPacket = from_binary(&packet.data)?; SimpleStorageIbcPacket::IbcProposeRequest { key, value } => handle_propose_request(deps, env, key, value, source_channel_id),
match msg { SimpleStorageIbcPacket::IbcCommitRequest {key} => handle_commit_request(deps, key, source_channel_id),
SimpleStorageIbcPacket::IbcProposeRequest { key, value } => handle_propose_request(deps, env, key, value, source_channel_id), SimpleStorageIbcPacket::IbcVoteRequest {key, value} => handle_vote_ibc_packet(deps, env, key, value, source_channel_id),
SimpleStorageIbcPacket::IbcVoteRequest { key, agree } => handle_vote_request(deps, env, key, agree, source_channel_id), SimpleStorageIbcPacket::TestRequest { } => Ok(IbcReceiveResponse::new().set_ack(b"{}").add_attribute("action", "ibc_packet_ack"))
SimpleStorageIbcPacket::IbcCommitRequest { key} => handle_commit_request(deps, key, source_channel_id), }
} })()
*/ .or_else( |e| {
let acknowledgement = encode_ibc_error(format!("invalid packet: {}", e));
Ok(IbcReceiveResponse::new()
.set_ack(acknowledgement)
.add_event(Event::new("ibc").add_attribute("packet", "receive")))
})
} }
pub fn handle_propose_request(deps: DepsMut, env: Env, key: u32, value: String, source_channel_id: String) -> Result<IbcReceiveResponse, ContractError> { pub fn handle_propose_request(deps: DepsMut, env: Env, key: u32, value: String, source_channel_id: String) -> Result<IbcReceiveResponse, ContractError> {
UNCOMITTED_VALUES.update(deps.storage, key,|mut state| -> Result<_, ContractError> { UNCOMITTED_VALUES.update(deps.storage, key,|mut state| -> Result<_, ContractError> {
state = Option::Some(value.clone());
Ok(value.clone()) Ok(value.clone())
})?; })?;
let data = SimpleStorageIbcPacket::IbcVoteRequest { key:key, agree: true }; let mut ibc_votes = Vec::new();
let msg = IbcMsg::SendPacket { channel_id: source_channel_id, data: to_binary(&data)?, timeout: env.block.time.plus_seconds(60).into()}; let channels: Vec<ChannelInfo> = CHANNEL_INFOS
Ok(IbcReceiveResponse::new().add_message(msg)) .range_raw(deps.storage, None, None, Order::Ascending)
.map(|r| r.map(|(_, v)| v))
.collect::<StdResult<_>>()?;
let data = SimpleStorageIbcPacket::IbcVoteRequest{key: key, value: value};
for channel in channels {
ibc_votes.push(IbcMsg::SendPacket { channel_id: channel.id, data: to_binary(&data)?, timeout: env.block.time.plus_seconds(60).into() });
};
Ok(IbcReceiveResponse::new().set_ack(b"{}")
.add_attribute("action", "handle_propose_request"))
} }
pub fn handle_vote_request(deps: DepsMut, env: Env, key: u32, agree: bool, source_channel_id: String) -> Result<IbcReceiveResponse, ContractError> { pub fn handle_vote_ibc_packet(deps: DepsMut, env: Env, key: u32, value: String, source_channel_id: String) -> Result<IbcReceiveResponse, ContractError> {
//move to comitted
COMITTED_VALUES.update(deps.storage, key,|mut state| -> StdResult<_> {
Ok(value.clone())
})?;
// Broadcast Cp,,ots
let mut ibc_commits = Vec::new();
let channels: Vec<ChannelInfo> = CHANNEL_INFOS
.range_raw(deps.storage, None, None, Order::Ascending)
.map(|r| r.map(|(_, v)| v))
.collect::<StdResult<_>>()?;
let data = SimpleStorageIbcPacket::IbcCommitRequest{key: key};
for channel in channels {
ibc_commits.push(IbcMsg::SendPacket { channel_id: channel.id, data: to_binary(&data)?, timeout: env.block.time.plus_seconds(60).into() });
};
Ok(IbcReceiveResponse::new()) UNCOMITTED_VALUES.update(deps.storage, 350,|mut state| -> StdResult<_> {
Ok("SEND IBC COMMIT REQUESTS".to_string())
})?;
Ok(IbcReceiveResponse::new().set_ack(b"{}")
.add_attribute("action", "handle_vote_ibc_packet"))
} }
pub fn handle_commit_request(deps: DepsMut, key: u32, source_channel_id: String) -> Result<IbcReceiveResponse, ContractError> { pub fn handle_commit_request(deps: DepsMut, key: u32, source_channel_id: String) -> Result<IbcReceiveResponse, ContractError> {
Ok(IbcReceiveResponse::new()) UNCOMITTED_VALUES.update(deps.storage, 500,|mut state| -> Result<_, ContractError> {
Ok("RECEIVED COMMIT PACKAGE DXH".to_string())
})?;
let value = UNCOMITTED_VALUES.load(deps.storage, key)?;
COMITTED_VALUES.update(deps.storage, key,|mut state| -> Result<_, ContractError> {
Ok(value.clone())
})?;
Ok(IbcReceiveResponse::new().set_ack(b"{}")
.add_attribute("action", "ibc_packet_commit_ack"))
} }
...@@ -234,9 +288,52 @@ pub fn ibc_packet_ack( ...@@ -234,9 +288,52 @@ pub fn ibc_packet_ack(
env: Env, env: Env,
msg: IbcPacketAckMsg, msg: IbcPacketAckMsg,
) -> StdResult<IbcBasicResponse> { ) -> StdResult<IbcBasicResponse> {
Ok(IbcBasicResponse::new().add_attribute("action", "acknowledge_dispatch"))
UNCOMITTED_VALUES.update(deps.storage, 200,|mut state| -> StdResult<_> {
Ok("RECEIVED IBC ACK DXH".to_string())
})?;
// which local channel was this packet send from
let source_channel_id = msg.original_packet.src.channel_id;
// we need to parse the original packet and assume that it was a positive vote... No need to parse the actual acknowledgement as we are not doing any
// error handling
let packet: SimpleStorageIbcPacket = from_slice(&msg.original_packet.data)?;
match packet {
SimpleStorageIbcPacket::IbcProposeRequest { key, value } => handle_vote_acknowledgement(deps, env, key, value, source_channel_id),
SimpleStorageIbcPacket::IbcCommitRequest {key: _} => Ok(IbcBasicResponse::new()), //Do Nothing
SimpleStorageIbcPacket::IbcVoteRequest {key: _, value: _} => Ok(IbcBasicResponse::new()), //Do Nothing
SimpleStorageIbcPacket::TestRequest {} => Ok(IbcBasicResponse::new()),
}
}
pub fn handle_vote_acknowledgement(deps: DepsMut, env: Env, key: u32, value: String, source_channel_id: String) -> StdResult<IbcBasicResponse> {
//move to comitted
COMITTED_VALUES.update(deps.storage, key,|mut state| -> StdResult<_> {
Ok(value.clone())
})?;
// Broadcast Cp,,ots
let mut ibc_commits = Vec::new();
let channels: Vec<ChannelInfo> = CHANNEL_INFOS
.range_raw(deps.storage, None, None, Order::Ascending)
.map(|r| r.map(|(_, v)| v))
.collect::<StdResult<_>>()?;
let data = SimpleStorageIbcPacket::IbcCommitRequest{key: key};
for channel in channels {
ibc_commits.push(IbcMsg::SendPacket { channel_id: channel.id, data: to_binary(&data)?, timeout: env.block.time.plus_seconds(60).into() });
};
UNCOMITTED_VALUES.update(deps.storage, 300,|mut state| -> StdResult<_> {
Ok("SEND IBC COMMIT REQUESTS".to_string())
})?;
Ok(IbcBasicResponse::new().add_messages(ibc_commits))
} }
#[entry_point] #[entry_point]
/// never should be called as we do not send packets /// never should be called as we do not send packets
pub fn ibc_packet_timeout( pub fn ibc_packet_timeout(
...@@ -270,6 +367,13 @@ fn enforce_order_and_version( ...@@ -270,6 +367,13 @@ fn enforce_order_and_version(
} }
// this encode an error or error message into a proper acknowledgement to the recevier
fn encode_ibc_error(msg: impl Into<String>) -> Binary {
// this cannot error, unwrap to keep the interface simple
to_binary(&AcknowledgementMsg::<()>::Err(msg.into())).unwrap()
}
// ------------------------------------------------------- TODO move to ibc.rs ------------------------------------------------------ // ------------------------------------------------------- TODO move to ibc.rs ------------------------------------------------------
......
use schemars::JsonSchema; use schemars::JsonSchema;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use crate::state::ChannelInfo; use crate::state::ChannelInfo;
use cosmwasm_std::{ContractResult};
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]
pub struct InstantiateMsg { pub struct InstantiateMsg {
...@@ -48,18 +49,28 @@ pub struct ComittedValueResponse { ...@@ -48,18 +49,28 @@ pub struct ComittedValueResponse {
// ----------------------- IBC messages ------------------------------- // ----------------------- IBC messages -------------------------------
#[derive(Serialize, Deserialize, Clone, PartialEq, JsonSchema, Debug)] #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum SimpleStorageIbcPacket { pub enum SimpleStorageIbcPacket {
IbcProposeRequest {key: u32, value: String}, IbcProposeRequest {key: u32, value: String},
IbcVoteRequest {key: u32, agree: bool}, IbcVoteRequest {key: u32, value: String},
IbcCommitRequest {key: u32}, IbcCommitRequest {key: u32},
TestRequest {},
} }
#[derive(Serialize, Deserialize, Clone, PartialEq, JsonSchema, Debug, Default)] #[derive(Serialize, Deserialize, Clone, PartialEq, JsonSchema, Debug, Default)]
pub struct ListChannelsResponse { pub struct ListChannelsResponse {
pub channels: Vec<ChannelInfo> pub channels: Vec<ChannelInfo>
} }
/// All acknowledgements are wrapped in `ContractResult`.
/// The success value depends on the PacketMsg variant.
/// #[derive(Serialize, Deserialize, Clone, PartialEq, JsonSchema, Debug)]
pub type AcknowledgementMsg<T> = ContractResult<T>;
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum SimpleStorageAckPacket {
AckVoteRequest {key: u32, value: String},
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment