Skip to content

Commit

Permalink
add system replace staker (#988)
Browse files Browse the repository at this point in the history
* add systemReplaceDelegator

* add checkpoint

* claim remove amount

* fix max_gas_price

* update log
  • Loading branch information
shaorongqiang authored and tiannian committed Jul 29, 2023
1 parent a8ab559 commit 89792dd
Show file tree
Hide file tree
Showing 12 changed files with 231 additions and 114 deletions.
27 changes: 18 additions & 9 deletions src/components/contracts/baseapp/src/app.rs
Original file line number Diff line number Diff line change
Expand Up @@ -305,7 +305,9 @@ impl crate::BaseApp {
let mut coinbase_mint_foud = false;
let mut delegator = H256::zero();

let claim_on_contract_address =
let claim_on_contract_address = if td_height
> CFG.checkpoint.evm_staking_inital_height
{
match H160::from_str(SYSTEM_ADDR).c(d!()).and_then(
|from| {
get_claim_on_contract_address::<BaseApp>(
Expand All @@ -321,8 +323,10 @@ impl crate::BaseApp {
resp.log = e.to_string();
return (resp, vec![]);
}
};

}
} else {
Default::default()
};
for pair in evt.attributes.iter() {
let key = String::from_utf8(pair.key.clone())
.unwrap_or_default();
Expand All @@ -349,12 +353,15 @@ impl crate::BaseApp {
.unwrap_or_default();
if topic == deposit_asset_topic {
deposit_asset_foud = true;
} else if topic.starts_with(
&coinbase_mint_event_topic
[0..coinbase_mint_event_topic.len() - 1],
) {
} else if td_height
> CFG.checkpoint.evm_staking_inital_height
&& topic.starts_with(
&coinbase_mint_event_topic[0
..coinbase_mint_event_topic.len()
- 1],
)
{
if let Some(start) = topic.find(", 0x") {
println!("start:{}", start);
coinbase_mint_foud = true;
delegator = match H256::from_str(
&topic[start + 2..topic.len() - 1],
Expand Down Expand Up @@ -389,7 +396,9 @@ impl crate::BaseApp {
resp.log = e.to_string();
}
}
} else if staking_contract_found
} else if td_height
> CFG.checkpoint.evm_staking_inital_height
&& staking_contract_found
&& coinbase_mint_foud
{
let data =
Expand Down
32 changes: 25 additions & 7 deletions src/components/contracts/baseapp/src/staking.rs
Original file line number Diff line number Diff line change
Expand Up @@ -308,23 +308,41 @@ impl EVMStaking for BaseApp {
Ok(())
}

fn claim(
fn replace_delegator(
&self,
td_addr: &[u8],
delegator_pk: &XfrPublicKey,
amount: u64,
validator: &[u8],
staker: &XfrPublicKey,
new_staker_address: H160,
) -> Result<()> {
let validator = H160::from_slice(validator);
let staker_address = mapping_address(staker);

if let Err(e) = self.modules.evm_module.replace_delegator(
&self.deliver_state,
validator,
staker_address,
new_staker_address,
) {
self.deliver_state.state.write().discard_session();
self.deliver_state.db.write().discard_session();
tracing::error!(target: "evm staking", "replace_delegator error:{:?}", e);
return Err(e);
}

self.deliver_state.state.write().commit_session();
self.deliver_state.db.write().commit_session();
Ok(())
}
fn claim(&self, td_addr: &[u8], delegator_pk: &XfrPublicKey) -> Result<()> {
let validator = H160::from_slice(td_addr);
let delegator = mapping_address(delegator_pk);
let amount = U256::from(amount);
let from = H160::from_str(SYSTEM_ADDR).c(d!())?;
if let Err(e) = self.modules.evm_module.claim(
&self.deliver_state,
from,
validator,
delegator,
delegator_pk,
amount,
) {
self.deliver_state.state.write().discard_session();
self.deliver_state.db.write().discard_session();
Expand All @@ -346,7 +364,7 @@ fn mapping_rate(rate: [u64; 2]) -> U256 {
U256::from(rate[0].saturating_mul(deciamls) / rate[1])
}

fn mapping_address(pk: &XfrPublicKey) -> H160 {
pub fn mapping_address(pk: &XfrPublicKey) -> H160 {
let result = Keccak256::digest(pk.as_bytes());
H160::from_slice(&result.as_slice()[..20])
}
60 changes: 43 additions & 17 deletions src/components/contracts/modules/evm/contracts/EVMStaking.abi.json
Original file line number Diff line number Diff line change
Expand Up @@ -101,11 +101,6 @@
"name": "validator",
"type": "address"
},
{
"internalType": "address",
"name": "delegator",
"type": "address"
},
{
"internalType": "uint256",
"name": "amount",
Expand All @@ -127,7 +122,7 @@
],
"name": "delegate",
"outputs": [],
"stateMutability": "nonpayable",
"stateMutability": "payable",
"type": "function"
},
{
Expand Down Expand Up @@ -432,6 +427,24 @@
"stateMutability": "nonpayable",
"type": "function"
},
{
"inputs": [
{
"internalType": "address[]",
"name": "validators",
"type": "address[]"
},
{
"internalType": "address",
"name": "newDelegator",
"type": "address"
}
],
"name": "replaceDelegator",
"outputs": [],
"stateMutability": "nonpayable",
"type": "function"
},
{
"inputs": [],
"name": "rewardAddr",
Expand Down Expand Up @@ -496,7 +509,7 @@
],
"name": "stake",
"outputs": [],
"stateMutability": "nonpayable",
"stateMutability": "payable",
"type": "function"
},
{
Expand All @@ -523,11 +536,6 @@
"internalType": "address",
"name": "delegator",
"type": "address"
},
{
"internalType": "uint256",
"name": "amount",
"type": "uint256"
}
],
"name": "systemClaim",
Expand Down Expand Up @@ -558,6 +566,29 @@
"stateMutability": "payable",
"type": "function"
},
{
"inputs": [
{
"internalType": "address[]",
"name": "validators",
"type": "address[]"
},
{
"internalType": "address",
"name": "oldDelegator",
"type": "address"
},
{
"internalType": "address",
"name": "newDelegator",
"type": "address"
}
],
"name": "systemReplaceDelegator",
"outputs": [],
"stateMutability": "nonpayable",
"type": "function"
},
{
"inputs": [
{
Expand Down Expand Up @@ -718,11 +749,6 @@
"name": "validator",
"type": "address"
},
{
"internalType": "address",
"name": "staker",
"type": "address"
},
{
"internalType": "string",
"name": "memo",
Expand Down
65 changes: 59 additions & 6 deletions src/components/contracts/modules/evm/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -838,15 +838,10 @@ impl<C: Config> App<C> {
validator: H160,
delegator: H160,
delegator_pk: &XfrPublicKey,
amount: U256,
) -> Result<()> {
let function = self.contracts.staking.function("systemClaim").c(d!())?;
let input = function
.encode_input(&[
Token::Address(validator),
Token::Address(delegator),
Token::Uint(amount),
])
.encode_input(&[Token::Address(validator), Token::Address(delegator)])
.c(d!())?;

let gas_limit = u64::MAX;
Expand Down Expand Up @@ -977,6 +972,64 @@ impl<C: Config> App<C> {
Ok(())
}

pub fn replace_delegator(
&self,
ctx: &Context,
validator: H160,
staker: H160,
new_staker: H160,
) -> Result<()> {
let func = self
.contracts
.staking
.function("systemReplaceDelegator")
.c(d!())?;

let validator = Token::Array(vec![Token::Address(validator)]);
let staker = Token::Address(staker);
let new_staker = Token::Address(new_staker);

let input = func
.encode_input(&[validator, staker, new_staker])
.c(d!())?;

let gas_limit = u64::MAX;
let value = U256::zero();
let from = H160::from_str(SYSTEM_ADDR).c(d!())?;

tracing::info!(
target: "evm staking",
"systemReplaceStaker from:{:?} gas_limit:{} value:{} contracts_address:{:?} input:{}",
from,
gas_limit,
value,
self.contracts.staking_address,
hex::encode(&input)
);

let (_, logs, used_gas) = ActionRunner::<C>::execute_systemc_contract(
ctx,
input.clone(),
from,
gas_limit,
self.contracts.staking_address,
value,
)?;

Self::store_transaction(
ctx,
U256::from(gas_limit),
from,
self.contracts.staking_address,
value,
input,
&logs,
used_gas,
)?;

Ok(())
}

#[allow(clippy::too_many_arguments)]
fn store_transaction(
ctx: &Context,
Expand Down
11 changes: 7 additions & 4 deletions src/components/contracts/modules/evm/src/runtime/runner.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
use super::stack::FindoraStackState;
// use crate::precompile::PrecompileSet;
use crate::{App, Config};
use config::abci::global_cfg::CFG;
use ethereum_types::{H160, H256, U256};
use evm::{
executor::stack::{StackExecutor, StackSubstateMetadata},
Expand Down Expand Up @@ -51,10 +52,12 @@ impl<C: Config> ActionRunner<C> {
gas_price >= C::FeeCalculator::min_gas_price(),
"GasPriceTooLow"
);
ensure!(
gas_price <= C::FeeCalculator::max_gas_price(),
"GasPriceTooHigh"
);
if ctx.header.height > CFG.checkpoint.max_gas_price_limit {
ensure!(
gas_price <= C::FeeCalculator::max_gas_price(),
"GasPriceTooHigh"
);
}
gas_price
}
None => Default::default(),
Expand Down
37 changes: 13 additions & 24 deletions src/components/finutils/src/bins/fn.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,10 @@
#![deny(warnings)]

use std::str::FromStr;

use fp_types::H160;

use {
clap::{crate_authors, load_yaml, App},
finutils::common::{self, evm::*},
Expand Down Expand Up @@ -416,30 +420,15 @@ fn run() -> Result<()> {
let target = m
.value_of("target")
.c(d!())
.and_then(wallet::public_key_from_base64)?;
// let new_td_addr_pk = if let Some(new_td_address_str) = m.value_of("td_address") {
// let new_td_address = hex::decode(new_td_address_str)
// .c(d!("`td_address` is invalid hex. "))?;

// if new_td_address.len() != 20 {
// return Err(eg!("Invalid tendermint address."));
// }

// if let Some(new_td_pk) = m.value_of("td_pubkey") {
// let pk_bytes =
// base64::decode(new_td_pk).c(d!("`td_pubkey` is invalid base64."))?;

// let _ = tendermint::PublicKey::from_raw_ed25519(&pk_bytes)
// .c(d!("Invalid tendermint public key."))?;

// Some((new_td_address, pk_bytes))
// } else {
// return Err(eg!("missing `td_pubkey`"));
// }
// } else {
// None
// };
common::replace_staker(target, None)?;
.and_then(|val| H160::from_str(val).c(d!()))?;
let td_addr = match m.value_of("validator-td-addr") {
Some(v) => v,
None => {
println!("{}", m.usage());
return Ok(());
}
};
common::replace_staker(target, td_addr)?;
} else if let Some(m) = matches.subcommand_matches("dev") {
#[cfg(not(target_arch = "wasm32"))]
{
Expand Down
Loading

0 comments on commit 89792dd

Please sign in to comment.