Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Testing for Eth Backing Module #172

Merged
merged 17 commits into from
Dec 20, 2019
Merged
Show file tree
Hide file tree
Changes from 16 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 10 additions & 1 deletion Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

17 changes: 15 additions & 2 deletions srml/eth-backing/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ edition = "2018"
[dependencies]
# crates.io
codec = { package = "parity-scale-codec", version = "1.0.0", default-features = false, features = ["derive"] }
hex = { version = "0.4", default-features = false }
#hex = { version = "0.4", default-features = false }
serde = { version = "1.0.101", optional = true }

# github.com
Expand All @@ -28,12 +28,25 @@ sr-eth-primitives = { path = "../../core/sr-eth-primitives", default-features =

[dev-dependencies]
hex-literal = "0.2.1"
rustc-hex = "2.0"

balances = { package = "darwinia-balances", path = '../balances' }
kton = { package = "darwinia-kton", path = "../kton" }
staking = { package = "darwinia-staking", path = "../staking" }

authorship = { package = "srml-authorship", git = "https://github.com/darwinia-network/substrate.git", branch = "darwinia-develop"}
session = { package = "srml-session",git = "https://github.com/darwinia-network/substrate.git", branch = "darwinia-develop"}
sr-staking-primitives = { git = "https://github.com/darwinia-network/substrate.git", branch = "darwinia-develop"}
phragmen = { package = "substrate-phragmen", git = "https://github.com/darwinia-network/substrate.git", branch = "darwinia-develop"}
runtime_io = { package = "sr-io", git = "https://github.com/darwinia-network/substrate.git", branch = "darwinia-develop" }
rlp = { package = "rlp", git = "https://github.com/darwinia-network/parity-common.git"}


[features]
default = ["std"]
std = [
"codec/std",
"hex/std",
# "hex/std",
"serde/std",

"ethabi/std",
Expand Down
148 changes: 88 additions & 60 deletions srml/eth-backing/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,8 @@
//use codec::{Decode, Encode};
use ethabi::{Event as EthEvent, EventParam as EthEventParam, ParamType, RawLog};
use rstd::{borrow::ToOwned, convert::TryFrom, marker::PhantomData, result, vec}; // fmt::Debug
use sr_primitives::traits::{SaturatedConversion, Saturating};
use support::{decl_event, decl_module, decl_storage, ensure, traits::Currency, traits::OnUnbalanced}; // dispatch::Result,
use sr_primitives::traits::{CheckedSub, SaturatedConversion};
use support::{decl_event, decl_module, decl_storage, ensure, fail, traits::Currency, traits::OnUnbalanced}; // dispatch::Result,
use system::ensure_signed; // Convert,

//use sr_primitives::RuntimeDebug;
Expand All @@ -25,14 +25,21 @@ use sr_eth_primitives::{EthAddress, H256, U256}; // receipt::LogEntry, receipt::
pub type Balance = u128;
pub type Moment = u64;

type RingBalanceOf<T> = <<T as Trait>::Ring as Currency<<T as system::Trait>::AccountId>>::Balance;
type Ring<T> = <<T as Trait>::Ring as Currency<<T as system::Trait>::AccountId>>::Balance;
type PositiveImbalanceRing<T> = <<T as Trait>::Ring as Currency<<T as system::Trait>::AccountId>>::PositiveImbalance;
//type NegativeImbalanceRing<T> = <<T as Trait>::Ring as Currency<<T as system::Trait>::AccountId>>::NegativeImbalance;

type KtonBalanceOf<T> = <<T as Trait>::Kton as Currency<<T as system::Trait>::AccountId>>::Balance;
type Kton<T> = <<T as Trait>::Kton as Currency<<T as system::Trait>::AccountId>>::Balance;
type PositiveImbalanceKton<T> = <<T as Trait>::Kton as Currency<<T as system::Trait>::AccountId>>::PositiveImbalance;
//type NegativeImbalanceKton<T> = <<T as Trait>::Kton as Currency<<T as system::Trait>::AccountId>>::NegativeImbalance;

type EthTransactionIndex = (H256, u64);

#[cfg(all(feature = "std", test))]
mod mock;
#[cfg(all(feature = "std", test))]
mod tests;

pub trait Trait: timestamp::Trait {
type Event: From<Event<Self>> + Into<<Self as system::Trait>::Event>;
type EthRelay: VerifyEthReceipts;
Expand All @@ -50,12 +57,12 @@ decl_storage! {
pub KtonRedeemAddress get(kton_redeem_address) config(): EthAddress;
pub DepositRedeemAddress get(deposit_redeem_address) config(): EthAddress;

pub RingLocked get(fn ring_locked) config(): RingBalanceOf<T>;
pub KtonLocked get(fn kton_locked) config(): KtonBalanceOf<T>;
pub RingLocked get(fn ring_locked) config(): Ring<T>;
pub KtonLocked get(fn kton_locked) config(): Kton<T>;

pub RingProofVerified get(ring_proof_verfied): map (H256, u64) => Option<EthReceiptProof>;
pub KtonProofVerified get(kton_proof_verfied): map (H256, u64) => Option<EthReceiptProof>;
pub DepositProofVerified get(deposit_proof_verfied): map (H256, u64) => Option<EthReceiptProof>;
pub RingProofVerified get(ring_proof_verfied): map EthTransactionIndex => Option<EthReceiptProof>;
pub KtonProofVerified get(kton_proof_verfied): map EthTransactionIndex => Option<EthReceiptProof>;
pub DepositProofVerified get(deposit_proof_verfied): map EthTransactionIndex => Option<EthReceiptProof>;
}
}

Expand All @@ -64,25 +71,19 @@ decl_event! {
where
<T as system::Trait>::AccountId
{
TODO(AccountId),
}
}

impl<T: Trait> Module<T> {
pub fn adjust_deposit_value() {
unimplemented!()
RedeemRing(AccountId, Balance, EthTransactionIndex),
RedeemKton(AccountId, Balance, EthTransactionIndex),
RedeemDeposit(AccountId, Balance, EthTransactionIndex),
}

// fn _release(_dest: &T::AccountId, _value: RingBalanceOf<T>) -> Result {
// unimplemented!()
// }
}

decl_module! {
pub struct Module<T: Trait> for enum Call
where
origin: T::Origin
{
fn deposit_event() = default;

// event RingBurndropTokens(address indexed token, address indexed owner, uint amount, bytes data)
// https://ropsten.etherscan.io/tx/0x81f699c93b00ab0b7db701f87b6f6045c1e0692862fcaaf8f06755abb0536800
pub fn redeem_ring(origin, proof_record: EthReceiptProof) {
Expand All @@ -94,15 +95,24 @@ decl_module! {
);

let (darwinia_account, redeemed_amount) = Self::parse_token_redeem_proof(&proof_record, "RingBurndropTokens")?;
let redeemed_ring = <RingBalanceOf<T>>::saturated_from(redeemed_amount);
let redeemed_positive_imbalance_ring = T::Ring::deposit_into_existing(&darwinia_account, redeemed_ring)?;

T::RingReward::on_unbalanced(redeemed_positive_imbalance_ring);
let redeemed_ring = <Ring<T>>::saturated_from(redeemed_amount);
if let Some(new_ring_locked) = Self::ring_locked().checked_sub(&redeemed_ring) {

let redeemed_positive_imbalance_ring = T::Ring::deposit_into_existing(&darwinia_account, redeemed_ring)?;

T::RingReward::on_unbalanced(redeemed_positive_imbalance_ring);

RingProofVerified::insert((proof_record.header_hash, proof_record.index), &proof_record);

<RingLocked<T>>::mutate(|l| {
*l = new_ring_locked;
});

RingProofVerified::insert((proof_record.header_hash, proof_record.index), proof_record);
<RingLocked<T>>::mutate(|l| {
*l = l.saturating_sub(redeemed_ring);
});
<Module<T>>::deposit_event(RawEvent::RedeemRing(darwinia_account, redeemed_amount, (proof_record.header_hash, proof_record.index)));
} else {
fail!("RING Locked - NO SUFFICIENT BACKING ASSETS")
}
}

// event KtonBurndropTokens(address indexed token, address indexed owner, uint amount, bytes data)
Expand All @@ -115,15 +125,23 @@ decl_module! {
);

let (darwinia_account, redeemed_amount) = Self::parse_token_redeem_proof(&proof_record, "KtonBurndropTokens")?;
let redeemed_kton = <KtonBalanceOf<T>>::saturated_from(redeemed_amount);
let redeemed_positive_imbalance_kton = T::Kton::deposit_into_existing(&darwinia_account, redeemed_kton)?;

T::KtonReward::on_unbalanced(redeemed_positive_imbalance_kton);
let redeemed_kton = <Kton<T>>::saturated_from(redeemed_amount);
if let Some(new_kton_locked) = Self::kton_locked().checked_sub(&redeemed_kton) {
let redeemed_positive_imbalance_kton = T::Kton::deposit_into_existing(&darwinia_account, redeemed_kton)?;

KtonProofVerified::insert((proof_record.header_hash, proof_record.index), proof_record);
<KtonLocked<T>>::mutate(|l| {
*l = l.saturating_sub(redeemed_kton);
});
T::KtonReward::on_unbalanced(redeemed_positive_imbalance_kton);

KtonProofVerified::insert((proof_record.header_hash, proof_record.index), &proof_record);

<KtonLocked<T>>::mutate(|l| {
hackfisher marked this conversation as resolved.
Show resolved Hide resolved
*l = new_kton_locked;
});

<Module<T>>::deposit_event(RawEvent::RedeemKton(darwinia_account, redeemed_amount, (proof_record.header_hash, proof_record.index)));
} else {
fail!("KTON Locked - NO SUFFICIENT BACKING ASSETS")
}
}

// https://github.com/evolutionlandorg/bank
Expand Down Expand Up @@ -185,7 +203,7 @@ decl_module! {
.ok_or("Convert to Int - FAILED")?;
let redeemed_amount = {
// TODO: div 10**18 and mul 10**9
let amount = result.params[2]
let amount = result.params[5]
.value
.clone()
.to_uint()
Expand All @@ -195,35 +213,39 @@ decl_module! {
Balance::try_from(amount)?
};
let darwinia_account = {
let raw_sub_key = result.params[3]
let raw_sub_key = result.params[6]
.value
.clone()
.to_bytes()
.ok_or("Convert to Bytes - FAILED")?;
let decoded_sub_key = hex::decode(&raw_sub_key).map_err(|_| "Decode Address - FAILED")?;
// let decoded_sub_key = hex::decode(&raw_sub_key).map_err(|_| "Decode Address - FAILED")?;

T::DetermineAccountId::account_id_for(&decoded_sub_key)?
T::DetermineAccountId::account_id_for(&raw_sub_key)?
};
let redeemed_ring = <RingBalanceOf<T>>::saturated_from(redeemed_amount);
let redeemed_positive_imbalance_ring = T::Ring::deposit_into_existing(&darwinia_account, redeemed_ring)?;
let redeemed_ring = <Ring<T>>::saturated_from(redeemed_amount);

if let Some(new_ring_locked) = Self::ring_locked().checked_sub(&redeemed_ring) {
T::OnDepositRedeem::on_deposit_redeem(
month.saturated_into(),
start_at.saturated_into(),
redeemed_amount,
&darwinia_account,
)?;

T::RingReward::on_unbalanced(redeemed_positive_imbalance_ring);
// TODO: check deposit_id duplication

// TODO: check deposit_id duplication
// TODO: Ignore Unit Interest for now

// TODO: Ignore Unit Interest for now
DepositProofVerified::insert((proof_record.header_hash, proof_record.index), &proof_record);

T::OnDepositRedeem::on_deposit_redeem(
month.saturated_into(),
start_at.saturated_into(),
redeemed_amount,
&darwinia_account,
)?;
<RingLocked<T>>::mutate(|l| {
*l = new_ring_locked;
});

DepositProofVerified::insert((proof_record.header_hash, proof_record.index), proof_record);
<RingLocked<T>>::mutate(|l| {
*l = l.saturating_sub(redeemed_ring);
});
<Module<T>>::deposit_event(RawEvent::RedeemDeposit(darwinia_account, redeemed_amount, (proof_record.header_hash, proof_record.index)));
} else {
fail!("RING Locked - NO SUFFICIENT BACKING ASSETS")
}
}
}
}
Expand Down Expand Up @@ -290,17 +312,17 @@ impl<T: Trait> Module<T> {
.clone()
.to_bytes()
.ok_or("Convert to Bytes - FAILED")?;
let decoded_sub_key = hex::decode(&raw_sub_key).map_err(|_| "Decode Address - FAILED")?;

T::DetermineAccountId::account_id_for(&decoded_sub_key)?
// let decoded_sub_key = hex::decode(&raw_sub_key).map_err(|_| "Decode Address - FAILED")?;

T::DetermineAccountId::account_id_for(&raw_sub_key)?
};

Ok((darwinia_account, redeemed_amount))
}
}

pub trait AccountIdFor<AccountId> {
// fn contract_address_for(code_hash: &CodeHash, data: &[u8], origin: &AccountId) -> AccountId;
fn account_id_for(decoded_sub_key: &[u8]) -> result::Result<AccountId, &'static str>;
}

Expand All @@ -311,12 +333,12 @@ where
T::AccountId: rstd::convert::From<[u8; 32]> + AsRef<[u8]>,
{
fn account_id_for(decoded_sub_key: &[u8]) -> result::Result<T::AccountId, &'static str> {
if decoded_sub_key.len() != 32 {
return Err("Address Length - MISMATCHED");
}
ensure!(decoded_sub_key.len() == 33, "Address Length - MISMATCHED");

ensure!(decoded_sub_key[0] == 42, "Pubkey Prefix - MISMATCHED");

let mut r = [0u8; 32];
r.copy_from_slice(&decoded_sub_key[..]);
r.copy_from_slice(&decoded_sub_key[1..]);

let darwinia_account = r.into();

Expand All @@ -325,3 +347,9 @@ where
Ok(darwinia_account)
}
}

impl<T: Trait> Module<T> {
pub fn adjust_deposit_value() {
unimplemented!()
}
}
Loading