├── .env.example ├── .github └── workflows │ ├── ci.yaml │ └── release.yaml ├── .gitignore ├── Cargo.toml ├── LICENSE ├── README.md ├── assets └── alchemy.png ├── src ├── connectors │ ├── errors.rs │ ├── mod.rs │ ├── provider.rs │ └── raw.rs ├── lib.rs ├── manager.rs ├── messages │ ├── inbound.rs │ ├── mod.rs │ └── outbound.rs ├── types.rs └── wrapper.rs └── tests ├── manager.rs ├── messages.rs ├── sockets.rs ├── tls.rs ├── types.rs └── util.rs /.env.example: -------------------------------------------------------------------------------- 1 | # A Websocket URI for the Alchemy API 2 | ALCHEMY_RPC_WS_API_KEY= 3 | -------------------------------------------------------------------------------- /.github/workflows/ci.yaml: -------------------------------------------------------------------------------- 1 | name: ci 2 | 3 | on: [push] 4 | 5 | jobs: 6 | cargo-fmt: 7 | runs-on: ubuntu-latest 8 | steps: 9 | - name: Checkout sources 10 | uses: actions/checkout@v2 11 | - name: Install toolchain 12 | uses: actions-rs/toolchain@v1 13 | with: 14 | toolchain: nightly 15 | profile: minimal 16 | components: rustfmt, clippy 17 | override: true 18 | - uses: Swatinem/rust-cache@v1 19 | with: 20 | cache-on-failure: true 21 | - name: cargo fmt 22 | run: cargo +nightly fmt --all -- --check 23 | 24 | cargo-docs: 25 | runs-on: ubuntu-latest 26 | steps: 27 | - name: Checkout sources 28 | uses: actions/checkout@v2 29 | - name: Install toolchain 30 | uses: actions-rs/toolchain@v1 31 | with: 32 | toolchain: nightly 33 | profile: minimal 34 | components: rustfmt, clippy 35 | override: true 36 | - uses: Swatinem/rust-cache@v1 37 | with: 38 | cache-on-failure: true 39 | - name: cargo doc 40 | run: cargo +nightly doc --all-features --no-deps 41 | 42 | cargo-clippy: 43 | runs-on: ubuntu-latest 44 | steps: 45 | - name: Checkout sources 46 | uses: actions/checkout@v2 47 | - name: Install toolchain 48 | uses: actions-rs/toolchain@v1 49 | with: 50 | toolchain: nightly 51 | profile: minimal 52 | components: rustfmt, clippy 53 | override: true 54 | - uses: Swatinem/rust-cache@v1 55 | with: 56 | cache-on-failure: false 57 | - name: cargo clippy 58 | run: cargo +nightly clippy --all --all-features -- -D warnings 59 | 60 | tests: 61 | runs-on: ubuntu-latest 62 | steps: 63 | - name: Checkout sources 64 | uses: actions/checkout@v2 65 | - name: Checkout submodules 66 | run: git submodule update --init 67 | - name: Install toolchain 68 | uses: actions-rs/toolchain@v1 69 | with: 70 | toolchain: stable 71 | profile: minimal 72 | override: true 73 | - uses: Swatinem/rust-cache@v1 74 | with: 75 | cache-on-failure: true 76 | - name: cargo test 77 | run: cargo test --all --all-features --quiet 78 | 79 | dry-release: 80 | runs-on: ubuntu-latest 81 | steps: 82 | - uses: actions/checkout@v2 83 | - uses: actions-rs/toolchain@v1 84 | with: 85 | toolchain: stable 86 | override: true 87 | - uses: katyo/publish-crates@v1 88 | with: 89 | dry-run: true 90 | check-repo: ${{ github.event_name == 'push' }} -------------------------------------------------------------------------------- /.github/workflows/release.yaml: -------------------------------------------------------------------------------- 1 | name: Release version 2 | 3 | on: 4 | push: 5 | branches: 6 | - main 7 | 8 | jobs: 9 | release: 10 | runs-on: ubuntu-latest 11 | steps: 12 | - uses: actions/checkout@v2 13 | - uses: actions-rs/toolchain@v1 14 | with: 15 | toolchain: stable 16 | override: true 17 | - uses: katyo/publish-crates@v1 18 | with: 19 | registry-token: ${{ secrets.CARGO_REGISTRY_TOKEN }} 20 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Generated by Cargo 2 | # will have compiled files and executables 3 | /target/ 4 | 5 | # Remove Cargo.lock from gitignore if creating an executable, leave it for libraries 6 | # More information here https://doc.rust-lang.org/cargo/guide/cargo-toml-vs-cargo-lock.html 7 | Cargo.lock 8 | 9 | # These are backup files generated by rustfmt 10 | **/*.rs.bk 11 | 12 | .env 13 | .env.* 14 | !/.env.example -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "alchemy-rs" 3 | version = "0.2.0" 4 | edition = "2021" 5 | authors = [ "asnared" ] 6 | readme = "README.md" 7 | repository = "https://github.com/abigger87/alchemy-rs/" 8 | license = "MIT" 9 | description = """ 10 | Minimal ethers-rs wrappers for the Alchemy API built in pure Rust. 11 | """ 12 | keywords = ["sdk", "alchemy", "api", "rust", "logging"] 13 | exclude = [ 14 | "assets", 15 | ".env", 16 | ".env.prod" 17 | ] 18 | 19 | [dependencies] 20 | async-trait = { version = "0.1.50", default-features = false } 21 | ethers = { version = "0.17.0", features = [ "ws", "rustls" ] } 22 | serde_json = { version = "1.0.64", default-features = false, features = ["raw_value"] } 23 | serde = "1.0.144" 24 | actix-rt = "2.7.0" 25 | soketto = "0.7.1" 26 | tokio = { version = "1", features = ["full"] } 27 | tokio-util = { version = "0.6", features = ["compat"] } 28 | tokio-stream = { version = "0.1", features = ["net"] } 29 | futures = { default-features = false, features = ["bilock", "std", "unstable"], version = "0.3.1" } 30 | tracing = "0.1.36" 31 | tracing-subscriber = "0.3.15" 32 | uuid = { version = "1.1.2", features = [ "serde" ] } 33 | 34 | async-tls = { version = "0.11.0", default-features = false, features = ["client"] } 35 | async-std = "1.12.0" -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2022 asnared 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | # alchemy-rs • [![ci](https://github.com/abigger87/alchemy-rs/actions/workflows/ci.yaml/badge.svg)](https://github.com/abigger87/alchemy-rs/actions/workflows/ci.yaml) ![license](https://img.shields.io/github/license/abigger87/alchemy-rs?label=license) [![crates.io](https://img.shields.io/crates/v/alchemy-rs.svg)](https://crates.io/crates/alchemy-rs) 4 | 5 | 6 | **Minimal** ethers-rs wrappers for the Alchemy API built in pure Rust. 7 | 8 | 9 | ## Getting Started 10 | 11 | Add the `alchemy-rs` crate to your project: 12 | 13 | ```toml 14 | alchemy_rs = "0.1.0" 15 | ``` 16 | 17 | 18 | ## Usage 19 | 20 | [alchemy-rs](https://github.com/abigger87/alchemy-rs) is a minimal ethers-rs wrapper for the Alchemy API built in pure rust. 21 | 22 | The [AlchemyManager](src/manager.rs) is the main entry point for interacting with the Alchemy API. It is initializable with an Alchemy API key and a [Chain](https://docs.rs/ethers/latest/ethers/types/enum.Chain.html). Alchemy supports the following chains: ... 23 | 24 | 25 | 26 | ## Examples 27 | 28 | Listening to pending transactions using alchemy's `alchemy_pendingTransactions` method is demonstrated below. 29 | 30 | ```rust 31 | use std::str::FromStr; 32 | use std::env; 33 | 34 | use alchemy_rs::prelude::*; 35 | 36 | async { 37 | // Read an alchemy websocket api key from the `ALCHEMY_API_KEY` environment variable 38 | let api_key = env::var("ALCHEMY_API_KEY").expect("ALCHEMY_API_KEY must be set"); 39 | 40 | // Create the AlchemyManager 41 | let mut manager = AlchemyManager::new(&format!("wss://eth-mainnet.g.alchemy.com/v2/{}", api_key), None); 42 | 43 | // Connect to the websocket 44 | let _ = manager.connect().await.unwrap(); 45 | 46 | // Listen to _pending_ transactions to the USDT address on mainnet 47 | // (there should be a lot of these!) 48 | let usdt_address = Address::from_str("dac17f958d2ee523a2206206994597c13d831ec7").unwrap(); 49 | 50 | // Try to subscribe to pending transactions 51 | let sub_id = match manager.subscribe(Some(usdt_address), None).await { 52 | Ok(id) => id, 53 | Err(e) => { 54 | println!("Error subscribing to pending transactions: {:?}", e); 55 | return; 56 | } 57 | }; 58 | 59 | // Now we can grab items from the stream 60 | let item: AlchemySocketMessageResponse; 61 | loop { 62 | match manager.receive(sub_id).await { 63 | Ok(i) => { 64 | item = i; 65 | break; 66 | }, 67 | Err(e) => { 68 | println!("Error receiving item: {:?}", e); 69 | return; 70 | } 71 | } 72 | } 73 | 74 | // Print the next item 75 | println!("Received pending transaction from the stream: {:?}", item); 76 | }; 77 | ``` 78 | 79 | 80 | ## Safety 81 | 82 | > **Warning** 83 | > 84 | > This is **experimental software** and is provided on an "as is" and "as available" basis. 85 | > Expect rapid iteration and **use at your own risk**. 86 | 87 | 88 | ## License 89 | 90 | [MIT](https://github.com/abigger87/alchemy-rs/blob/master/LICENSE), but go crazy :P 91 | 92 | 93 | ## Acknowledgements 94 | 95 | - [ethers-rs](https://github.com/gakonst/ethers-rs) 96 | -------------------------------------------------------------------------------- /assets/alchemy.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/refcell/alchemy-rs/b6bc9fc615fc530f2a93c633f0247675b0b23ccd/assets/alchemy.png -------------------------------------------------------------------------------- /src/connectors/errors.rs: -------------------------------------------------------------------------------- 1 | use ethers::providers::ProviderError; 2 | use soketto::handshake; 3 | 4 | /// An Alchemy Websocket Connection Error 5 | #[derive(Debug)] 6 | pub enum AlchemyConnectionError { 7 | /// A Provider Connection Error 8 | ProviderError(ProviderError), 9 | /// Raw Websocket TcpStream Error 10 | RawStreamError(std::io::Error), 11 | /// A Raw Websocket Connection Error 12 | RawSocketError(soketto::handshake::Error), 13 | /// A Raw Websocket Handshake Error 14 | RawHandshakeError(handshake::Error), 15 | /// Deserialization Error 16 | Deserialization(serde_json::Error), 17 | /// Received an unexpected response type 18 | UnexpectedResponseType, 19 | /// Missing the websocket channel sender 20 | MissingSender, 21 | /// Missing the websocket channel receiver 22 | MissingReceiver, 23 | /// Connection Closed 24 | Closed, 25 | /// No websocket connection established yet 26 | MissingConnection, 27 | /// Sending a message to the websocket channel failed 28 | SendFailed(soketto::connection::Error), 29 | /// Flushing the websocket channel failed 30 | FlushFailed(soketto::connection::Error), 31 | 32 | /// Some soketto websocket error 33 | SomeError(soketto::connection::Error), 34 | /// The method is unimplemented 35 | Unimplemented, 36 | /// The text response could not be parsed as a string 37 | InvalidTextString, 38 | } 39 | -------------------------------------------------------------------------------- /src/connectors/mod.rs: -------------------------------------------------------------------------------- 1 | //! Alchemy Connectors 2 | 3 | /// An ethers provider connector 4 | pub mod provider; 5 | 6 | /// A raw websocket connector 7 | pub mod raw; 8 | 9 | /// Common Errors 10 | pub mod errors; 11 | 12 | /// Re-export a prelude 13 | pub mod prelude { 14 | pub use super::{errors::*, provider::*, raw::*, *}; 15 | } 16 | 17 | /// An alchemy api connection manager 18 | #[derive(Debug)] 19 | pub enum AlchemyConnector { 20 | /// An ethers-rs websocket [Provider](ethers::providers::Provider) for alchemy 21 | Provider(Option), 22 | /// A Raw, Persistent Websocket Connection to the Alchemy API using [soketto](https://docs.rs/soketto/latest/soketto/) 23 | Raw(Option), 24 | } 25 | 26 | /// The type of alchemy api websocket connection 27 | #[derive(Debug, Clone, PartialEq, Eq)] 28 | pub enum AlchemyConnectorType { 29 | /// An ethers-rs websocket [Provider](ethers::providers::Provider) for alchemy 30 | Provider, 31 | /// A Raw, Persistent Websocket Connection to the Alchemy API using [soketto](https://docs.rs/soketto/latest/soketto/) 32 | Raw, 33 | } 34 | 35 | impl Default for AlchemyConnectorType { 36 | fn default() -> Self { 37 | AlchemyConnectorType::Raw 38 | } 39 | } 40 | 41 | impl From for AlchemyConnector { 42 | fn from(t: AlchemyConnectorType) -> Self { 43 | match t { 44 | AlchemyConnectorType::Provider => AlchemyConnector::Provider(None), 45 | AlchemyConnectorType::Raw => AlchemyConnector::Raw(None), 46 | } 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /src/connectors/provider.rs: -------------------------------------------------------------------------------- 1 | use ethers::prelude::*; 2 | 3 | use super::errors::AlchemyConnectionError; 4 | 5 | /// An ethers-rs websocket [Provider](ethers::providers::Provider) for alchemy 6 | #[derive(Debug, Default, Clone)] 7 | pub struct EthersWsProvider { 8 | /// The ethers-rs websocket [Provider](ethers::providers::Provider) 9 | pub provider: Option>, 10 | } 11 | 12 | impl EthersWsProvider { 13 | /// Create a new ethers-rs websocket [Provider](ethers::providers::Provider) for alchemy 14 | pub fn new() -> Self { 15 | Self { provider: None } 16 | } 17 | 18 | /// Connect to the websocket provider 19 | pub async fn connect(&mut self, url: &str) -> Result<(), AlchemyConnectionError> { 20 | match Provider::connect(String::from(url)).await { 21 | Ok(p) => { 22 | self.provider = Some(p); 23 | Ok(()) 24 | } 25 | Err(e) => Err(AlchemyConnectionError::ProviderError(e)), 26 | } 27 | } 28 | } 29 | 30 | impl From> for EthersWsProvider { 31 | fn from(provider: Provider) -> Self { 32 | Self { 33 | provider: Some(provider), 34 | } 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /src/connectors/raw.rs: -------------------------------------------------------------------------------- 1 | use futures::io::{BufReader, BufWriter}; 2 | use soketto::handshake; 3 | use tokio::net::TcpStream; 4 | use tokio_util::compat::{Compat, TokioAsyncReadCompatExt}; 5 | 6 | use super::errors::AlchemyConnectionError; 7 | 8 | /// A Raw, Persistent Websocket Connection to the Alchemy API using [soketto](https://docs.rs/soketto/latest/soketto/) 9 | /// 10 | /// ## Alchemy 11 | /// 12 | /// The Alchemy Websocket API allows you to interactively demo the endpoints. 13 | /// 14 | /// Simply install a websocket shell command and connect to the demo endpoint: 15 | /// 16 | /// ```sh 17 | /// $ wscat -c wss://eth-mainnet.ws.alchemyapi.io/ws/demo 18 | /// 19 | /// // create subscription 20 | /// > {"id": 1, "method": "eth_subscribe", "params": ["newHeads"]} 21 | /// < {"jsonrpc":"2.0","id":1,"result":"0xcd0c3e8af590364c09d0fa6a1210faf5"} 22 | /// 23 | /// // incoming notifications 24 | /// < {"jsonrpc":"2.0","method":"eth_subscription","params":{"subscription":"0xcd0c3e8af590364c09d0fa6a1210faf5","result":{"difficulty":"0xd9263f42a87",<...>, "uncles":[]}}} 25 | /// < {"jsonrpc":"2.0","method":"eth_subscription","params":{"subscription":"0xcd0c3e8af590364c09d0fa6a1210faf5","result":{"difficulty":"0xd90b1a7ad02", <...>, "uncles":["0x80aacd1ea4c9da32efd8c2cc9ab38f8f70578fcd46a1a4ed73f82f3e0957f936"]}}} 26 | /// 27 | /// // cancel subscription 28 | /// > {"id": 1, "method": "eth_unsubscribe", "params": ["0xcd0c3e8af590364c09d0fa6a1210faf5"]} 29 | /// < {"jsonrpc":"2.0","id":1,"result":true} 30 | /// ``` 31 | /// 32 | #[derive(Debug, Default)] 33 | pub struct RawAlchemyConnection { 34 | // / The websocket connection 35 | // pub connection: Option>>>>, 36 | /// The websocket client sender after building 37 | pub sender: Option>>>>, 38 | /// The websocket client receiver after building 39 | pub receiver: Option>>>>, 40 | } 41 | 42 | impl RawAlchemyConnection { 43 | /// Create a new RawAlchemyConnection 44 | pub fn new() -> Self { 45 | Self { 46 | sender: None, 47 | receiver: None, 48 | } 49 | } 50 | 51 | /// Connect to the sokettot websocket 52 | pub async fn connect(&mut self, url: &'_ str) -> Result<(), AlchemyConnectionError> { 53 | // Create the socket connection 54 | let socket = match tokio::net::TcpStream::connect(url).await { 55 | Ok(s) => s, 56 | Err(e) => return Err(AlchemyConnectionError::RawStreamError(e)), 57 | }; 58 | 59 | // Create the client connection 60 | let compatible_socket = BufReader::new(BufWriter::new(socket.compat())); 61 | let mut client = handshake::Client::new(compatible_socket, url, ""); 62 | 63 | // Handshake the connection 64 | match client.handshake().await { 65 | Ok(sr) => { 66 | tracing::info!("Got handshake response: {:?}", sr); 67 | tracing::debug!( 68 | "Expecting server response: {:?}", 69 | handshake::ServerResponse::Accepted { protocol: None } 70 | ); 71 | } 72 | Err(e) => return Err(AlchemyConnectionError::RawHandshakeError(e)), 73 | } 74 | 75 | let (sender, receiver) = client.into_builder().finish(); 76 | self.sender = Some(sender); 77 | self.receiver = Some(receiver); 78 | 79 | Ok(()) 80 | } 81 | } 82 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | #![warn(missing_docs)] 2 | #![warn(unused_extern_crates)] 3 | #![forbid(unsafe_code)] 4 | #![forbid(where_clauses_object_safety)] 5 | #![deny(rustdoc::broken_intra_doc_links)] 6 | #![doc=include_str!("../README.md")] 7 | 8 | /// Refactored Websocket Connectors for the Alchemy Manager 9 | pub mod connectors; 10 | 11 | /// Refactored Alchemy Websocket Messages 12 | pub mod messages; 13 | 14 | /// Alchemy Manager 15 | pub mod manager; 16 | 17 | /// ethers-rs Alchemy wrappers 18 | pub mod wrapper; 19 | 20 | /// Common types 21 | pub mod types; 22 | 23 | /// A prelude of commonly used alchemy-rs items 24 | pub mod prelude { 25 | pub use super::{manager::*, messages::prelude::*, types::*, wrapper::*}; 26 | 27 | // Re-export ethers-rs prelude 28 | pub use ethers::prelude::*; 29 | } 30 | -------------------------------------------------------------------------------- /src/manager.rs: -------------------------------------------------------------------------------- 1 | use ethers::prelude::*; 2 | 3 | use crate::connectors::prelude::*; 4 | use crate::messages::prelude::*; 5 | 6 | /// An alchemy api connection manager 7 | #[derive(Debug)] 8 | pub struct AlchemyManager { 9 | /// The raw alchemy connection url 10 | pub url: String, 11 | /// The connector to the alchemy api 12 | pub connector: AlchemyConnector, 13 | } 14 | 15 | impl AlchemyManager { 16 | /// Create a new AlchemyManager 17 | pub fn new(url: &str, ty: Option) -> Self { 18 | Self { 19 | url: url.to_string(), 20 | connector: ty.unwrap_or_default().into(), 21 | } 22 | } 23 | 24 | /// Connect to the underlying [AlchemyConnector](AlchemyConnector) 25 | /// 26 | /// ## Return 27 | /// 28 | /// Returns a self reference to allow for method chaining. 29 | /// 30 | pub async fn connect(&mut self) -> Result<&Self, AlchemyConnectionError> { 31 | match &mut self.connector { 32 | AlchemyConnector::Provider(None) => { 33 | let provider = Provider::connect(self.url.clone()) 34 | .await 35 | .map_err(AlchemyConnectionError::ProviderError)?; 36 | self.connector = AlchemyConnector::Provider(Some(provider.into())); 37 | } 38 | AlchemyConnector::Raw(None) => { 39 | let mut conn = RawAlchemyConnection::new(); 40 | conn.connect(&self.url).await?; 41 | self.connector = AlchemyConnector::Raw(Some(conn)); 42 | } 43 | AlchemyConnector::Provider(Some(ref mut c)) => match c.connect(&self.url.clone()).await 44 | { 45 | Ok(_) => (), 46 | Err(e) => return Err(e), 47 | }, 48 | AlchemyConnector::Raw(Some(ref mut c)) => match c.connect(&self.url.clone()).await { 49 | Ok(_) => (), 50 | Err(e) => return Err(e), 51 | }, 52 | } 53 | 54 | Ok(self) 55 | } 56 | 57 | /// Subscribes to pending transactions 58 | /// 59 | /// ## Arguments 60 | /// 61 | /// * `to` - The address to filter transactions sent to 62 | /// * `from` - The address to filter transactions sent from 63 | /// 64 | /// ## Returns 65 | /// 66 | /// A subscription [Uuid](uuid::Uuid). 67 | /// 68 | /// ## Example 69 | /// 70 | /// ```rust 71 | /// use std::str::FromStr; 72 | /// 73 | /// use alchemy_rs::prelude::*; 74 | /// 75 | /// async { 76 | /// // We humbly ask that you do not use this alchemy api key 77 | /// let mut manager = AlchemyManager::new( 78 | /// "wss://eth-mainnet.g.alchemy.com/v2/MVNYMOb_58bAMzhXX2pS25NDiZ3Q9HeC", 79 | /// None, 80 | /// ); 81 | /// 82 | /// // Establish the websocket connection 83 | /// // Note: on success, a self reference is returned so we can chain methods 84 | /// let _ = manager.connect().await.unwrap(); 85 | /// 86 | /// // Listen to _pending_ transactions to the USDT address on mainnet 87 | /// // (there should be a lot of these!) 88 | /// let usdt_address = Address::from_str("dac17f958d2ee523a2206206994597c13d831ec7").unwrap(); 89 | /// let sub_id = manager.subscribe( 90 | /// Some(usdt_address), 91 | /// None 92 | /// ).await.expect("Failed to subscribe to pending transactions!"); 93 | /// 94 | /// // Now we can grab items from the stream 95 | /// let item: AlchemySocketMessageResponse; 96 | /// loop { 97 | /// match manager.receive(sub_id).await { 98 | /// Ok(i) => { 99 | /// item = i; 100 | /// break; 101 | /// }, 102 | /// Err(_) => return, 103 | /// } 104 | /// } 105 | /// 106 | /// // Print the next item 107 | /// println!("Received pending transaction from the stream: {:?}", item); 108 | /// }; 109 | /// ``` 110 | pub async fn subscribe( 111 | &mut self, 112 | to: Option
, 113 | from: Option
, 114 | ) -> Result { 115 | // Extract the internal connection 116 | let connection = match &mut self.connector { 117 | AlchemyConnector::Raw(Some(raw_conn)) => raw_conn, 118 | AlchemyConnector::Provider(Some(_)) => { 119 | return Err(AlchemyConnectionError::Unimplemented) 120 | } 121 | AlchemyConnector::Raw(None) | AlchemyConnector::Provider(None) => { 122 | return Err(AlchemyConnectionError::MissingConnection) 123 | } 124 | }; 125 | 126 | // Example Message body 127 | // { "id": 1, "method": "eth_subscribe", "params": [ "alchemy_pendingTransactions", { "toAddress": "00000000219ab540356cBB839Cbe05303d7705Fa" } ] } 128 | 129 | let mut param_mapping: serde_json::Map = serde_json::Map::new(); 130 | if let Some(t) = to { 131 | param_mapping.insert( 132 | "toAddress".to_string(), 133 | serde_json::Value::String(t.to_string()), 134 | ); 135 | } 136 | if let Some(f) = from { 137 | param_mapping.insert( 138 | "fromAddress".to_string(), 139 | serde_json::Value::String(f.to_string()), 140 | ); 141 | } 142 | 143 | // Construct the Alchemy Socket Message 144 | let message = AlchemySocketMessage { 145 | id: 1, 146 | method: OutSocketMethod::Subscribe, 147 | params: vec![ 148 | serde_json::Value::String(String::from("alchemy_pendingTransactions")), 149 | serde_json::Value::Object(param_mapping), 150 | ], 151 | }; 152 | 153 | // Turn the message into stringified json 154 | let message_string = match serde_json::to_string(&message) { 155 | Ok(s) => s, 156 | Err(e) => return Err(AlchemyConnectionError::Deserialization(e)), 157 | }; 158 | 159 | // Extract the sender from the contained websocket channel 160 | let sender = match &mut connection.sender { 161 | Some(s) => s, 162 | None => return Err(AlchemyConnectionError::MissingSender), 163 | }; 164 | 165 | // Send the string message 166 | if let Err(e) = sender.send_text(message_string).await { 167 | return Err(AlchemyConnectionError::SendFailed(e)); 168 | } 169 | 170 | // Flush the send channel 171 | if let Err(e) = sender.flush().await { 172 | return Err(AlchemyConnectionError::FlushFailed(e)); 173 | } 174 | 175 | // Extract the receiver from the contained websocket channel 176 | let receiver = match &mut connection.receiver { 177 | Some(r) => r, 178 | None => return Err(AlchemyConnectionError::MissingReceiver), 179 | }; 180 | 181 | // After sending the message, the alchemy socket should respond with a subscription id 182 | // Ex: { "id": 1, "result": "0x79a3295f5d5f4bd7efaac4e1738c7ada", "jsonrpc": "2.0" } 183 | let mut data = vec![]; 184 | match receiver.receive_data(&mut data).await { 185 | Ok(soketto::Data::Text(_)) => { 186 | // Convert the data into a text string 187 | let text = match String::from_utf8(data) { 188 | Ok(s) => s, 189 | Err(_) => return Err(AlchemyConnectionError::InvalidTextString), 190 | }; 191 | match serde_json::from_str::(&text) { 192 | Ok(asmr) => Ok(asmr.result), // lol 193 | Err(e) => Err(AlchemyConnectionError::Deserialization(e)), 194 | } 195 | } 196 | Ok(soketto::Data::Binary(_)) => Err(AlchemyConnectionError::UnexpectedResponseType), 197 | Err(soketto::connection::Error::Closed) => Err(AlchemyConnectionError::Closed), 198 | Err(e) => Err(AlchemyConnectionError::SomeError(e)), 199 | } 200 | } 201 | 202 | /// Receive a socket message from the established websocket connection 203 | pub async fn receive( 204 | &mut self, 205 | _sub_id: uuid::Uuid, 206 | ) -> Result { 207 | // Extract the internal connection 208 | let connection = match &mut self.connector { 209 | AlchemyConnector::Raw(Some(raw_conn)) => raw_conn, 210 | AlchemyConnector::Provider(Some(_)) => { 211 | return Err(AlchemyConnectionError::Unimplemented) 212 | } 213 | AlchemyConnector::Raw(None) | AlchemyConnector::Provider(None) => { 214 | return Err(AlchemyConnectionError::MissingConnection) 215 | } 216 | }; 217 | 218 | // Extract the receiver from the contained websocket channel 219 | let receiver = match &mut connection.receiver { 220 | Some(r) => r, 221 | None => return Err(AlchemyConnectionError::MissingReceiver), 222 | }; 223 | 224 | // We should receive an [AlchemySocketMessageResponse](crate::messages::inbound::AlchemySocketMessageResponse) 225 | // on any new `eth_subscription` message 226 | let mut data = vec![]; 227 | 228 | // TODO: we have to wait for the next message with the given subscription id, not just any message 229 | 230 | match receiver.receive_data(&mut data).await { 231 | Ok(soketto::Data::Text(_)) => { 232 | // Convert the data into a text string 233 | let text = match String::from_utf8(data) { 234 | Ok(s) => s, 235 | Err(_) => return Err(AlchemyConnectionError::InvalidTextString), 236 | }; 237 | match serde_json::from_str::(&text) { 238 | Ok(asmr) => Ok(asmr), 239 | Err(e) => Err(AlchemyConnectionError::Deserialization(e)), 240 | } 241 | } 242 | Ok(soketto::Data::Binary(_)) => Err(AlchemyConnectionError::UnexpectedResponseType), 243 | Err(soketto::connection::Error::Closed) => Err(AlchemyConnectionError::Closed), 244 | Err(e) => Err(AlchemyConnectionError::SomeError(e)), 245 | } 246 | } 247 | } 248 | -------------------------------------------------------------------------------- /src/messages/inbound.rs: -------------------------------------------------------------------------------- 1 | use ethers::types::Transaction; 2 | use serde::{Deserialize, Serialize}; 3 | 4 | /// An `eth_subscription` message 5 | pub type EthSubscription = String; 6 | 7 | /// The json rpc version 8 | pub type JsonRpc = String; 9 | 10 | /// Alchemy Subscription Message Result 11 | /// 12 | /// ## Example 13 | /// 14 | /// After sending an eth_subscribe to the alchemy websocket, we should expect a json-stringified response like below. 15 | /// 16 | /// ```json 17 | /// { 18 | /// "id": 1, 19 | /// "result": "0xa79a6df98fb2a42516b5aca3177fbb6c", 20 | /// "jsonrpc": "2.0" 21 | /// } 22 | /// ``` 23 | #[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq)] 24 | pub struct AlchemySubscriptionMessageResult { 25 | /// The message id 26 | pub id: u64, 27 | /// The message result 28 | #[serde( 29 | serialize_with = "serialize_uuid_simple", 30 | deserialize_with = "deserialize_uuid_simple" 31 | )] 32 | pub result: uuid::Uuid, 33 | /// The message jsonrpc 34 | pub jsonrpc: JsonRpc, 35 | } 36 | 37 | pub(crate) fn serialize_uuid_simple(uuid: &uuid::Uuid, s: S) -> Result 38 | where 39 | S: serde::Serializer, 40 | { 41 | s.serialize_str(&format!("0x{}", &uuid.as_simple())) 42 | } 43 | 44 | pub(crate) fn deserialize_uuid_simple<'de, D>(deserializer: D) -> Result 45 | where 46 | D: serde::Deserializer<'de>, 47 | { 48 | match serde_json::Value::deserialize(deserializer) { 49 | Ok(serde_json::Value::String(s)) => { 50 | uuid::Uuid::parse_str(&s.replace("0x", "")).map_err(serde::de::Error::custom) 51 | } 52 | Err(e) => Err(e), 53 | _ => Err(serde::de::Error::custom( 54 | "Deserialized invalid serde_json::Value from uuid", 55 | )), 56 | } 57 | } 58 | 59 | /// An Alchemy Websocket Message Response 60 | /// 61 | /// ## Example 62 | /// 63 | /// After receiving an [AlchemySubscriptionMessageResult](crate::messages::inbound::AlchemySubscriptionMessageResult), 64 | /// we should expect to receive messages with a method string of `eth_subscription`. 65 | /// 66 | /// ```json 67 | /// { 68 | /// "jsonrpc": "2.0", 69 | /// "method": "eth_subscription", 70 | /// "params": { 71 | /// ... 72 | /// } 73 | /// } 74 | /// ``` 75 | #[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq)] 76 | pub struct AlchemySocketMessageResponse { 77 | /// The message jsonrpc 78 | pub jsonrpc: JsonRpc, 79 | /// The message method 80 | pub method: EthSubscription, 81 | /// The inner message result 82 | pub result: AlchemyInnerResponse, 83 | } 84 | 85 | /// An inner Alchemy Websocket Message Response 86 | #[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq)] 87 | #[serde(untagged)] 88 | pub enum AlchemyInnerResponse { 89 | /// An `alchemy_pendingTransactions` message 90 | PendingTransactionResult(PendingTransactionResult), 91 | } 92 | 93 | /// An `alchemy_pendingTransactions` message result 94 | /// 95 | /// ## Example 96 | /// 97 | /// ```json 98 | /// { 99 | /// "result": { 100 | /// "hash": "0xf3207c10a9b9e09b4b51d5c783a1ba85b632055d06100c51f2c1a331dc293d65", 101 | /// "nonce": "0x47", 102 | /// "blockHash": null, 103 | /// "blockNumber": null, 104 | /// "transactionIndex": null, 105 | /// "from": "0xe2ca13527f5accdcdb571a7004a0324e6a36ee6f", 106 | /// "to": "0xdac17f958d2ee523a2206206994597c13d831ec7", 107 | /// "value": "0x0", 108 | /// "gasPrice": "0x59682f000", 109 | /// "gas": "0x11170", 110 | /// "input": "0xa9059cbb000000000000000000000000a02462b8e950cb7ba26f69a6862069231eeb5da10000000000000000000000000000000000000000000000000000000002faf080", 111 | /// "v": "0x0", 112 | /// "r": "0x58abb3787d50b4bd6e4969d08136780eade64971b3a1c24a38b84cd0da52c3fb", 113 | /// "s": "0x4c9ff3765093a1373e0cf08afd7d789636d3a6e1d75e544c917b191d566ab84b", 114 | /// "maxFeePerGas": "0x59682f000", 115 | /// "maxPriorityFeePerGas": "0x77359400", 116 | /// "type": "0x2", 117 | /// "accessList": [], 118 | /// "chainId": "0x1", 119 | /// }, 120 | /// "subscription": "0x79a3295f5d5f4bd7efaac4e1738c7ada" 121 | /// } 122 | /// ``` 123 | #[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq)] 124 | pub struct PendingTransactionResult { 125 | /// The associated subscription uuid 126 | #[serde( 127 | serialize_with = "serialize_uuid_simple", 128 | deserialize_with = "deserialize_uuid_simple" 129 | )] 130 | pub subscription: uuid::Uuid, 131 | /// The message result 132 | pub result: Transaction, 133 | } 134 | -------------------------------------------------------------------------------- /src/messages/mod.rs: -------------------------------------------------------------------------------- 1 | //! Alchemy Websocket Messages 2 | 3 | /// Outbound requests 4 | pub mod outbound; 5 | 6 | /// Inbound responses 7 | pub mod inbound; 8 | 9 | /// A prelude to re-export commonly used types 10 | pub mod prelude { 11 | pub use super::{inbound::*, outbound::*}; 12 | } 13 | -------------------------------------------------------------------------------- /src/messages/outbound.rs: -------------------------------------------------------------------------------- 1 | use serde::{Deserialize, Serialize}; 2 | 3 | /// An Outbound Alchemy Websocket Message 4 | /// 5 | /// ## Example 6 | /// 7 | /// The websocket message should serialize into a json string like: 8 | /// ```json 9 | /// { 10 | /// "id": 1, 11 | /// "method": "eth_subscribe", 12 | /// "params": [ 13 | /// "alchemy_pendingTransactions", 14 | /// { 15 | /// "toAddress": "00000000219ab540356cBB839Cbe05303d7705Fa" 16 | /// } 17 | /// ] 18 | /// } 19 | /// ``` 20 | #[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq)] 21 | pub struct AlchemySocketMessage { 22 | /// The message id 23 | pub id: u64, 24 | /// The message method 25 | pub method: OutSocketMethod, 26 | /// The message params 27 | pub params: Vec, 28 | } 29 | 30 | /// An Alchemy Websocket Message Method 31 | #[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq)] 32 | pub enum OutSocketMethod { 33 | /// Subscribe to a websocket channel 34 | #[serde(rename = "eth_subscribe")] 35 | Subscribe, 36 | /// Unsubscribe from a websocket channel 37 | #[serde(rename = "eth_unsubscribe")] 38 | Unsubscribe, 39 | } 40 | -------------------------------------------------------------------------------- /src/types.rs: -------------------------------------------------------------------------------- 1 | //! Common types for alchemy-rs 2 | 3 | /// ## ExposedProvider 4 | /// 5 | /// A minimal trait that allows objects to expose a method to retrieve their provider. 6 | /// 7 | /// Backwards-compatible with ethers-rs, and forwards-compatible with higher-level wrappers. 8 | /// 9 | /// ### Example 10 | /// 11 | /// Below we demonstrate implementing the [ExposedProvider](alchemy-rs::types::ExposedProvider) trait for a custom struct wrapping a [Provider](ethers::providers::Provider). 12 | /// 13 | /// ```rust 14 | /// use std::convert::TryFrom; 15 | /// use ethers::providers::{Middleware, Provider, Http}; 16 | /// use alchemy_rs::types::{ExposedProvider}; 17 | /// 18 | /// /// A custom struct that wraps a [Provider](ethers::providers::Provider) 19 | /// #[derive(Debug, Clone)] 20 | /// pub struct ProviderWrapper { 21 | /// /// The provider 22 | /// pub provider: Provider, 23 | /// } 24 | /// 25 | /// impl ExposedProvider for ProviderWrapper { 26 | /// fn provider(&self) -> &Provider { 27 | /// &self.provider 28 | /// } 29 | /// } 30 | /// 31 | /// #[cfg(test)] 32 | /// mod tests { 33 | /// use super::*; 34 | /// use ethers::providers::{Http, Provider}; 35 | /// use std::convert::TryFrom; 36 | /// 37 | /// #[test] 38 | /// fn test_expose_provider() { 39 | /// // Instantiate the provider 40 | /// let provider = Provider::::try_from( 41 | /// "https://mainnet.infura.io/v3/c60b0bb42f8a4c6481ecd229eddaca27" 42 | /// ).expect("could not instantiate HTTP Provider"); 43 | /// 44 | /// // Create the wrapper containing the provider 45 | /// let wrapper = ProviderWrapper { provider }; 46 | /// 47 | /// // Retrieve the provider from the wrapper 48 | /// let retrieved = wrapper.provider(); 49 | /// 50 | /// // Verify that we can get a block from the provider 51 | /// let block = provider.get_block(100u64).await?; 52 | /// println!("Got block: {}", serde_json::to_string(&block)?); 53 | /// } 54 | /// } 55 | /// ``` 56 | pub trait ExposedProvider { 57 | /// Retrieve the provider 58 | fn provider(&self) -> ðers::providers::Provider; 59 | } 60 | -------------------------------------------------------------------------------- /src/wrapper.rs: -------------------------------------------------------------------------------- 1 | //! TODO: An ethers-rs wrapper for the Alchemy API. 2 | //! Similar to the CeloMiddleware as a 3 | 4 | // #[cfg_attr(target_arch = "wasm32", async_trait(?Send))] 5 | // #[cfg_attr(not(target_arch = "wasm32"), async_trait)] 6 | // pub trait AlchemyMiddleware: Middleware { 7 | // async fn alchemy_pending_transactions + Send + Sync + serde::Serialize>( 8 | // &self, 9 | // to: Option, 10 | // from: Option, 11 | // ) -> Result, Self::Error> { 12 | // self.provider() 13 | // .alchemy_pending_transactions(to, from) 14 | // .await 15 | // .map_err(FromErr::from) 16 | // } 17 | // } 18 | 19 | // #[cfg_attr(target_arch = "wasm32", async_trait(?Send))] 20 | // #[cfg_attr(not(target_arch = "wasm32"), async_trait)] 21 | // impl AlchemyMiddleware for Provider

{ 22 | // async fn alchemy_pending_transactions + Send + Sync + serde::Serialize>( 23 | // &self, 24 | // to: Option, 25 | // from: Option, 26 | // ) -> Result, Self::Error> { 27 | // let params = vec![ 28 | // to.map(|t| serde_json::to_value(t).expect("Types never fail to serialize.")), 29 | // from.map(|t| serde_json::to_value(t).expect("Types never fail to serialize.")), 30 | // ] 31 | // .into_iter() 32 | // .flatten() 33 | // .collect(); 34 | // self.request("alchemy_pendingTransactions", params).await 35 | // } 36 | // } 37 | -------------------------------------------------------------------------------- /tests/manager.rs: -------------------------------------------------------------------------------- 1 | use std::str::FromStr; 2 | 3 | use ethers::types::Address; 4 | 5 | use alchemy_rs::{prelude::*, connectors::AlchemyConnectorType}; 6 | 7 | #[actix_rt::test] 8 | async fn test_alchemy_subscription() { 9 | // Create the AlchemyManager 10 | let mut manager = AlchemyManager::new( 11 | "wss://eth-mainnet.g.alchemy.com/v2/MVNYMOb_58bAMzhXX2pS25NDiZ3Q9HeC", 12 | Some(AlchemyConnectorType::Raw), 13 | ); 14 | 15 | // Connect to the websocket 16 | let _ = manager.connect().await.unwrap(); 17 | 18 | // Listen to _pending_ transactions to the USDT address on mainnet 19 | // (there should be a lot of these!) 20 | let usdt_address = Address::from_str("dac17f958d2ee523a2206206994597c13d831ec7").unwrap(); 21 | 22 | // Try to subscribe to pending transactions 23 | let sub_id = match manager.subscribe(Some(usdt_address), None).await { 24 | Ok(id) => id, 25 | Err(e) => { 26 | println!("Error subscribing to pending transactions: {:?}", e); 27 | return; 28 | } 29 | }; 30 | 31 | // Now we can grab items from the stream 32 | let item = match manager.receive(sub_id).await { 33 | Ok(i) => i, 34 | Err(e) => { 35 | println!("Error receiving item: {:?}", e); 36 | return; 37 | } 38 | }; 39 | 40 | // Print the next item 41 | println!("Received pending transaction from the stream: {:?}", item); 42 | } 43 | -------------------------------------------------------------------------------- /tests/messages.rs: -------------------------------------------------------------------------------- 1 | use alchemy_rs::messages::{ 2 | outbound::{AlchemySocketMessage, OutSocketMethod}, 3 | prelude::AlchemySubscriptionMessageResult, 4 | }; 5 | 6 | mod util; 7 | 8 | #[test] 9 | fn test_outbound_alchemy_socket_message_serialization() { 10 | // Craft an expected alchemy outbound eth_subscribe socket message json string 11 | let expected = r#"{ 12 | "id": 1, 13 | "method": "eth_subscribe", 14 | "params": [ 15 | "alchemy_pendingTransactions", 16 | { 17 | "toAddress": "dac17f958d2ee523a2206206994597c13d831ec7" 18 | } 19 | ] 20 | }"#; 21 | 22 | // Construct a raw outbound alchemy socket message 23 | let mut map = serde_json::Map::new(); 24 | map.insert( 25 | "toAddress".to_string(), 26 | serde_json::Value::String("dac17f958d2ee523a2206206994597c13d831ec7".to_string()), 27 | ); 28 | let constructed = AlchemySocketMessage { 29 | id: 1, 30 | method: OutSocketMethod::Subscribe, 31 | params: vec![ 32 | serde_json::Value::String(String::from("alchemy_pendingTransactions")), 33 | serde_json::Value::Object(map), 34 | ], 35 | }; 36 | 37 | // Make sure it can serialize to the expected string 38 | let serialized_string = match serde_json::to_string(&constructed) { 39 | Ok(s) => { 40 | util::assert_strings_roughly_equal(&s, expected); 41 | s 42 | } 43 | Err(e) => panic!("Failed to serialize outbound message: {}", e), 44 | }; 45 | 46 | // Now take the resulting serialized string and deserialize it into an alchemy outbound socket message 47 | let deserialized = match serde_json::from_str::(&serialized_string) { 48 | Ok(d) => d, 49 | Err(e) => panic!("Failed to deserialize outbound message: {}", e), 50 | }; 51 | 52 | // Make sure the deserialized message is the same as the constructed message 53 | assert_eq!(constructed, deserialized); 54 | } 55 | 56 | #[test] 57 | fn test_inbound_alchemy_subscription_message_result_serialization() { 58 | // Craft the expected json string 59 | let expected = r#"{ 60 | "id": 1, 61 | "result": "0xa79a6df98fb2a42516b5aca3177fbb6c", 62 | "jsonrpc": "2.0" 63 | }"#; 64 | 65 | // Construct a concrete struct 66 | let constructed = AlchemySubscriptionMessageResult { 67 | id: 1, 68 | result: uuid::Uuid::parse_str("a79a6df98fb2a42516b5aca3177fbb6c").unwrap(), 69 | jsonrpc: "2.0".to_string(), 70 | }; 71 | 72 | // Validate serialization 73 | let serialized_string = match serde_json::to_string(&constructed) { 74 | Ok(s) => { 75 | util::assert_strings_roughly_equal(&s, expected); 76 | s 77 | } 78 | Err(e) => panic!("Failed to serialize: {}", e), 79 | }; 80 | 81 | // Now take the resulting serialized string and deserialize it 82 | let deserialized = 83 | match serde_json::from_str::(&serialized_string) { 84 | Ok(d) => d, 85 | Err(e) => panic!("Failed to deserialize: {}", e), 86 | }; 87 | 88 | // Make sure the deserialized message is the same as the constructed message 89 | assert_eq!(constructed, deserialized); 90 | } 91 | -------------------------------------------------------------------------------- /tests/sockets.rs: -------------------------------------------------------------------------------- 1 | use tokio_util::compat::TokioAsyncReadCompatExt; 2 | 3 | #[actix_rt::test] 4 | async fn test_connecting_to_alchemy() { 5 | // Create the socket connection 6 | let socket = match tokio::net::TcpStream::connect("eth-mainnet.g.alchemy.com:443").await { 7 | Ok(s) => s, 8 | Err(e) => panic!("Could not connect to Alchemy: {:?}", e), 9 | }; 10 | println!("Create socket connection to Alchemy"); 11 | 12 | // Create the client connection 13 | let compatible_socket = futures::io::BufReader::new(futures::io::BufWriter::new(socket.compat())); 14 | let mut client = soketto::handshake::Client::new(compatible_socket, "ws://eth-mainnet.g.alchemy.com", "/v2/MVNYMOb_58bAMzhXX2pS25NDiZ3Q9HeC"); 15 | println!("Created client connection"); 16 | 17 | // let api_key = "MVNYMOb_58bAMzhXX2pS25NDiZ3Q9HeC".as_bytes().to_vec(); 18 | let gzip = "gzip".as_bytes().to_vec(); 19 | let version = "2.0.3".as_bytes().to_vec(); 20 | let auth_header = vec![ 21 | // soketto::handshake::client::Header { 22 | // name: "ALCHEMY_API_KEY", 23 | // value: &api_key, 24 | // }, 25 | soketto::handshake::client::Header { 26 | name: "Alchemy-Ethers-Sdk-Version", 27 | value: &version, 28 | }, 29 | soketto::handshake::client::Header { 30 | name: "Accept-Encoding", 31 | value: &gzip, 32 | }, 33 | ]; 34 | client.set_headers(auth_header.as_slice()); 35 | 36 | // Handshake the connection 37 | match client.handshake().await { 38 | Ok(sr) => { 39 | match sr { 40 | soketto::handshake::ServerResponse::Accepted { protocol } => { 41 | println!("Accepted protocol: {:?}", protocol); 42 | } 43 | soketto::handshake::ServerResponse::Redirect { status_code, location } => { 44 | println!("Redirected with status code: {}, location: {}", status_code, location); 45 | } 46 | soketto::handshake::ServerResponse::Rejected { status_code } => { 47 | println!("Rejected with status code: {}", status_code); 48 | panic!("Rejected with status code: {}", status_code); 49 | } 50 | } 51 | } 52 | Err(e) => panic!("Handshake error! {:?}", e), 53 | } 54 | 55 | let (_, _) = client.into_builder().finish(); 56 | } 57 | -------------------------------------------------------------------------------- /tests/tls.rs: -------------------------------------------------------------------------------- 1 | use async_tls::TlsConnector; 2 | use async_std::net::TcpStream; 3 | 4 | #[actix_rt::test] 5 | async fn test_connecting_to_alchemy() { 6 | // Create the socket connection 7 | let socket = match TcpStream::connect("eth-mainnet.g.alchemy.com:443").await { 8 | Ok(s) => s, 9 | Err(e) => panic!("Could not connect to Alchemy: {:?}", e), 10 | }; 11 | println!("Create socket connection to Alchemy"); 12 | 13 | // Create the async-tls connector 14 | let connector = TlsConnector::default(); 15 | 16 | // Establish the connection 17 | let mut _tls_stream = match connector.connect("wss://eth-mainnet.g.alchemy.com/v2/MVNYMOb_58bAMzhXX2pS25NDiZ3Q9HeC", socket).await { 18 | Ok(s) => s, 19 | Err(e) => panic!("Could not connect to Alchemy: {:?}", e), 20 | }; 21 | 22 | } 23 | -------------------------------------------------------------------------------- /tests/types.rs: -------------------------------------------------------------------------------- 1 | use ethers::providers::{Http, Middleware, Provider}; 2 | use std::convert::TryFrom; 3 | 4 | use alchemy_rs::types::*; 5 | 6 | #[derive(Debug, Clone)] 7 | pub struct ProviderWrapper { 8 | /// The provider 9 | pub provider: Provider, 10 | } 11 | 12 | impl ExposedProvider for ProviderWrapper { 13 | fn provider(&self) -> &Provider { 14 | &self.provider 15 | } 16 | } 17 | 18 | #[actix_rt::test] 19 | async fn test_expose_provider() { 20 | // Instantiate the provider 21 | let provider = 22 | Provider::::try_from("https://mainnet.infura.io/v3/c60b0bb42f8a4c6481ecd229eddaca27") 23 | .expect("could not instantiate HTTP Provider"); 24 | 25 | // Create the wrapper containing the provider 26 | let wrapper = ProviderWrapper { provider }; 27 | 28 | // Retrieve the provider from the wrapper 29 | let retrieved = wrapper.provider(); 30 | 31 | // Verify that we can get a block from the provider 32 | let block = retrieved.get_block(100u64).await.unwrap(); 33 | println!("Got block: {}", serde_json::to_string(&block).unwrap()); 34 | } 35 | -------------------------------------------------------------------------------- /tests/util.rs: -------------------------------------------------------------------------------- 1 | pub fn assert_strings_roughly_equal(a: impl Into, b: impl Into) { 2 | let undressed_a = (a.into() as String).as_str().replace(['\n', ' ', '\t'], ""); 3 | let undressed_b = (b.into() as String).as_str().replace(['\n', ' ', '\t'], ""); 4 | assert_eq!(undressed_a, undressed_b); 5 | } 6 | --------------------------------------------------------------------------------