Skip to content

Commit

Permalink
update according to review
Browse files Browse the repository at this point in the history
  • Loading branch information
tolak committed Sep 25, 2023
1 parent 25d603a commit d577dc9
Show file tree
Hide file tree
Showing 19 changed files with 204 additions and 1,528 deletions.
2 changes: 1 addition & 1 deletion contracts/index_executor/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ serde = { version = "=1.0.185", default-features = false, features = ["derive",
dyn-clone = "1.0.10"
hex-literal = "0.4.1"
hex = { version = "0.4.3", default-features = false, features = ["alloc"] }
fixed = { version = "1.23.1", default-features = false, features = ["serde"] }
fixed = { version = "=1.23.1", default-features = false, features = ["serde"] }
half = { version = "=2.2.1", default-features = false }
ink = { version = "4.2.1", default-features = false }
ink_env = { version = "4.2.1", default-features = false }
Expand Down
22 changes: 13 additions & 9 deletions contracts/index_executor/src/actions/acala/asset.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use crate::traits::AssetRegistry;
use crate::utils::slice_to_generalkey;
use alloc::{vec, vec::Vec};
use alloc::{collections::BTreeMap, vec::Vec};

use scale::Decode;
use scale::Encode;
Expand Down Expand Up @@ -116,27 +116,31 @@ pub type TokenAttrs = (
pub struct AcalaAssets;

impl AcalaAssets {
fn get_map() -> Vec<TokenAttrs> {
fn get_map() -> BTreeMap<MultiLocation, TokenAttrs> {
let lc_kar: MultiLocation =
MultiLocation::new(1, X2(Parachain(2000), slice_to_generalkey(&[0x00, 0x80])));
let lc_pha: MultiLocation = MultiLocation::new(1, X1(Parachain(2004)));
let lc_aca: MultiLocation =
MultiLocation::new(1, X2(Parachain(2000), slice_to_generalkey(&[0x00, 0x00])));
let lc_dot: MultiLocation =
MultiLocation::new(1, X2(Parachain(2000), slice_to_generalkey(&[0x00, 0x02])));
vec![
(lc_aca, TokenSymbol::ACA, TokenType::Utility, None),
(lc_dot, TokenSymbol::DOT, TokenType::Native, None),
(lc_kar, TokenSymbol::KAR, TokenType::Native, None),
(lc_pha, TokenSymbol::PHA, TokenType::Foreign, Some(FA_PHA)),
]
BTreeMap::from([
(lc_aca, (lc_aca, TokenSymbol::ACA, TokenType::Utility, None)),
(lc_dot, (lc_dot, TokenSymbol::DOT, TokenType::Native, None)),
(lc_kar, (lc_kar, TokenSymbol::KAR, TokenType::Native, None)),
(
lc_pha,
(lc_pha, TokenSymbol::PHA, TokenType::Foreign, Some(FA_PHA)),
),
])
}

pub fn get_asset_attrs(
location: &MultiLocation,
) -> Option<(TokenSymbol, TokenType, Option<ForeignAssetId>)> {
let tokens = AcalaAssets::get_map();
let token = tokens.iter().find(|s| s.0 == *location);
let token = tokens.get(location);
// let token = tokens.iter().find(|s| s.0 == *location);
if let Some(token) = token {
return Some((token.1, token.2, token.3));
}
Expand Down
6 changes: 2 additions & 4 deletions contracts/index_executor/src/actions/astar/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,11 @@ pub type AstarArthSwap = uniswapv2::UniswapV2;

use crate::call::CallBuilder;
use crate::chain::Chain;
use crate::utils::ToArray;
use alloc::{boxed::Box, string::String, vec, vec::Vec};

pub fn evm_create_actions(chain: &Chain) -> Vec<(String, Box<dyn CallBuilder>)> {
let arthswap_pancake_router: [u8; 20] = hex::decode("E915D2393a08a00c5A463053edD31bAe2199b9e7")
.unwrap()
.to_array();
let arthswap_pancake_router: [u8; 20] =
hex_literal::hex!("E915D2393a08a00c5A463053edD31bAe2199b9e7");
vec![(
String::from("astar_evm_arthswap"),
Box::new(AstarArthSwap::new(
Expand Down
5 changes: 1 addition & 4 deletions contracts/index_executor/src/actions/ethereum/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,9 @@ pub type EthereumUniswapV2 = uniswapv2::UniswapV2;

use crate::call::CallBuilder;
use crate::chain::Chain;
use crate::utils::ToArray;

pub fn create_actions(chain: &Chain) -> Vec<(String, Box<dyn CallBuilder>)> {
let uniswapv2_router: [u8; 20] = hex::decode("7a250d5630B4cF539739dF2C5dAcb4c659F2488D")
.unwrap()
.to_array();
let uniswapv2_router: [u8; 20] = hex_literal::hex!("7a250d5630B4cF539739dF2C5dAcb4c659F2488D");

vec![(
String::from("ethereum_uniswapv2"),
Expand Down
5 changes: 1 addition & 4 deletions contracts/index_executor/src/actions/moonbeam/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,10 @@ pub type MoonbeamStellaSwap = uniswapv2::UniswapV2;
use crate::call::CallBuilder;
use crate::chain::Chain;
use crate::constants::*;
use crate::utils::ToArray;
use alloc::{boxed::Box, string::String, vec, vec::Vec};

pub fn create_actions(chain: &Chain) -> Vec<(String, Box<dyn CallBuilder>)> {
let stellaswap_router: [u8; 20] = hex::decode("70085a09D30D6f8C4ecF6eE10120d1847383BB57")
.unwrap()
.to_array();
let stellaswap_router: [u8; 20] = hex_literal::hex!("70085a09D30D6f8C4ecF6eE10120d1847383BB57");
let moonbeam_xtoken: [u8; 20] = hex_literal::hex!("0000000000000000000000000000000000000804");

vec![
Expand Down
28 changes: 13 additions & 15 deletions contracts/index_executor/src/call.rs
Original file line number Diff line number Diff line change
Expand Up @@ -64,26 +64,24 @@ impl Tokenizable for Call {
}

fn into_token(self) -> Token {
let mut tokens: Vec<Token> = vec![];
match (self.params, self.input_call, self.call_index) {
(CallParams::Evm(evm_call), Some(input_call), Some(call_index)) => {
tokens.push(evm_call.target.into_token());
tokens.push(Bytes(evm_call.calldata).into_token());
tokens.push(evm_call.value.into_token());
tokens.push(evm_call.need_settle.into_token());
tokens.push(evm_call.update_offset.into_token());
tokens.push(evm_call.update_len.into_token());
tokens.push(evm_call.spend_asset.into_token());
tokens.push(evm_call.spend_amount.into_token());
tokens.push(evm_call.receive_asset.into_token());
tokens.push(U256::from(input_call).into_token());
tokens.push(U256::from(call_index).into_token());
}
(CallParams::Evm(evm_call), Some(input_call), Some(call_index)) => Token::Tuple(vec![
evm_call.target.into_token(),
Bytes(evm_call.calldata).into_token(),
evm_call.value.into_token(),
evm_call.need_settle.into_token(),
evm_call.update_offset.into_token(),
evm_call.update_len.into_token(),
evm_call.spend_asset.into_token(),
evm_call.spend_amount.into_token(),
evm_call.receive_asset.into_token(),
U256::from(input_call).into_token(),
U256::from(call_index).into_token(),
]),
_ => {
return Token::Tuple(vec![]);
}
}
Token::Tuple(tokens)
}
}

Expand Down
32 changes: 16 additions & 16 deletions contracts/index_executor/src/chain.rs
Original file line number Diff line number Diff line change
Expand Up @@ -120,8 +120,8 @@ impl BalanceFetcher for Chain {
if self.is_native(&asset) {
let web3 = Web3::new(transport);
let balance = resolve_ready(web3.eth().balance(evm_account, None))
.log_err("Fetch data [evm native balance] failed")
.map_err(|_| "FetchDataFailed")?;
.log_err("chain::get_balance: fetch data [evm native balance] failed")
.or(Err("FetchDataFailed"))?;
balance.try_into().map_err(|_| "BalanceOverflow")
} else {
let eth = Eth::new(transport);
Expand All @@ -138,8 +138,8 @@ impl BalanceFetcher for Chain {
Options::default(),
None,
))
.log_err("Fetch data [evm erc20 balance] failed")
.map_err(|_| "FetchDataFailed")?;
.log_err("chain::get_balance: fetch data [evm erc20 balance] failed")
.or(Err("FetchDataFailed"))?;
balance.try_into().map_err(|_| "BalanceOverflow")
}
}
Expand All @@ -154,13 +154,13 @@ impl BalanceFetcher for Chain {
),
None,
)
.log_err("Read storage [sub native balance] failed")
.map_err(|_| "FetchDataFailed")?
.log_err("chain::get_balance, read storage [sub native balance] failed")
.or(Err("FetchDataFailed"))?
{
let account_info: AccountInfo<Index, AccountData<Balance>> =
scale::Decode::decode(&mut raw_storage.as_slice())
.log_err("Decode storage [sub native balance] failed")
.map_err(|_| "DecodeStorageFailed")?;
.log_err("chain::get_balance, decode storage [sub native balance] failed")
.or(Err("DecodeStorageFailed"))?;
Ok(account_info.data.free)
} else {
Ok(0u128)
Expand All @@ -186,14 +186,14 @@ impl BalanceFetcher for Chain {
None,
)
.log_err(
"Read storage [sub foreign asset balance] from pallet-asset failed",
"chain::get_balance: read storage [sub foreign asset balance] from pallet-asset failed",
)
.map_err(|_| "FetchDataFailed")?
.or(Err("FetchDataFailed"))?
{
let account_info: AssetAccount<Balance, Balance, ()> =
scale::Decode::decode(&mut raw_storage.as_slice())
.log_err("Decode storage [sub foreign asset balance] from pallet-asset failed")
.map_err(|_| "DecodeStorageFailed")?;
.log_err("chain::get_balance: decode storage [sub foreign asset balance] from pallet-asset failed")
.or(Err("DecodeStorageFailed"))?;
Ok(account_info.balance)
} else {
Ok(0u128)
Expand All @@ -214,14 +214,14 @@ impl BalanceFetcher for Chain {
None,
)
.log_err(
"Read storage [sub foreign asset balance] from orml-token failed",
"chain::get_balance: read storage [sub foreign asset balance] from orml-token failed",
)
.map_err(|_| "FetchDataFailed")?
.or(Err("FetchDataFailed"))?
{
let account_info: OrmlTokenAccountData<Balance> =
scale::Decode::decode(&mut raw_storage.as_slice())
.log_err("Decode storage [sub foreign asset balance] from orml-token failed")
.map_err(|_| "DecodeStorageFailed")?;
.log_err("chain::get_balance: decode storage [sub foreign asset balance] from orml-token failed")
.or(Err("DecodeStorageFailed"))?;
Ok(account_info.free)
} else {
Ok(0u128)
Expand Down
2 changes: 2 additions & 0 deletions contracts/index_executor/src/constants.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,3 +14,5 @@ pub const PHALA_PARACHAIN_ID: u32 = 2035;
pub const KHALA_PARACHAIN_ID: u32 = 2004;
#[allow(dead_code)]
pub const MOONRIVER_PARACHAIN_ID: u32 = 2023;

pub const HANDLER_ABI: &[u8] = include_bytes!("./abi/handler.json");
4 changes: 2 additions & 2 deletions contracts/index_executor/src/gov.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ impl WorkerGov {
) -> Result<Vec<u8>, &'static str> {
let transport = Eth::new(PinkHttp::new(endpoint));
let handler_contract =
Contract::from_json(transport, handler, include_bytes!("./abi/handler.json"))
Contract::from_json(transport, handler, crate::constants::HANDLER_ABI)
.or(Err("ConstructContractFailed"))?;
let worker = KeyPair::from(worker_key);

Expand All @@ -33,7 +33,7 @@ impl WorkerGov {
))
.or(Err("GasEstimateFailed"))?;

// Submit the `approve` transaction
// Submit the `drop` transaction
let tx_id = resolve_ready(handler_contract.signed_call(
"drop",
id,
Expand Down
2 changes: 1 addition & 1 deletion contracts/index_executor/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -128,7 +128,7 @@ mod index_executor {
Ok(())
}

/// Debug only, remove before release
/// TODO: Debug only, remove before release
#[ink(message)]
pub fn export_worker_keys(&self) -> Result<Vec<[u8; 32]>> {
self.ensure_owner()?;
Expand Down
24 changes: 12 additions & 12 deletions contracts/index_executor/src/registry.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,35 +34,35 @@ impl Registry {
endpoint: "https://mainnet.infura.io/v3/6d61e7957c1c489ea8141e947447405b"
.to_string(),
chain_type: ChainType::Evm,
native_asset: hex::decode("0000000000000000000000000000000000000000")
.expect("InvalidLocation"),
native_asset: hex_literal::hex!("0000000000000000000000000000000000000000")
.to_vec(),
foreign_asset: None,
handler_contract: hex::decode("F9eaE3Ec6BFE94F510eb3a5de8Ac9dEB9E74DF39")
.expect("InvalidLocation"),
handler_contract: hex_literal::hex!("F9eaE3Ec6BFE94F510eb3a5de8Ac9dEB9E74DF39")
.to_vec(),
tx_indexer_url: "null".to_string(),
},
Chain {
id: 1,
name: "Moonbeam".to_string(),
endpoint: "https://moonbeam.api.onfinality.io/public".to_string(),
chain_type: ChainType::Evm,
native_asset: hex::decode("0000000000000000000000000000000000000000")
.expect("InvalidLocation"),
native_asset: hex_literal::hex!("0000000000000000000000000000000000000000")
.to_vec(),
foreign_asset: None,
handler_contract: hex::decode("635eA86804200F80C16ea8EdDc3c749a54a9C37D")
.expect("InvalidLocation"),
handler_contract: hex_literal::hex!("635eA86804200F80C16ea8EdDc3c749a54a9C37D")
.to_vec(),
tx_indexer_url: "https://squid.subsquid.io/graph-moonbeam/graphql".to_string(),
},
Chain {
id: 2,
name: "AstarEvm".to_string(),
endpoint: "https://astar.public.blastapi.io".to_string(),
chain_type: ChainType::Evm,
native_asset: hex::decode("0000000000000000000000000000000000000000")
.expect("InvalidLocation"),
native_asset: hex_literal::hex!("0000000000000000000000000000000000000000")
.to_vec(),
foreign_asset: None,
handler_contract: hex::decode("B376b0Ee6d8202721838e76376e81eEc0e2FE864")
.expect("InvalidLocation"),
handler_contract: hex_literal::hex!("B376b0Ee6d8202721838e76376e81eEc0e2FE864")
.to_vec(),
tx_indexer_url: "https://squid.subsquid.io/graph-astar/graphql".to_string(),
},
Chain {
Expand Down
56 changes: 26 additions & 30 deletions contracts/index_executor/src/step.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use crate::chain::{BalanceFetcher, Chain, ChainType};
use crate::utils::ToArray;
use alloc::vec;
use alloc::{borrow::ToOwned, boxed::Box, string::String, vec::Vec};
use alloc::{borrow::ToOwned, boxed::Box, format, string::String, vec, vec::Vec};
use pink_extension::ResultExt;
use pink_subrpc::{create_transaction_with_calldata, send_transaction, ExtraParam};

use crate::account::AccountInfo;
Expand Down Expand Up @@ -123,7 +123,7 @@ impl Step {
return Err("InvalidAddressInStep");
}

hex::decode(&address[2..]).map_err(|_| "DecodeAddressFailed")
hex::decode(&address[2..]).or(Err("DecodeAddressFailed"))
}
}

Expand Down Expand Up @@ -315,7 +315,7 @@ impl Runner for MultiStep {
let handler = Contract::from_json(
Eth::new(PinkHttp::new(chain.endpoint)),
chain.handler_contract.to_array().into(),
include_bytes!("./abi/handler.json"),
crate::constants::HANDLER_ABI,
)
.expect("Bad abi data");

Expand All @@ -326,10 +326,11 @@ impl Runner for MultiStep {
worker_account.account20.into(),
Options::default(),
))
.map_err(|e| {
pink_extension::error!("Failed to estimated step gas cost with error: {:?}", e);
"FailedToEstimateGas"
})?;
.log_err(&format!(
"Step.run: failed to estimated step gas cost with calls: {:?}",
&calls
))
.or(Err("FailedToEstimateGas"))?;
pink_extension::debug!("Estimated step gas error: {:?}", gas);

// Actually submit the tx (no guarantee for success)
Expand All @@ -342,13 +343,11 @@ impl Runner for MultiStep {
}),
KeyPair::from(signer),
))
.map_err(|e| {
pink_extension::error!(
"Failed to submit step execution tx with error: {:?}",
e
);
"FailedToSubmitTransaction"
})?;
.log_err(&format!(
"Step.run: failed to submit tx with nonce: {:?}",
&nonce
))
.or(Err("FailedToSubmitTransaction"))?;

tx_id.as_bytes().to_owned()
}
Expand All @@ -365,21 +364,18 @@ impl Runner for MultiStep {
era: None,
},
)
.map_err(|e| {
pink_extension::error!(
"Failed to construct substrate tx with error: {:?}",
e
);
"FailedToCreateTransaction"
})?;

send_transaction(&chain.endpoint, &signed_tx).map_err(|e| {
pink_extension::error!(
"Failed to submit step execution tx with error: {:?}",
e
);
"FailedToSubmitTransaction"
})?
.log_err(&format!(
"Step.run: failed to create transaction with nonce: {:?}",
hex::encode(&calldata)
))
.or(Err("FailedToCreateTransaction"))?;

send_transaction(&chain.endpoint, &signed_tx)
.log_err(&format!(
"Step.run: failed to submit step execution tx with signed tx: {:?}",
&signed_tx
))
.or(Err("FailedToSubmitTransaction"))?
}
_ => return Err("UnexpectedCallType"),
},
Expand Down
Loading

0 comments on commit d577dc9

Please sign in to comment.