Skip to content

Commit

Permalink
reverted aioracle logic to prod version & fixed test cases
Browse files Browse the repository at this point in the history
  • Loading branch information
ducphamle2 committed Apr 13, 2023
1 parent 0ac45af commit 5183c3b
Show file tree
Hide file tree
Showing 5 changed files with 302 additions and 357 deletions.
279 changes: 136 additions & 143 deletions package/aioracle/aioracle_v2/src/contract.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use aioracle_base::{Executor, Reward, ServiceMsg};
use aioracle_base::{Executor, GetServiceFeesMsg, Reward, ServiceMsg};
use cosmwasm_std::{
attr, from_slice, to_binary, BankMsg, Binary, Coin, CosmosMsg, Decimal, Deps, DepsMut, Env,
HandleResponse, HumanAddr, InitResponse, MessageInfo, MigrateResponse, Order, StdError,
Expand All @@ -22,9 +22,9 @@ use crate::executors::{
remove_executors, save_executors, update_executors,
};
use crate::msg::{
CurrentStageResponse, GetParticipantFee, GetServiceContracts, GetServiceFees,
GetServiceFeesMsg, HandleMsg, InitMsg, IsClaimedResponse, LatestStageResponse, MigrateMsg,
QueryMsg, Report, RequestResponse, StageInfo, UpdateConfigMsg,
CurrentStageResponse, GetParticipantFee, GetServiceContracts, GetServiceFees, HandleMsg,
InitMsg, IsClaimedResponse, LatestStageResponse, MigrateMsg, QueryMsg, Report, RequestResponse,
StageInfo, UpdateConfigMsg,
};
use crate::state::{
executors_map, requests, Config, Contracts, Request, CHECKPOINT, CLAIM, CONFIG, CONTRACT_FEES,
Expand Down Expand Up @@ -134,11 +134,11 @@ pub fn handle(
}
HandleMsg::ExecutorJoin { executor } => handle_executor_join(deps, env, info, executor),
HandleMsg::ExecutorLeave { executor } => handle_executor_leave(deps, env, info, executor),
// HandleMsg::SubmitEvidence {
// stage,
// report,
// proof,
// } => handle_submit_evidence(deps, env, info, stage, report, proof),
HandleMsg::SubmitEvidence {
stage,
report,
proof,
} => handle_submit_evidence(deps, env, info, stage, report, proof),
}
}

Expand Down Expand Up @@ -279,31 +279,35 @@ pub fn handle_request(
fee.amount = fee.amount + contract_fee.amount;
Ok(fee)
})?;
//////////////////////////////////////////////////// deprecated. We dont care abt rewards anymore
// // reward plus preference must match sent funds
// let bound_executor_fee: Coin = query_bound_executor_fee(deps.as_ref())?;
// if preference_executor_fee.denom.ne(&bound_executor_fee.denom)
// || preference_executor_fee
// .amount
// .lt(&bound_executor_fee.amount)
// {
// return Err(ContractError::InsufficientFundsBoundFees {});
// }
// // collect fees
// let mut rewards = get_service_fees(deps.as_ref(), &service)?;
// if !bound_executor_fee.amount.is_zero() {
// rewards.push((
// HumanAddr::from("placeholder"),
// bound_executor_fee.denom,
// bound_executor_fee.amount,
// ));
// }
// // TODO: add substract contract fee & verify against it
// if !verify_request_fees(&info.sent_funds, &rewards, threshold, &contract_fee) {
// return Err(ContractError::InsufficientFundsRequestFees {});
// }

// rewards.pop(); // pop so we dont store the placeholder reward in the list

// reward plus preference must match sent funds
let bound_executor_fee: Coin = query_bound_executor_fee(deps.as_ref())?;

if preference_executor_fee.denom.ne(&bound_executor_fee.denom)
|| preference_executor_fee
.amount
.lt(&bound_executor_fee.amount)
{
return Err(ContractError::InsufficientFundsBoundFees {});
}

// collect fees
let mut rewards = get_service_fees(deps.as_ref(), &service)?;

if !bound_executor_fee.amount.is_zero() {
rewards.push((
HumanAddr::from("placeholder"),
bound_executor_fee.denom,
bound_executor_fee.amount,
));
}

// TODO: add substract contract fee & verify against it
if !verify_request_fees(&info.sent_funds, &rewards, threshold, &contract_fee) {
return Err(ContractError::InsufficientFundsRequestFees {});
}

rewards.pop(); // pop so we dont store the placeholder reward in the list

// this will keep track of the executor list of the request
let current_size = query_executor_size(deps.as_ref())?;
Expand All @@ -330,7 +334,7 @@ pub fn handle_request(
threshold,
service: service.clone(),
input,
rewards: vec![],
rewards,
},
)?;

Expand All @@ -346,81 +350,81 @@ pub fn handle_request(
})
}

// pub fn handle_submit_evidence(
// deps: DepsMut,
// env: Env,
// info: MessageInfo,
// stage: u64,
// report: Binary,
// proofs: Option<Vec<String>>,
// ) -> Result<HandleResponse, ContractError> {
// let Config {
// trusting_period,
// slashing_amount,
// denom,
// ..
// } = CONFIG.load(deps.storage)?;

// let is_verified = verify_data(deps.as_ref(), stage, report.clone(), proofs)?;
// if !is_verified {
// return Err(ContractError::Unauthorized {});
// }

// let report_struct: Report = from_slice(report.as_slice())
// .map_err(|err| ContractError::Std(StdError::generic_err(err.to_string())))?;

// // check evidence, only allow evidence per executor
// let mut evidence_key = report_struct.executor.clone().to_base64();
// evidence_key.push_str(&stage.to_string());
// let is_claimed = EVIDENCES.may_load(deps.storage, evidence_key.as_bytes())?;

// if let Some(is_claimed) = is_claimed {
// if is_claimed {
// return Err(ContractError::AlreadyFinishedEvidence {});
// }
// }

// let Request {
// submit_merkle_height,
// ..
// } = requests().load(deps.storage, &stage.to_be_bytes())?;

// let is_exist = executors_map().may_load(deps.storage, report_struct.executor.as_slice())?;
// let mut cosmos_msgs: Vec<CosmosMsg> = vec![];

// // only slash if the executor cannot be found in the whitelist
// if is_exist.is_none() && (submit_merkle_height + trusting_period).gt(&env.block.height) {
// // query contract balance to slash
// let balance = deps
// .querier
// .query_balance(env.contract.address.clone(), denom.as_str())
// .map_err(|err| ContractError::Std(StdError::generic_err(err.to_string())))?;
// // if executor does not exist & still in trusting period => can slash amount in contract by sending the percentage amount to the reporter who discovers the faulty stage.
// let total_slash = balance.amount.mul(Decimal::permille(slashing_amount));
// if !total_slash.is_zero() {
// let send_msg = BankMsg::Send {
// from_address: env.contract.address,
// to_address: info.sender,
// amount: vec![Coin {
// denom: balance.denom,
// amount: total_slash,
// }],
// };
// cosmos_msgs.push(send_msg.into());
// }

// EVIDENCES.save(deps.storage, evidence_key.as_bytes(), &true)?;
// }

// Ok(HandleResponse {
// data: None,
// messages: cosmos_msgs,
// attributes: vec![
// attr("action", "handle_submit_evidence"),
// attr("stage", stage.to_string()),
// ],
// })
// }
pub fn handle_submit_evidence(
deps: DepsMut,
env: Env,
info: MessageInfo,
stage: u64,
report: Binary,
proofs: Option<Vec<String>>,
) -> Result<HandleResponse, ContractError> {
let Config {
trusting_period,
slashing_amount,
denom,
..
} = CONFIG.load(deps.storage)?;

let is_verified = verify_data(deps.as_ref(), stage, report.clone(), proofs)?;
if !is_verified {
return Err(ContractError::Unauthorized {});
}

let report_struct: Report = from_slice(report.as_slice())
.map_err(|err| ContractError::Std(StdError::generic_err(err.to_string())))?;

// check evidence, only allow evidence per executor
let mut evidence_key = report_struct.executor.clone().to_base64();
evidence_key.push_str(&stage.to_string());
let is_claimed = EVIDENCES.may_load(deps.storage, evidence_key.as_bytes())?;

if let Some(is_claimed) = is_claimed {
if is_claimed {
return Err(ContractError::AlreadyFinishedEvidence {});
}
}

let Request {
submit_merkle_height,
..
} = requests().load(deps.storage, &stage.to_be_bytes())?;

let is_exist = executors_map().may_load(deps.storage, report_struct.executor.as_slice())?;
let mut cosmos_msgs: Vec<CosmosMsg> = vec![];

// only slash if the executor cannot be found in the whitelist
if is_exist.is_none() && (submit_merkle_height + trusting_period).gt(&env.block.height) {
// query contract balance to slash
let balance = deps
.querier
.query_balance(env.contract.address.clone(), denom.as_str())
.map_err(|err| ContractError::Std(StdError::generic_err(err.to_string())))?;
// if executor does not exist & still in trusting period => can slash amount in contract by sending the percentage amount to the reporter who discovers the faulty stage.
let total_slash = balance.amount.mul(Decimal::permille(slashing_amount));
if !total_slash.is_zero() {
let send_msg = BankMsg::Send {
from_address: env.contract.address,
to_address: info.sender,
amount: vec![Coin {
denom: balance.denom,
amount: total_slash,
}],
};
cosmos_msgs.push(send_msg.into());
}

EVIDENCES.save(deps.storage, evidence_key.as_bytes(), &true)?;
}

Ok(HandleResponse {
data: None,
messages: cosmos_msgs,
attributes: vec![
attr("action", "handle_submit_evidence"),
attr("stage", stage.to_string()),
],
})
}

pub fn execute_register_merkle_root(
deps: DepsMut,
Expand Down Expand Up @@ -452,7 +456,7 @@ pub fn execute_register_merkle_root(
}

// if merkle root empty then update new
requests().update(deps.storage, &stage.to_be_bytes(), |request| {
let request = requests().update(deps.storage, &stage.to_be_bytes(), |request| {
if let Some(mut request) = request {
request.merkle_root = mroot.clone();
request.submit_merkle_height = env.block.height;
Expand All @@ -463,23 +467,22 @@ pub fn execute_register_merkle_root(
Err(StdError::generic_err("Invalid request empty"))
})?;

/////////////////////////////////////////////// Deprecated. We no longer care about executor rewards
// // add executors' rewards into the pool
// for executor in executors {
// // only add reward if executor is in list
// let executor_check = executors_map().may_load(deps.storage, &executor)?;
// if executor_check.is_none() || !executor_check.unwrap().is_active {
// continue;
// }
// let executor_reward =
// get_participant_fee(deps.as_ref(), executor.clone(), service_addr.as_str())?;
// process_executors_pool(
// deps.storage,
// executor,
// &request.preference_executor_fee,
// executor_reward,
// )?;
// }
// add executors' rewards into the pool
for executor in executors {
// only add reward if executor is in list
let executor_check = executors_map().may_load(deps.storage, &executor)?;
if executor_check.is_none() || !executor_check.unwrap().is_active {
continue;
}
let executor_reward =
get_participant_fee(deps.as_ref(), executor.clone(), service_addr.as_str())?;
process_executors_pool(
deps.storage,
executor,
&request.preference_executor_fee,
executor_reward,
)?;
}

// check if can increase checkpoint. Can only increase when all requests in range have merkle root
process_checkpoint(deps, stage, checkpoint_threshold)?;
Expand Down Expand Up @@ -550,9 +553,7 @@ pub fn query(deps: Deps, env: Env, msg: QueryMsg) -> StdResult<Binary> {
}
QueryMsg::GetServiceFees { service } => to_binary(&query_service_fees(deps, service)?),
QueryMsg::GetBoundExecutorFee {} => to_binary(&query_bound_executor_fee(deps)?),
QueryMsg::GetParticipantFee { pubkey, service } => {
to_binary(&query_participant_fee(deps, pubkey, service)?)
}
QueryMsg::GetParticipantFee { pubkey } => to_binary(&query_participant_fee(deps, pubkey)?),
QueryMsg::GetTrustingPool { pubkey } => to_binary(&query_trusting_pool(deps, env, pubkey)?),
QueryMsg::GetTrustingPools {
offset,
Expand All @@ -562,18 +563,10 @@ pub fn query(deps: Deps, env: Env, msg: QueryMsg) -> StdResult<Binary> {
}
}

pub fn query_participant_fee(
_deps: Deps,
_pubkey: Binary,
_service: Option<String>,
) -> StdResult<Coin> {
Ok(Coin {
denom: String::from("orai"),
amount: Uint128::from(0u64),
})
// let Config { service_addr, .. } = CONFIG.load(deps.storage)?;
// get_participant_fee(deps, pubkey, service_addr.as_str(), service)
// .map_err(|err| StdError::generic_err(err.to_string()))
pub fn query_participant_fee(deps: Deps, pubkey: Binary) -> StdResult<Coin> {
let Config { service_addr, .. } = CONFIG.load(deps.storage)?;
get_participant_fee(deps, pubkey, service_addr.as_str())
.map_err(|err| StdError::generic_err(err.to_string()))
}

fn get_service_fees(deps: Deps, service: &str) -> StdResult<Vec<Reward>> {
Expand Down
46 changes: 23 additions & 23 deletions package/aioracle/aioracle_v2/src/migrations/v03.rs
Original file line number Diff line number Diff line change
Expand Up @@ -192,27 +192,27 @@ mod test {
TODO run error? recheck ...
*/
// #[test]
fn test_migrate() {
let mut deps = setup_old_contract();
let info = mock_info(HumanAddr::from("foobar"), &[]);
migrate(deps.as_mut(), mock_env(), info, MigrateMsg {}).unwrap();

// query executors

let executors: Vec<Executor> = from_binary(
&query(
deps.as_ref(),
mock_env(),
QueryMsg::GetExecutors {
offset: None,
limit: None,
order: None,
},
)
.unwrap(),
)
.unwrap();

println!("executors: {:?}", executors);
}
// fn test_migrate() {
// let mut deps = setup_old_contract();
// let info = mock_info(HumanAddr::from("foobar"), &[]);
// migrate(deps.as_mut(), mock_env(), info, MigrateMsg {}).unwrap();

// // query executors

// let executors: Vec<Executor> = from_binary(
// &query(
// deps.as_ref(),
// mock_env(),
// QueryMsg::GetExecutors {
// offset: None,
// limit: None,
// order: None,
// },
// )
// .unwrap(),
// )
// .unwrap();

// println!("executors: {:?}", executors);
// }
}
Loading

0 comments on commit 5183c3b

Please sign in to comment.