Skip to content

Commit

Permalink
Fix Substrate transaction queue (#31)
Browse files Browse the repository at this point in the history
* flake.lock: Update

Flake lock file updates:

• Updated input 'flake-utils':
    'github:numtide/flake-utils/a1720a10a6cfe8234c0e93907ffe81be440f4cef' (2023-05-31)
  → 'github:numtide/flake-utils/ff7b65b44d01cf9ba6a71320833626af21126384' (2023-09-12)
• Updated input 'nixpkgs':
    'github:NixOS/nixpkgs/95be94370d09f97f6af6a1df1eb9649b5260724e' (2023-06-02)
  → 'github:NixOS/nixpkgs/45827faa2132b8eade424f6bdd48d8828754341a' (2023-11-26)
• Updated input 'rust-overlay':
    'github:oxalica/rust-overlay/19fdc1c7ae8aa90ba50f044496fda6c4b6616f91' (2023-06-02)
  → 'github:oxalica/rust-overlay/055d3d2ea161dfc6ca569f2f135a107f48cf483e' (2023-11-27)

* fix: wait till tx in block
  • Loading branch information
shekohex authored Nov 27, 2023
1 parent 3f3a785 commit b64b76b
Show file tree
Hide file tree
Showing 6 changed files with 96 additions and 53 deletions.
3 changes: 3 additions & 0 deletions chainIdRpcs.json
Original file line number Diff line number Diff line change
Expand Up @@ -61,5 +61,8 @@
],
"1081": [
"ws://3.144.199.9:9944"
],
"1082": [
"ws://127.0.0.1:9944"
]
}
18 changes: 9 additions & 9 deletions flake.lock

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

81 changes: 55 additions & 26 deletions src/faucet.rs
Original file line number Diff line number Diff line change
Expand Up @@ -142,34 +142,33 @@ pub async fn handle_token_transfer(
Ok(result)
}

#[post("/faucet", data = "<payload>")]
#[allow(clippy::too_many_arguments)]
pub async fn faucet(
pub async fn check_twitter(
app_config: &State<crate::AppConfig>,
twitter_bearer_token: auth::TwitterBearerToken<'_>,
payload: Json<Payload>,
auth_db: &State<SledAuthDb>,
evm_providers: &State<EvmProviders<EthersClient>>,
substrate_providers: &State<
SubstrateProviders<OnlineClient<PolkadotConfig>>,
>,
evm_wallet: &State<Wallet<SigningKey>>,
signer_pair: &State<subxt_signer::sr25519::Keypair>,
tx_sender: &State<UnboundedSender<Transaction>>,
) -> Result<status::Custom<String>, Error> {
let faucet_data = payload.clone().into_inner().faucet;
) -> Result<twitter_v2::User, Error> {
// during debug builds, we return a dummy user
if cfg!(debug_assertions) {
let token = twitter_bearer_token.token();
return Ok(twitter_v2::User {
id: NumericId::new(token.parse().unwrap()),
username: "dummy".to_string(),
name: "dummy".to_string(),
created_at: None,
description: None,
entities: None,
location: None,
pinned_tweet_id: None,
profile_image_url: None,
protected: None,
public_metrics: None,
url: None,
verified: None,
withheld: None,
});
}
let auth = BearerToken::new(twitter_bearer_token.token());
let twitter_api = TwitterApi::new(auth);
// Extract faucet request fields
let FaucetRequest {
wallet_address,
typed_chain_id,
..
} = faucet_data.clone();
println!(
"Requesting faucet for (address {}, chain: {:?}",
wallet_address, typed_chain_id
);

let twitter_user: twitter_v2::User = twitter_api
.get_users_me()
.send()
Expand Down Expand Up @@ -269,11 +268,41 @@ pub async fn faucet(
);

if !is_following_webb {
return Err(Error::Custom(
Err(Error::Custom(
"User is not following the webb twitter account".to_string(),
));
))
} else {
Ok(twitter_user)
}
}

#[post("/faucet", data = "<payload>")]
#[allow(clippy::too_many_arguments)]
pub async fn faucet(
app_config: &State<crate::AppConfig>,
twitter_bearer_token: auth::TwitterBearerToken<'_>,
payload: Json<Payload>,
auth_db: &State<SledAuthDb>,
evm_providers: &State<EvmProviders<EthersClient>>,
substrate_providers: &State<
SubstrateProviders<OnlineClient<PolkadotConfig>>,
>,
evm_wallet: &State<Wallet<SigningKey>>,
signer_pair: &State<subxt_signer::sr25519::Keypair>,
tx_sender: &State<UnboundedSender<Transaction>>,
) -> Result<status::Custom<String>, Error> {
let twitter_user = check_twitter(app_config, twitter_bearer_token).await?;
let faucet_data = payload.clone().into_inner().faucet;
// Extract faucet request fields
let FaucetRequest {
wallet_address,
typed_chain_id,
..
} = faucet_data.clone();
println!(
"Requesting faucet for (address {}, chain: {:?}",
wallet_address, typed_chain_id
);
// Check if the user's last claim date is within the last 24 hours
let claim_data = auth_db
.get_last_claim_data(twitter_user.id.into(), typed_chain_id)
Expand Down
6 changes: 5 additions & 1 deletion src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -219,7 +219,11 @@ fn substrate_providers_firing() -> impl Fairing {
let result: Result<HashMap<u64, OnlineClient<PolkadotConfig>>, Error> =
match rocket.state::<AppConfig>() {
Some(_config) => {
let networks = vec![Network::Tangle];
let networks = vec![
Network::Tangle,
#[cfg(debug_assertions)]
Network::TangleLocal,
];

let mut futures_unordered = FuturesUnordered::new();

Expand Down
5 changes: 5 additions & 0 deletions src/txes/networks.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ pub enum Network {

// Substrate
Tangle,
TangleLocal,
}

impl Network {
Expand All @@ -34,6 +35,7 @@ impl Network {
"demeter" => Some(Self::Demeter),
"tangle-evm-testnet" => Some(Self::TangleEVMTestnet),
"tangle" => Some(Self::Tangle),
"tangle-local" => Some(Self::TangleLocal),
_ => None,
}
}
Expand Down Expand Up @@ -77,13 +79,15 @@ impl Network {
pub fn from_substrate_chain_id(chain_id: u64) -> Option<Self> {
match chain_id {
1081 => Some(Self::Tangle),
1082 => Some(Self::TangleLocal),
_ => None,
}
}

pub fn to_substrate_chain_id(&self) -> Option<u64> {
match self {
Self::Tangle => Some(1081),
Self::TangleLocal => Some(1082),
_ => None,
}
}
Expand All @@ -103,6 +107,7 @@ impl Network {
pub fn to_typed_chain_id(&self) -> Option<TypedChainId> {
match self {
Self::Tangle => Some(TypedChainId::Substrate(1081)),
Self::TangleLocal => Some(TypedChainId::Substrate(1082)),
Self::ArbitrumGoerli => Some(TypedChainId::Evm(421613)),
Self::Athena => Some(TypedChainId::Evm(3884533461)),
Self::Demeter => Some(TypedChainId::Evm(3884533463)),
Expand Down
36 changes: 19 additions & 17 deletions src/txes/processor.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@

use std::sync::Arc;

use crate::subxt::utils::H256;
Expand Down Expand Up @@ -248,28 +247,31 @@ async fn handle_substrate_native_tx(

println!("Tranasction sent with TxHash: {:?}", tx_hash);

// let events = tx_result
// .wait_for_finalized_success()
// .await
// .map_err(|e| Error::Custom(e.to_string()))?;
// let block_hash = events.block_hash();
let tx_block = tx_result
.wait_for_in_block()
.await
.map_err(|e| Error::Custom(e.to_string()))?;
let block_hash = tx_block.block_hash();

// // Find a Transfer event and print it.
// let transfer_event = events
// .find_first::<RuntimeApi::balances::events::Transfer>()
// .map_err(|e| Error::Custom(e.to_string()))?;
// if let Some(event) = transfer_event {
// let from = event.from;
// let to = event.to;
// let amount = event.amount.div(10u128.pow(18));
// println!("Transfered {amount} tokens {from} -> {to}");
// }
// Find a Transfer event and print it.
let transfer_event = tx_block
.fetch_events()
.await
.map_err(|e| Error::Custom(e.to_string()))?
.find_first::<RuntimeApi::balances::events::Transfer>()
.map_err(|e| Error::Custom(e.to_string()))?;
if let Some(event) = transfer_event {
let from = event.from;
let to = event.to;
let amount = event.amount / (10u128.pow(18));
println!("Transfered {amount} tokens {from} -> {to}");
}

// Return the transaction hash.
result_sender
.send(Ok(TxResult::Substrate {
tx_hash,
block_hash: tx_hash,
block_hash,
}))
.map_err(|e| {
Error::Custom(format!("Failed to send tx_hash: {:?}", e))
Expand Down

0 comments on commit b64b76b

Please sign in to comment.