Skip to content

Commit

Permalink
Fix Substrate transactions
Browse files Browse the repository at this point in the history
  • Loading branch information
shekohex committed Oct 4, 2023
1 parent 97c0430 commit b2bcdc5
Show file tree
Hide file tree
Showing 12 changed files with 1,721 additions and 660 deletions.
2,253 changes: 1,678 additions & 575 deletions Cargo.lock

Large diffs are not rendered by default.

6 changes: 3 additions & 3 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -18,15 +18,15 @@ rocket_oauth2 = { git = "https://github.com/webb-tools/rocket_oauth2", branch =
# rocket_oauth2 = { version = "0.5.0-rc.1", features = ["hyper_rustls_adapter"] }
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
sp-core = "21.0.0"
thiserror = "1.0"
twitter-v2 = { version = "0.1.8", default-features = false, features = ["oauth2", "rustls-tls"] }

webb-auth-sled = { path = "./auth-sled" }
webb-auth = { path = "./auth" }

webb = "0.6.1"
webb-proposals = "0.5.4"
webb = "0.8.0"
webb-proposals = { git = "https://github.com/webb-tools/webb-rs", rev="a960eaf", features = ["scale"] }
subxt-signer = { version = "0.31.0", features = ["subxt"] }
rocket_cors = { git = "https://github.com/lawliet89/rocket_cors", branch = "master" }

[features]
Expand Down
2 changes: 1 addition & 1 deletion auth-sled/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -13,4 +13,4 @@ sled = "0.34.7"
webb-auth = { path = "../auth" }
serde_json = { version = "1.0", features = ["preserve_order"] }
thiserror = "1.0"
webb-proposals = "0.5.4"
webb-proposals = { git = "https://github.com/webb-tools/webb-rs", rev="a960eaf", features = ["scale"] }
2 changes: 1 addition & 1 deletion auth/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -10,4 +10,4 @@ async-trait = "0.1"
chrono = { version = "0.4", features = ["serde"] }
serde = "1.0"
thiserror = "1.0"
webb-proposals = "0.5.4"
webb-proposals = { git = "https://github.com/webb-tools/webb-rs", rev="a960eaf", features = ["scale"] }
1 change: 1 addition & 0 deletions faucet-frontend/.env.example
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
REACT_APP_BACKEND_URL='http://localhost:8000'
REACT_APP_TWITTER_CLIENT_ID='<client_id>'
REACT_APP_TWITTER_CLIENT_SECRET='<client_secret>'
5 changes: 4 additions & 1 deletion faucet-frontend/src/pages/Home.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,12 @@ import ClaimFundsForm from "../components/ClaimFundsForm";

const postData = async (code: string) => {
const client_id = process.env.REACT_APP_TWITTER_CLIENT_ID || "";
const client_secret = process.env.REACT_APP_TWITTER_CLIENT_SECRET || "";
const token = btoa(`${client_id}:${client_secret}`);
const publicUrl = process.env.PUBLIC_URL || "http://localhost:3000";
const response = await axios.post(
// This will be proxied to https:
// "https://api.twitter.com/2/oauth2/token"
// "https://api.twitter.com/oauth2/token"
"/2/oauth2/token",
{
code,
Expand All @@ -22,6 +24,7 @@ const postData = async (code: string) => {
baseURL: publicUrl,
headers: {
"Content-Type": "application/x-www-form-urlencoded",
"Authorization": `Basic ${token}`,
},
}
);
Expand Down
3 changes: 2 additions & 1 deletion faucet-frontend/src/setupProxy.js
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
const { createProxyMiddleware } = require("http-proxy-middleware");

module.exports = function (app) {
module.exports = function(app) {
app.use(
"/2/oauth2/token",
createProxyMiddleware({
target: "https://api.twitter.com",
changeOrigin: true,
secure: false,
preserveHeaderKeyCase: true
})
);
};
1 change: 1 addition & 0 deletions flake.nix
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
# Mold Linker for faster builds (only on Linux)
(lib.optionals pkgs.stdenv.isLinux pkgs.mold)
(lib.optionals pkgs.stdenv.isDarwin pkgs.darwin.apple_sdk.frameworks.Security)
(lib.optionals pkgs.stdenv.isDarwin pkgs.darwin.apple_sdk.frameworks.SystemConfiguration)
];
buildInputs = [
pkgs.openssl
Expand Down
4 changes: 2 additions & 2 deletions src/faucet.rs
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ pub async fn handle_token_transfer(
SubstrateProviders<OnlineClient<PolkadotConfig>>,
>,
_evm_wallet: &State<Wallet<SigningKey>>,
signer_pair: &State<sp_core::sr25519::Pair>,
signer_pair: &State<subxt_signer::sr25519::Keypair>,
tx_sender: &State<UnboundedSender<Transaction>>,
) -> Result<TxResult, Error> {
let (result_sender, result_receiver) = oneshot::channel();
Expand Down Expand Up @@ -154,7 +154,7 @@ pub async fn faucet(
SubstrateProviders<OnlineClient<PolkadotConfig>>,
>,
evm_wallet: &State<Wallet<SigningKey>>,
signer_pair: &State<sp_core::sr25519::Pair>,
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;
Expand Down
6 changes: 3 additions & 3 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@ use rocket::{launch, log, routes};
use rocket_cors::{AllowedOrigins, CorsOptions};
use rocket_oauth2::OAuth2;
use serde::Deserialize;
use sp_core::Pair;
use txes::{
networks::Network,
processor::TransactionProcessingSystem,
Expand Down Expand Up @@ -130,12 +129,13 @@ fn ethers_wallet_firing() -> impl Fairing {
}

fn substrate_wallet_firing() -> impl Fairing {
use subxt_signer::{bip39::Mnemonic, sr25519::Keypair};
AdHoc::try_on_ignite("Open substrate wallet", |rocket| async {
let maybe_wallet = match rocket.state::<AppConfig>() {
Some(config) => {
let mnemonic: String =
let mnemonic: Mnemonic =
config.mnemonic.parse().expect("Mnemonic is not valid");
sp_core::sr25519::Pair::from_string(&mnemonic, None)
Keypair::from_phrase(&mnemonic, None)
}
None => return Err(rocket),
};
Expand Down
91 changes: 20 additions & 71 deletions src/txes/processor.rs
Original file line number Diff line number Diff line change
@@ -1,16 +1,17 @@
use std::ops::Div;
use std::sync::Arc;

use crate::subxt::utils::H256;
use ethers::prelude::ContractCall;
use ethers::providers::Middleware;
use ethers::types::{Address, TransactionReceipt, TransactionRequest};
use rocket::tokio::{self, sync::oneshot};
use sp_core::H256;
use tokio::sync::mpsc::UnboundedReceiver;
use webb::evm::contract::protocol_solidity::erc20_preset_minter_pauser::ERC20PresetMinterPauserContract;
use webb::evm::ethers;
use webb::evm::ethers::types::U256;
use webb::substrate::subxt::utils::{AccountId32, MultiAddress};
use webb::substrate::subxt::{tx::PairSigner, OnlineClient, PolkadotConfig};
use webb::substrate::subxt::{OnlineClient, PolkadotConfig};
use webb::substrate::tangle_runtime::api as RuntimeApi;

use crate::error::Error;
Expand Down Expand Up @@ -202,24 +203,17 @@ async fn handle_evm_token_tx<M: Middleware>(
async fn handle_substrate_tx(
api: OnlineClient<PolkadotConfig>,
to: AccountId32,
amount: u128,
_amount: u128,
native_token_amount: u128,
asset_id: Option<u32>,
signer: sp_core::sr25519::Pair,
signer: subxt_signer::sr25519::Keypair,
result_sender: oneshot::Sender<Result<TxResult, Error>>,
) -> Result<H256, Error> {
match asset_id {
Some(asset_id) => {
handle_substrate_token_tx(
api,
to,
amount,
asset_id,
signer,
result_sender,
)
.await
}
Some(asset_id) => Err(Error::Custom(format!(
"Substrate only supports sending native tokens. Asset ID {} not supported",
asset_id
))),
None => {
handle_substrate_native_tx(
api,
Expand All @@ -237,20 +231,16 @@ async fn handle_substrate_native_tx(
api: OnlineClient<PolkadotConfig>,
to: AccountId32,
amount: u128,
signer: sp_core::sr25519::Pair,
signer: subxt_signer::sr25519::Keypair,
result_sender: oneshot::Sender<Result<TxResult, Error>>,
) -> Result<H256, Error> {
let to_address = MultiAddress::Id(to.clone());
let balance_transfer_tx =
RuntimeApi::tx().balances().transfer(to_address, amount);

// Sign and submit the extrinsic.
let tx_result = api
.tx()
.sign_and_submit_then_watch_default(
&balance_transfer_tx,
&PairSigner::new(signer),
)
.sign_and_submit_then_watch_default(&balance_transfer_tx, &signer)
.await
.map_err(|e| Error::Custom(e.to_string()))?;

Expand All @@ -260,69 +250,28 @@ async fn handle_substrate_native_tx(
.wait_for_finalized_success()
.await
.map_err(|e| Error::Custom(e.to_string()))?;
let block_hash = events.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 {
println!("Balance transfer success: {event:?}");
let from = event.from;
let to = event.to;
let amount = event.amount.div(10u128.pow(18));
println!("Transfered {amount} tokens {from} -> {to}");
}

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

Ok(tx_hash)
}

async fn handle_substrate_token_tx(
api: OnlineClient<PolkadotConfig>,
to: AccountId32,
amount: u128,
asset_id: u32,
signer: sp_core::sr25519::Pair,
result_sender: oneshot::Sender<Result<TxResult, Error>>,
) -> Result<H256, Error> {
let to_address = MultiAddress::Id(to.clone());
let token_transfer_tx = RuntimeApi::tx()
.tokens()
.transfer(to_address, asset_id, amount);

// Sign and submit the extrinsic.
let tx_result = api
.tx()
.sign_and_submit_then_watch_default(
&token_transfer_tx,
&PairSigner::new(signer),
)
.await
.map_err(|e| Error::Custom(e.to_string()))?;

let tx_hash = tx_result.extrinsic_hash();

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

// Find a Transfer event and print it.
let transfer_event = events
.find_first::<RuntimeApi::tokens::events::Transfer>()
.map_err(|e| Error::Custom(e.to_string()))?;
if let Some(event) = transfer_event {
println!("Balance transfer success: {event:?}");
}

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

Ok(tx_hash)
}
7 changes: 5 additions & 2 deletions src/txes/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,10 @@ pub struct SubstrateProviders<T> {
#[derive(Debug, Serialize, Deserialize)]
pub enum TxResult {
Evm(TransactionReceipt),
Substrate(webb::substrate::subxt::utils::H256),
Substrate {
block_hash: webb::substrate::subxt::utils::H256,
tx_hash: webb::substrate::subxt::utils::H256,
},
}

#[allow(clippy::large_enum_variant)]
Expand All @@ -58,7 +61,7 @@ pub enum Transaction {
amount: u128,
native_token_amount: u128,
asset_id: Option<u32>,
signer: sp_core::sr25519::Pair,
signer: subxt_signer::sr25519::Keypair,
result_sender: oneshot::Sender<Result<TxResult, Error>>,
},
}
Expand Down

0 comments on commit b2bcdc5

Please sign in to comment.