Skip to content

Commit

Permalink
Merge pull request #2 from octopus-appchains/v2.2.0
Browse files Browse the repository at this point in the history
Upgrade to Octopus Appchain Anchor template v2.2.0
  • Loading branch information
riversyang authored Sep 13, 2022
2 parents 9be0959 + 18493c0 commit 894482d
Show file tree
Hide file tree
Showing 31 changed files with 1,088 additions and 1,037 deletions.
323 changes: 109 additions & 214 deletions Cargo.lock

Large diffs are not rendered by default.

3 changes: 2 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ near-primitives = "0.5.0"
near-units = "0.2.0"
hex = "0.4.2"
num-format = "0.4.0"
parity-scale-codec = "2.0.0"
secp256k1-test = { package = "secp256k1", version = "0.20.3", features = ["rand-std", "recovery"] }
beefy-light-client = { git = "https://github.com/octopus-network/beefy-light-client.git", branch = "main" }
codec = { package = "parity-scale-codec", version = "3.0.0", default-features = false, features = ["derive"] }
Expand All @@ -24,7 +25,7 @@ mock-oct-token = { path = "./mock-oct-token" }
wrapped-appchain-token = { git = "https://github.com/octopus-network/wrapped-appchain-token.git", branch = "v2.0.0" }
wrapped-appchain-nft = { git = "https://github.com/octopus-network/wrapped-appchain-nft.git", branch = "main" }
tokio = { version = "1.14", features = ["full"] }
workspaces = "0.3"
workspaces = "0.4"

[profile.release]
codegen-units = 1
Expand Down
30 changes: 17 additions & 13 deletions appchain-anchor/src/appchain_messages.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,18 +14,18 @@ pub enum PayloadType {
#[derive(Clone, Serialize, Deserialize, BorshDeserialize, BorshSerialize)]
#[serde(crate = "near_sdk::serde")]
pub struct BurnAssetPayload {
token_id: String,
sender: String,
receiver_id: AccountId,
amount: u128,
pub token_id: String,
pub sender: String,
pub receiver_id: AccountId,
pub amount: u128,
}

#[derive(Clone, Serialize, Deserialize, BorshDeserialize, BorshSerialize)]
#[serde(crate = "near_sdk::serde")]
pub struct LockPayload {
sender: String,
receiver_id: AccountId,
amount: u128,
pub sender: String,
pub receiver_id: AccountId,
pub amount: u128,
}

#[derive(Clone, Serialize, Deserialize, BorshDeserialize, BorshSerialize)]
Expand Down Expand Up @@ -81,9 +81,9 @@ pub enum MessagePayload {

#[derive(Encode, Decode, Clone)]
pub struct RawMessage {
nonce: u64,
payload_type: PayloadType,
payload: Vec<u8>,
pub nonce: u64,
pub payload_type: PayloadType,
pub payload: Vec<u8>,
}

impl RawMessage {
Expand All @@ -98,8 +98,12 @@ impl IndexedAndClearable for u32 {
()
}
//
fn clear_extra_storage(&mut self) {
()
fn clear_extra_storage(&mut self) -> MultiTxsOperationProcessingResult {
if env::used_gas() > Gas::ONE_TERA.mul(T_GAS_CAP_FOR_MULTI_TXS_PROCESSING) {
MultiTxsOperationProcessingResult::NeedMoreGas
} else {
MultiTxsOperationProcessingResult::Ok
}
}
}

Expand Down Expand Up @@ -293,7 +297,7 @@ impl AppchainAnchor {
raw_message.nonce as u32,
&AppchainMessageProcessingResult::Error {
nonce: raw_message.nonce as u32,
message: format!("Failed to deserialize raw message paylod: {}", err),
message: format!("Failed to deserialize raw message payload: {}", err),
},
),
}
Expand Down
14 changes: 9 additions & 5 deletions appchain-anchor/src/assets/near_fungible_tokens.rs
Original file line number Diff line number Diff line change
Expand Up @@ -365,28 +365,32 @@ impl FungibleTokenContractResolver for AppchainAnchor {
symbol: String,
sender_id_in_appchain: String,
receiver_id_in_near: AccountId,
_amount: U128,
amount: U128,
appchain_message_nonce: u32,
) {
assert_self();
match env::promise_result(0) {
PromiseResult::NotReady => unreachable!(),
PromiseResult::Successful(_) => {
let message = format!(
"Near fungible token '{}' with amount '{}' for appchain account '{}' is unlocked.",
symbol, amount.0, sender_id_in_appchain
);
self.record_appchain_message_processing_result(
&AppchainMessageProcessingResult::Ok {
nonce: appchain_message_nonce,
message: None,
message: Some(message),
},
);
}
PromiseResult::Failed => {
let reason = format!(
"Maybe the receiver account '{}' is not registered in '{}' token contract.",
"Maybe the receiver account '{}' is not exised, or it is not registered in '{}' token contract.",
&receiver_id_in_near, &symbol
);
let message = format!(
"Failed to unlock near fungible token for appchain account '{}'. {}",
sender_id_in_appchain, reason
"Failed to unlock near fungible token '{}' with amount '{}' for appchain account '{}'. {}",
symbol, amount.0, sender_id_in_appchain, reason
);
self.record_appchain_message_processing_result(
&AppchainMessageProcessingResult::Error {
Expand Down
8 changes: 7 additions & 1 deletion appchain-anchor/src/assets/wrapped_appchain_nfts.rs
Original file line number Diff line number Diff line change
Expand Up @@ -499,10 +499,16 @@ impl WrappedAppchainNFTContractResolver for AppchainAnchor {
match env::promise_result(0) {
PromiseResult::NotReady => unreachable!(),
PromiseResult::Successful(_) => {
let message = format!(
"NFT '{}' from appchain account '{}' with metadata '{}' is minted.",
instance_id,
owner_id_in_appchain,
serde_json::to_string(&token_metadata).unwrap(),
);
self.record_appchain_message_processing_result(
&AppchainMessageProcessingResult::Ok {
nonce: appchain_message_nonce,
message: None,
message: Some(message),
},
);
}
Expand Down
25 changes: 11 additions & 14 deletions appchain-anchor/src/assets/wrapped_appchain_token.rs
Original file line number Diff line number Diff line change
Expand Up @@ -282,22 +282,19 @@ impl WrappedAppchainTokenContractResolver for AppchainAnchor {
wrapped_appchain_token.changed_balance.0 + i128::try_from(amount.0).unwrap(),
);
self.wrapped_appchain_token.set(&wrapped_appchain_token);
let message = match sender_id_in_appchain {
Some(sender_id) => format!(
"Wrapped appchain token minted by '{}' of appchain for '{}' with amount '{}'.",
if let Some(sender_id) = sender_id_in_appchain {
// Only generate appchain message processing result in cross-chain transfer case
let message = format!(
"Wrapped appchain token is minted by '{}' of appchain for '{}' with amount '{}'.",
&sender_id, &receiver_id_in_near, &amount.0
),
None => format!(
"Wrapped appchain token minted by crosschain message for '{}' with amount '{}'.",
&receiver_id_in_near, &amount.0
),
);
self.record_appchain_message_processing_result(
&AppchainMessageProcessingResult::Ok {
nonce: appchain_message_nonce,
message: Some(message),
},
);
};
self.record_appchain_message_processing_result(
&AppchainMessageProcessingResult::Ok {
nonce: appchain_message_nonce,
message: Some(message),
},
);
}
PromiseResult::Failed => {
let reason = format!("Maybe the total supply will overflow.");
Expand Down
41 changes: 7 additions & 34 deletions appchain-anchor/src/interfaces.rs
Original file line number Diff line number Diff line change
Expand Up @@ -331,10 +331,6 @@ pub trait StakingManager {
pub trait SudoActions {
///
fn set_owner_pk(&mut self, public_key: PublicKey);
/// Apply a certain `AppchainMessage`
fn stage_appchain_message(&mut self, appchain_message: AppchainMessage);
///
fn stage_appchain_encoded_messages(&mut self, encoded_messages: Vec<u8>);
///
fn set_metadata_of_wrapped_appchain_token(&mut self, metadata: FungibleTokenMetadata);
///
Expand All @@ -344,32 +340,14 @@ pub trait SudoActions {
value: U128,
);
///
fn reset_validator_set_histories_to(&mut self, era_number: U64);
///
fn reset_staking_histories_to(&mut self, era_number: U64);
///
fn refresh_user_staking_histories(&mut self);
///
fn reset_next_validator_set_to(&mut self, era_number: U64);
///
fn clear_appchain_notification_histories(&mut self);
fn regenerate_user_staking_histories(&mut self) -> MultiTxsOperationProcessingResult;
///
fn reset_beefy_light_client(&mut self, initial_public_keys: Vec<String>);
///
fn clear_reward_distribution_records(&mut self, era_number: U64);
///
fn clear_unbonded_stakes(&mut self);
///
fn clear_unwithdrawn_rewards(&mut self, era_number: U64);
///
fn reset_validator_profiles_to(&mut self, era_number: U64);
///
fn pause_asset_transfer(&mut self);
///
fn resume_asset_transfer(&mut self);
///
fn remove_staking_history_at(&mut self, index: U64);
///
fn pause_rewards_withdrawal(&mut self);
///
fn resume_rewards_withdrawal(&mut self);
Expand All @@ -380,19 +358,14 @@ pub trait SudoActions {
account_id_in_appchain: String,
);
///
fn force_change_account_id_in_appchain_of_staking_history(
&mut self,
index: U64,
account_id_in_appchain: String,
);
///
fn remove_duplicated_message_nonces_in_reward_distribution_records(&mut self, era_number: U64);
///
fn set_latest_applied_appchain_message_nonce(&mut self, nonce: u32);
///
fn clear_appchain_messages(&mut self) -> MultiTxsOperationProcessingResult;
///
fn try_complete_switching_era(&mut self) -> MultiTxsOperationProcessingResult;
fn unlock_auto_unbonded_stake_of(
&mut self,
delegator_id: Option<AccountId>,
validator_id: AccountId,
staking_history_index: U64,
);
}

pub trait ValidatorActions {
Expand Down
26 changes: 19 additions & 7 deletions appchain-anchor/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
mod anchor_viewer;
pub mod appchain_challenge;
mod appchain_messages;
pub mod appchain_messages;
mod assets;
pub mod interfaces;
mod lookup_array;
Expand Down Expand Up @@ -613,8 +613,12 @@ impl IndexedAndClearable for AppchainNotificationHistory {
self.index = U64::from(*index);
}
//
fn clear_extra_storage(&mut self) {
()
fn clear_extra_storage(&mut self) -> MultiTxsOperationProcessingResult {
if env::used_gas() > Gas::ONE_TERA.mul(T_GAS_CAP_FOR_MULTI_TXS_PROCESSING) {
MultiTxsOperationProcessingResult::NeedMoreGas
} else {
MultiTxsOperationProcessingResult::Ok
}
}
}

Expand All @@ -624,8 +628,12 @@ impl IndexedAndClearable for StakingHistory {
self.index = U64::from(*index);
}
//
fn clear_extra_storage(&mut self) {
()
fn clear_extra_storage(&mut self) -> MultiTxsOperationProcessingResult {
if env::used_gas() > Gas::ONE_TERA.mul(T_GAS_CAP_FOR_MULTI_TXS_PROCESSING) {
MultiTxsOperationProcessingResult::NeedMoreGas
} else {
MultiTxsOperationProcessingResult::Ok
}
}
}

Expand All @@ -635,7 +643,11 @@ impl IndexedAndClearable for AppchainChallenge {
()
}
//
fn clear_extra_storage(&mut self) {
()
fn clear_extra_storage(&mut self) -> MultiTxsOperationProcessingResult {
if env::used_gas() > Gas::ONE_TERA.mul(T_GAS_CAP_FOR_MULTI_TXS_PROCESSING) {
MultiTxsOperationProcessingResult::NeedMoreGas
} else {
MultiTxsOperationProcessingResult::Ok
}
}
}
41 changes: 28 additions & 13 deletions appchain-anchor/src/lookup_array.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ pub trait IndexedAndClearable {
///
fn set_index(&mut self, index: &u64);
///
fn clear_extra_storage(&mut self);
fn clear_extra_storage(&mut self) -> MultiTxsOperationProcessingResult;
}

#[derive(BorshDeserialize, BorshSerialize)]
Expand Down Expand Up @@ -97,25 +97,33 @@ where
self.lookup_map.get(&index).unwrap()
}
///
pub fn remove_before(&mut self, index: &u64) {
pub fn remove_before(&mut self, index: &u64) -> MultiTxsOperationProcessingResult {
if self.start_index >= *index {
return;
return MultiTxsOperationProcessingResult::Ok;
}
for index in self.start_index..*index {
self.remove_at(&index);
let result = self.remove_at(&index);
if !result.is_ok() {
return result;
}
}
self.start_index = *index;
MultiTxsOperationProcessingResult::Ok
}
///
pub fn reset_to(&mut self, index: &u64) {
pub fn reset_to(&mut self, index: &u64) -> MultiTxsOperationProcessingResult {
assert!(
*index >= self.start_index && *index <= self.end_index,
"Invalid history data index."
);
for index in (*index + 1)..self.end_index + 1 {
self.remove_at(&index);
let result = self.remove_at(&index);
if !result.is_ok() {
return result;
}
}
self.end_index = *index;
MultiTxsOperationProcessingResult::Ok
}
///
pub fn clear(&mut self) -> MultiTxsOperationProcessingResult {
Expand All @@ -125,10 +133,7 @@ where
self.end_index
);
let mut index = self.start_index;
while index <= self.end_index
&& env::used_gas() < Gas::ONE_TERA.mul(T_GAS_CAP_FOR_MULTI_TXS_PROCESSING)
{
self.remove_at(&index);
while index <= self.end_index && self.remove_at(&index).is_ok() {
index += 1;
}
if env::used_gas() > Gas::ONE_TERA.mul(T_GAS_CAP_FOR_MULTI_TXS_PROCESSING) {
Expand All @@ -141,10 +146,20 @@ where
}
}
///
pub fn remove_at(&mut self, index: &u64) {
pub fn remove_at(&mut self, index: &u64) -> MultiTxsOperationProcessingResult {
if let Some(mut record) = self.lookup_map.get(index) {
record.clear_extra_storage();
self.lookup_map.remove_raw(&index.try_to_vec().unwrap());
let result = record.clear_extra_storage();
match result {
MultiTxsOperationProcessingResult::Ok => {
self.lookup_map.remove_raw(&index.try_to_vec().unwrap());
}
MultiTxsOperationProcessingResult::NeedMoreGas => {
self.lookup_map.insert(index, &record);
}
MultiTxsOperationProcessingResult::Error(_) => (),
}
return result;
}
MultiTxsOperationProcessingResult::Ok
}
}
Loading

0 comments on commit 894482d

Please sign in to comment.