Skip to content

Commit

Permalink
chore(docs): finish doctests and docstrings for heimdall_common
Browse files Browse the repository at this point in the history
  • Loading branch information
Jon-Becker committed Nov 15, 2023
1 parent 0d691f6 commit 8cb8e2c
Show file tree
Hide file tree
Showing 17 changed files with 809 additions and 603 deletions.
22 changes: 11 additions & 11 deletions common/src/constants.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,32 +3,32 @@ use lazy_static::lazy_static;

lazy_static! {

// The following regex is used to validate Ethereum addresses.
/// The following regex is used to validate Ethereum addresses.
pub static ref ADDRESS_REGEX: Regex = Regex::new(r"^(0x)?[0-9a-fA-F]{40}$").unwrap();

// The following regex is used to validate Ethereum transaction hashes.
/// The following regex is used to validate Ethereum transaction hashes.
pub static ref TRANSACTION_HASH_REGEX: Regex = Regex::new(r"^(0x)?[0-9a-fA-F]{64}$").unwrap();

// The following regex is used to validate raw bytecode files as targets.
// It also restricts the file to a maximum of ~24kb, the maximum size of a
// contract on Ethereum.
/// The following regex is used to validate raw bytecode files as targets.
/// It also restricts the file to a maximum of ~24kb, the maximum size of a
/// contract on Ethereum.
pub static ref BYTECODE_REGEX: Regex = Regex::new(r"^(0x)?[0-9a-fA-F]{0,50000}$").unwrap();

// The following regex is used to reduce null byte prefixes
/// The following regex is used to reduce null byte prefixes
pub static ref REDUCE_HEX_REGEX: Regex = Regex::new(r"^0x(00)*").unwrap();

// The following regex is used as a search pattern for words
/// The following regex is used as a search pattern for words
pub static ref WORD_REGEX: Regex = Regex::new(r"0x[0-9a-fA-F]{0,64}").unwrap();

// The following regex is used to find type castings
/// The following regex is used to find type castings
pub static ref TYPE_CAST_REGEX: Regex = Regex::new(r"(address\(|string\(|bool\(|bytes(\d*)\(|uint(\d*)\(|int(\d*)\()(?!\))").unwrap();

// The following regex is used to find memory length accesses
/// The following regex is used to find memory length accesses
pub static ref MEMLEN_REGEX: Regex = Regex::new(r"memory\[memory\[[0-9x]*\]\]").unwrap();

// The following regex is used to find memory accesses
/// The following regex is used to find memory accesses
pub static ref MEMORY_REGEX: Regex = Regex::new(r"memory\[\(?[0-9x]*\]").unwrap();

// The following regex is used to find storage accesses
/// The following regex is used to find storage accesses
pub static ref STORAGE_REGEX: Regex = Regex::new(r"storage\[\(?[0-9x]*\]").unwrap();
}
2 changes: 1 addition & 1 deletion common/src/ether/evm/core/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -318,7 +318,7 @@ pub fn convert_bitmask(instruction: Instruction) -> (usize, Vec<String>) {
/// 2. Potential types that the byte size could be.
///
/// ```
/// use heimdall_common::ether::evm::utils::byte_size_to_type;
/// use heimdall_common::ether::evm::core::types::byte_size_to_type;
///
/// let (byte_size, potential_types) = byte_size_to_type(1);
/// assert_eq!(byte_size, 1);
Expand Down
12 changes: 6 additions & 6 deletions common/src/ether/rpc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,8 @@ use heimdall_cache::{read_cache, store_cache};
/// ```no_run
/// use heimdall_common::ether::rpc::chain_id;
///
/// let chain_id = chain_id("https://eth.llamarpc.com").await.unwrap();
/// assert_eq!(chain_id, 1);
/// // let chain_id = chain_id("https://eth.llamarpc.com").await.unwrap();
/// //assert_eq!(chain_id, 1);
/// ```
pub async fn chain_id(rpc_url: &str) -> Result<u64, Box<dyn std::error::Error>> {
// get a new logger
Expand Down Expand Up @@ -66,8 +66,8 @@ pub async fn chain_id(rpc_url: &str) -> Result<u64, Box<dyn std::error::Error>>
/// ```no_run
/// use heimdall_common::ether::rpc::get_code;
///
/// let bytecode = get_code("0x0", "https://eth.llamarpc.com").await;
/// assert!(bytecode.is_ok());
/// // let bytecode = get_code("0x0", "https://eth.llamarpc.com").await;
/// // assert!(bytecode.is_ok());
/// ```
pub async fn get_code(
contract_address: &str,
Expand Down Expand Up @@ -136,8 +136,8 @@ pub async fn get_code(
/// ```no_run
/// use heimdall_common::ether::rpc::get_code;
///
/// let bytecode = get_code("0x0", "https://eth.llamarpc.com").await;
/// assert!(bytecode.is_ok());
/// // let bytecode = get_code("0x0", "https://eth.llamarpc.com").await;
/// // assert!(bytecode.is_ok());
/// ```
pub async fn get_transaction(
transaction_hash: &str,
Expand Down
8 changes: 8 additions & 0 deletions common/src/resources/openai.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,14 @@
use crate::utils::io::logging::Logger;
use async_openai::{types::CreateCompletionRequestArgs, Client};

/// Complete the given prompt using the OpenAI API.
///
/// ```
/// use heimdall_common::resources::openai::complete;
///
/// let prompt = "what is love?";
/// let api_key = "your-api-key";
/// // complete(prompt, api_key).await;
pub async fn complete(prompt: &str, api_key: &str) -> Option<String> {
let client = Client::new().with_api_key(api_key);

Expand Down
25 changes: 25 additions & 0 deletions common/src/resources/transpose.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ struct TransposeResponse {
results: Vec<Value>,
}

/// executes a transpose SQL query and returns the response
async fn _call_transpose(query: &str, api_key: &str) -> Option<TransposeResponse> {
// get a new logger
let logger = Logger::default();
Expand Down Expand Up @@ -74,6 +75,19 @@ async fn _call_transpose(query: &str, api_key: &str) -> Option<TransposeResponse
}
}

/// Get all interactions with the given address. Includes transactions to, from, as well as internal
/// transactions to and from the address.
///
/// ```
/// use heimdall_common::resources::transpose::get_transaction_list;
///
/// let chain = "ethereum";
/// let address = "0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2";
/// let api_key = "YOUR_API_KEY";
/// let bounds = (0, 1); // block number bounds
///
/// // let transactions = get_transaction_list(chain, address, api_key, bounds).await;
/// ```
pub async fn get_transaction_list(
chain: &str,
address: &str,
Expand Down Expand Up @@ -152,6 +166,17 @@ pub async fn get_transaction_list(
transactions
}

/// Get the contrct creation block and transaction hash for the given address.
///
/// ```
/// use heimdall_common::resources::transpose::get_contract_creation;
///
/// let chain = "ethereum";
/// let address = "0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2";
/// let api_key = "YOUR_API_KEY";
///
/// // let contract_creation = get_contract_creation(chain, address, api_key).await;
/// ```
pub async fn get_contract_creation(
chain: &str,
address: &str,
Expand Down
13 changes: 8 additions & 5 deletions common/src/utils/http.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,17 +9,20 @@ static APP_USER_AGENT: &str = concat!(env!("CARGO_PKG_NAME"), "/", env!("CARGO_P

/// Make a GET request to the target URL and return the response body as JSON
///
/// # Arguments
/// `url` - the URL to make the GET request to
/// `timeout` - timeout duration in seconds
/// ```no_run
/// use heimdall_common::utils::http::get_json_from_url;
///
/// # Returns
/// `Result<Option<Value>, reqwest::Error>` - the response body as JSON
/// let url = "https://example.com";
/// let timeout = 5;
/// // get_json_from_url(url, timeout).await;
/// ```
pub async fn get_json_from_url(url: &str, timeout: u64) -> Result<Option<Value>, reqwest::Error> {
_get_json_from_url(url, 0, 5, timeout).await
}

#[async_recursion]
/// Internal function for making a GET request to the target URL and returning the response body as
/// JSON
async fn _get_json_from_url(
url: &str,
retry_count: u8,
Expand Down
56 changes: 55 additions & 1 deletion common/src/utils/integers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,13 @@ pub trait ToLocaleString {
}

impl ToLocaleString for usize {
// add commas every 3 digits, e.g. 1000000 -> 1,000,000.
/// Add commas every 3 digits, e.g. 1000000 -> 1,000,000.
///
/// ```
/// use heimdall_common::utils::integers::ToLocaleString;
///
/// assert_eq!(1000000.to_locale_string(), "1,000,000");
/// ```
fn to_locale_string(&self) -> String {
let num_str = self.to_string();
let mut result = String::new();
Expand All @@ -18,3 +24,51 @@ impl ToLocaleString for usize {
result.chars().rev().collect()
}
}

#[cfg(test)]
mod tests {
use crate::utils::integers::ToLocaleString;

#[test]
fn test_to_locale_string() {
// Test case: Single-digit number
let num = 5;
let expected = "5".to_string();
assert_eq!(num.to_locale_string(), expected);

// Test case: Three-digit number
let num = 123;
let expected = "123".to_string();
assert_eq!(num.to_locale_string(), expected);

// Test case: Four-digit number
let num = 1234;
let expected = "1,234".to_string();
assert_eq!(num.to_locale_string(), expected);

// Test case: Five-digit number
let num = 12345;
let expected = "12,345".to_string();
assert_eq!(num.to_locale_string(), expected);

// Test case: Six-digit number
let num = 123456;
let expected = "123,456".to_string();
assert_eq!(num.to_locale_string(), expected);

// Test case: Seven-digit number
let num = 1234567;
let expected = "1,234,567".to_string();
assert_eq!(num.to_locale_string(), expected);

// Test case: Eight-digit number
let num = 12345678;
let expected = "12,345,678".to_string();
assert_eq!(num.to_locale_string(), expected);

// Test case: Nine-digit number
let num = 123456789;
let expected = "123,456,789".to_string();
assert_eq!(num.to_locale_string(), expected);
}
}
43 changes: 43 additions & 0 deletions common/src/utils/io/file.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,15 @@ use std::{
process::Command,
};

/// Convert a long path to a short path.
///
/// ```no_run
/// use heimdall_common::utils::io::file::short_path;
///
/// let path = "/some/long/path/that/is/cwd/something.json";
/// let short_path = short_path(path);
/// assert_eq!(short_path, "./something.json");
/// ```
pub fn short_path(path: &str) -> String {
let current_dir = match env::current_dir() {
Ok(dir) => dir.into_os_string().into_string().unwrap(),
Expand All @@ -15,6 +24,15 @@ pub fn short_path(path: &str) -> String {
path.replace(&current_dir, ".")
}

/// Write contents to a file on the disc
///
/// ```no_run
/// use heimdall_common::utils::io::file::write_file;
///
/// let path = "/tmp/test.txt";
/// let contents = "Hello, World!";
/// let result = write_file(path, contents);
/// ```
pub fn write_file(_path: &str, contents: &str) -> String {
let path = std::path::Path::new(_path);
let prefix = path.parent().unwrap();
Expand All @@ -40,10 +58,27 @@ pub fn write_file(_path: &str, contents: &str) -> String {
_path.to_string()
}

/// Write contents to a file on the disc
///
/// ```no_run
/// use heimdall_common::utils::io::file::write_lines_to_file;
///
/// let path = "/tmp/test.txt";
/// let contents = vec![String::from("Hello"), String::from("World!")];
/// let result = write_lines_to_file(path, contents);
/// ```
pub fn write_lines_to_file(_path: &str, contents: Vec<String>) {
write_file(_path, &contents.join("\n"));
}

/// Read contents from a file on the disc
///
/// ```no_run
/// use heimdall_common::utils::io::file::read_file;
///
/// let path = "/tmp/test.txt";
/// let contents = read_file(path);
/// ```
pub fn read_file(_path: &str) -> String {
let path = std::path::Path::new(_path);
let mut file = match File::open(path) {
Expand All @@ -66,6 +101,14 @@ pub fn read_file(_path: &str) -> String {
contents
}

/// Delete a file from the disc
///
/// ```no_run
/// use heimdall_common::utils::io::file::delete_path;
///
/// let path = "/tmp/test.txt";
/// let result = delete_path(path);
/// ```
pub fn delete_path(_path: &str) -> bool {
let path = std::path::Path::new(_path);
Command::new("rm").args(["-rf", path.to_str().unwrap()]).output().is_ok()
Expand Down
1 change: 0 additions & 1 deletion common/src/utils/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ pub mod io;
pub mod strings;
pub mod sync;
pub mod testing;
mod tests;
pub mod threading;
pub mod time;
pub mod version;
Loading

0 comments on commit 8cb8e2c

Please sign in to comment.