Explorar el Código

chore: apply rustfmt

Pavel Strakhov hace 1 año
padre
commit
955a805e85
Se han modificado 100 ficheros con 733 adiciones y 1896 borrados
  1. 25 64
      apps/fortuna/src/api.rs
  2. 2 8
      apps/fortuna/src/api/chain_ids.rs
  3. 1 4
      apps/fortuna/src/api/index.rs
  4. 1 4
      apps/fortuna/src/api/live.rs
  5. 1 4
      apps/fortuna/src/api/metrics.rs
  6. 1 4
      apps/fortuna/src/api/ready.rs
  7. 3 14
      apps/fortuna/src/api/revelation.rs
  8. 2 10
      apps/fortuna/src/chain/eth_gas_oracle.rs
  9. 16 56
      apps/fortuna/src/chain/ethereum.rs
  10. 7 18
      apps/fortuna/src/chain/nonce_manager.rs
  11. 13 26
      apps/fortuna/src/chain/reader.rs
  12. 9 23
      apps/fortuna/src/chain/traced_client.rs
  13. 3 8
      apps/fortuna/src/command.rs
  14. 2 8
      apps/fortuna/src/command/generate.rs
  15. 1 4
      apps/fortuna/src/command/get_request.rs
  16. 3 13
      apps/fortuna/src/command/inspect.rs
  17. 6 20
      apps/fortuna/src/command/register_provider.rs
  18. 1 4
      apps/fortuna/src/command/request_randomness.rs
  19. 12 52
      apps/fortuna/src/command/run.rs
  20. 9 38
      apps/fortuna/src/command/setup_provider.rs
  21. 3 13
      apps/fortuna/src/command/withdraw_fees.rs
  22. 11 33
      apps/fortuna/src/config.rs
  23. 1 4
      apps/fortuna/src/config/generate.rs
  24. 1 4
      apps/fortuna/src/config/get_request.rs
  25. 1 5
      apps/fortuna/src/config/inspect.rs
  26. 1 4
      apps/fortuna/src/config/register_provider.rs
  27. 1 4
      apps/fortuna/src/config/request_randomness.rs
  28. 1 5
      apps/fortuna/src/config/run.rs
  29. 1 4
      apps/fortuna/src/config/setup_provider.rs
  30. 1 4
      apps/fortuna/src/config/withdraw_fees.rs
  31. 34 81
      apps/fortuna/src/keeper.rs
  32. 1 5
      apps/fortuna/src/main.rs
  33. 7 17
      apps/fortuna/src/state.rs
  34. 6 16
      apps/hermes/server/src/api.rs
  35. 5 12
      apps/hermes/server/src/api/metrics_middleware.rs
  36. 5 19
      apps/hermes/server/src/api/rest.rs
  37. 3 13
      apps/hermes/server/src/api/rest/get_price_feed.rs
  38. 5 23
      apps/hermes/server/src/api/rest/get_vaa.rs
  39. 6 25
      apps/hermes/server/src/api/rest/get_vaa_ccip.rs
  40. 1 4
      apps/hermes/server/src/api/rest/index.rs
  41. 3 12
      apps/hermes/server/src/api/rest/latest_price_feeds.rs
  42. 4 19
      apps/hermes/server/src/api/rest/latest_vaas.rs
  43. 1 4
      apps/hermes/server/src/api/rest/live.rs
  44. 2 9
      apps/hermes/server/src/api/rest/price_feed_ids.rs
  45. 2 8
      apps/hermes/server/src/api/rest/ready.rs
  46. 6 26
      apps/hermes/server/src/api/rest/v2/latest_price_updates.rs
  47. 4 13
      apps/hermes/server/src/api/rest/v2/latest_publisher_stake_caps.rs
  48. 2 9
      apps/hermes/server/src/api/rest/v2/price_feeds_metadata.rs
  49. 5 23
      apps/hermes/server/src/api/rest/v2/sse.rs
  50. 5 23
      apps/hermes/server/src/api/rest/v2/timestamp_price_updates.rs
  51. 59 86
      apps/hermes/server/src/api/types.rs
  52. 41 83
      apps/hermes/server/src/api/ws.rs
  53. 1 8
      apps/hermes/server/src/config.rs
  54. 1 4
      apps/hermes/server/src/config/aggregate.rs
  55. 1 4
      apps/hermes/server/src/config/benchmarks.rs
  56. 1 4
      apps/hermes/server/src/config/metrics.rs
  57. 1 4
      apps/hermes/server/src/config/pythnet.rs
  58. 1 5
      apps/hermes/server/src/config/rpc.rs
  59. 1 4
      apps/hermes/server/src/config/wormhole.rs
  60. 2 8
      apps/hermes/server/src/main.rs
  61. 2 12
      apps/hermes/server/src/metrics_server.rs
  62. 13 54
      apps/hermes/server/src/network/pythnet.rs
  63. 12 24
      apps/hermes/server/src/network/wormhole.rs
  64. 1 6
      apps/hermes/server/src/serde.rs
  65. 11 28
      apps/hermes/server/src/state.rs
  66. 65 115
      apps/hermes/server/src/state/aggregate.rs
  67. 9 19
      apps/hermes/server/src/state/aggregate/metrics.rs
  68. 25 46
      apps/hermes/server/src/state/aggregate/wormhole_merkle.rs
  69. 3 9
      apps/hermes/server/src/state/benchmarks.rs
  70. 25 47
      apps/hermes/server/src/state/cache.rs
  71. 1 4
      apps/hermes/server/src/state/metrics.rs
  72. 1 5
      apps/hermes/server/src/state/price_feeds_metadata.rs
  73. 10 35
      apps/hermes/server/src/state/wormhole.rs
  74. 10 16
      governance/remote_executor/cli/src/cli.rs
  75. 30 64
      governance/remote_executor/cli/src/main.rs
  76. 7 20
      governance/remote_executor/programs/remote-executor/src/lib.rs
  77. 1 4
      governance/remote_executor/programs/remote-executor/src/state/claim_record.rs
  78. 24 38
      governance/remote_executor/programs/remote-executor/src/state/governance_payload.rs
  79. 2 6
      governance/remote_executor/programs/remote-executor/src/state/posted_vaa.rs
  80. 29 59
      governance/remote_executor/programs/remote-executor/src/tests/executor_simulator.rs
  81. 4 15
      governance/remote_executor/programs/remote-executor/src/tests/test_adversarial.rs
  82. 4 15
      governance/remote_executor/programs/remote-executor/src/tests/test_basic_instructions.rs
  83. 3 14
      pythnet/message_buffer/programs/message_buffer/src/instructions/create_buffer.rs
  84. 1 5
      pythnet/message_buffer/programs/message_buffer/src/instructions/delete_buffer.rs
  85. 2 11
      pythnet/message_buffer/programs/message_buffer/src/instructions/mod.rs
  86. 2 6
      pythnet/message_buffer/programs/message_buffer/src/instructions/put_all.rs
  87. 1 7
      pythnet/message_buffer/programs/message_buffer/src/instructions/resize_buffer.rs
  88. 4 13
      pythnet/message_buffer/programs/message_buffer/src/lib.rs
  89. 9 30
      pythnet/message_buffer/programs/message_buffer/src/state/message_buffer.rs
  90. 1 4
      pythnet/message_buffer/programs/message_buffer/src/state/mod.rs
  91. 3 7
      pythnet/message_buffer/programs/message_buffer/src/state/whitelist.rs
  92. 13 29
      pythnet/message_buffer/programs/mock-cpi-caller/src/instructions/add_price.rs
  93. 2 9
      pythnet/message_buffer/programs/mock-cpi-caller/src/instructions/cpi_max_test.rs
  94. 1 5
      pythnet/message_buffer/programs/mock-cpi-caller/src/instructions/mod.rs
  95. 9 22
      pythnet/message_buffer/programs/mock-cpi-caller/src/instructions/update_price.rs
  96. 3 10
      pythnet/message_buffer/programs/mock-cpi-caller/src/lib.rs
  97. 2 3
      pythnet/message_buffer/programs/mock-cpi-caller/src/message.rs
  98. 21 30
      pythnet/message_buffer/programs/mock-cpi-caller/src/message/price.rs
  99. 4 4
      pythnet/message_buffer/programs/mock-cpi-caller/src/state/mod.rs
  100. 7 13
      pythnet/message_buffer/programs/mock-cpi-caller/src/state/price.rs

+ 25 - 64
apps/fortuna/src/api.rs

@@ -1,47 +1,27 @@
 use {
     crate::{
-        chain::reader::{
-            BlockNumber,
-            BlockStatus,
-            EntropyReader,
-        },
+        chain::reader::{BlockNumber, BlockStatus, EntropyReader},
         state::HashChainState,
     },
     anyhow::Result,
     axum::{
         body::Body,
         http::StatusCode,
-        response::{
-            IntoResponse,
-            Response,
-        },
+        response::{IntoResponse, Response},
         routing::get,
         Router,
     },
     ethers::core::types::Address,
     prometheus_client::{
         encoding::EncodeLabelSet,
-        metrics::{
-            counter::Counter,
-            family::Family,
-        },
+        metrics::{counter::Counter, family::Family},
         registry::Registry,
     },
-    std::{
-        collections::HashMap,
-        sync::Arc,
-    },
+    std::{collections::HashMap, sync::Arc},
     tokio::sync::RwLock,
     url::Url,
 };
-pub use {
-    chain_ids::*,
-    index::*,
-    live::*,
-    metrics::*,
-    ready::*,
-    revelation::*,
-};
+pub use {chain_ids::*, index::*, live::*, metrics::*, ready::*, revelation::*};
 
 mod chain_ids;
 mod index;
@@ -99,16 +79,16 @@ impl ApiState {
 #[derive(Clone)]
 pub struct BlockchainState {
     /// The chain id for this blockchain, useful for logging
-    pub id:                     ChainId,
+    pub id: ChainId,
     /// The hash chain(s) required to serve random numbers for this blockchain
-    pub state:                  Arc<HashChainState>,
+    pub state: Arc<HashChainState>,
     /// The contract that the server is fulfilling requests for.
-    pub contract:               Arc<dyn EntropyReader>,
+    pub contract: Arc<dyn EntropyReader>,
     /// The address of the provider that this server is operating for.
-    pub provider_address:       Address,
+    pub provider_address: Address,
     /// The server will wait for this many block confirmations of a request before revealing
     /// the random number.
-    pub reveal_delay_blocks:    BlockNumber,
+    pub reveal_delay_blocks: BlockNumber,
     /// The BlockStatus of the block that is considered to be confirmed on the blockchain.
     /// For eg., Finalized, Safe
     pub confirmed_block_status: BlockStatus,
@@ -194,35 +174,16 @@ pub fn get_register_uri(base_uri: &str, chain_id: &str) -> Result<String> {
 mod test {
     use {
         crate::{
-            api::{
-                self,
-                ApiState,
-                BinaryEncoding,
-                Blob,
-                BlockchainState,
-                GetRandomValueResponse,
-            },
-            chain::reader::{
-                mock::MockEntropyReader,
-                BlockStatus,
-            },
-            state::{
-                HashChainState,
-                PebbleHashChain,
-            },
+            api::{self, ApiState, BinaryEncoding, Blob, BlockchainState, GetRandomValueResponse},
+            chain::reader::{mock::MockEntropyReader, BlockStatus},
+            state::{HashChainState, PebbleHashChain},
         },
         axum::http::StatusCode,
-        axum_test::{
-            TestResponse,
-            TestServer,
-        },
+        axum_test::{TestResponse, TestServer},
         ethers::prelude::Address,
         lazy_static::lazy_static,
         prometheus_client::registry::Registry,
-        std::{
-            collections::HashMap,
-            sync::Arc,
-        },
+        std::{collections::HashMap, sync::Arc},
         tokio::sync::RwLock,
     };
 
@@ -245,11 +206,11 @@ mod test {
         let eth_read = Arc::new(MockEntropyReader::with_requests(10, &[]));
 
         let eth_state = BlockchainState {
-            id:                     "ethereum".into(),
-            state:                  ETH_CHAIN.clone(),
-            contract:               eth_read.clone(),
-            provider_address:       PROVIDER,
-            reveal_delay_blocks:    1,
+            id: "ethereum".into(),
+            state: ETH_CHAIN.clone(),
+            contract: eth_read.clone(),
+            provider_address: PROVIDER,
+            reveal_delay_blocks: 1,
             confirmed_block_status: BlockStatus::Latest,
         };
 
@@ -258,11 +219,11 @@ mod test {
         let avax_read = Arc::new(MockEntropyReader::with_requests(10, &[]));
 
         let avax_state = BlockchainState {
-            id:                     "avalanche".into(),
-            state:                  AVAX_CHAIN.clone(),
-            contract:               avax_read.clone(),
-            provider_address:       PROVIDER,
-            reveal_delay_blocks:    2,
+            id: "avalanche".into(),
+            state: AVAX_CHAIN.clone(),
+            contract: avax_read.clone(),
+            provider_address: PROVIDER,
+            reveal_delay_blocks: 2,
             confirmed_block_status: BlockStatus::Latest,
         };
 

+ 2 - 8
apps/fortuna/src/api/chain_ids.rs

@@ -1,13 +1,7 @@
 use {
-    crate::api::{
-        ChainId,
-        RestError,
-    },
+    crate::api::{ChainId, RestError},
     anyhow::Result,
-    axum::{
-        extract::State,
-        Json,
-    },
+    axum::{extract::State, Json},
 };
 
 /// Get the list of supported chain ids

+ 1 - 4
apps/fortuna/src/api/index.rs

@@ -1,7 +1,4 @@
-use axum::{
-    response::IntoResponse,
-    Json,
-};
+use axum::{response::IntoResponse, Json};
 
 /// This is the index page for the REST service. It lists all the available endpoints.
 ///

+ 1 - 4
apps/fortuna/src/api/live.rs

@@ -1,9 +1,6 @@
 use axum::{
     http::StatusCode,
-    response::{
-        IntoResponse,
-        Response,
-    },
+    response::{IntoResponse, Response},
 };
 
 pub async fn live() -> Response {

+ 1 - 4
apps/fortuna/src/api/metrics.rs

@@ -1,10 +1,7 @@
 //! Exposing prometheus metrics via HTTP in openmetrics format.
 
 use {
-    axum::{
-        extract::State,
-        response::IntoResponse,
-    },
+    axum::{extract::State, response::IntoResponse},
     prometheus_client::encoding::text::encode,
 };
 

+ 1 - 4
apps/fortuna/src/api/ready.rs

@@ -1,9 +1,6 @@
 use axum::{
     http::StatusCode,
-    response::{
-        IntoResponse,
-        Response,
-    },
+    response::{IntoResponse, Response},
 };
 
 pub async fn ready() -> Response {

+ 3 - 14
apps/fortuna/src/api/revelation.rs

@@ -1,25 +1,14 @@
 use {
-    crate::api::{
-        ChainId,
-        RequestLabel,
-        RestError,
-    },
+    crate::api::{ChainId, RequestLabel, RestError},
     anyhow::Result,
     axum::{
-        extract::{
-            Path,
-            Query,
-            State,
-        },
+        extract::{Path, Query, State},
         Json,
     },
     pythnet_sdk::wire::array,
     serde_with::serde_as,
     tokio::try_join,
-    utoipa::{
-        IntoParams,
-        ToSchema,
-    },
+    utoipa::{IntoParams, ToSchema},
 };
 
 /// Reveal the random value for a given sequence number and blockchain.

+ 2 - 10
apps/fortuna/src/chain/eth_gas_oracle.rs

@@ -2,17 +2,11 @@ use {
     axum::async_trait,
     ethers::{
         prelude::{
-            gas_oracle::{
-                GasOracleError,
-                Result,
-            },
+            gas_oracle::{GasOracleError, Result},
             GasOracle,
         },
         providers::Middleware,
-        types::{
-            I256,
-            U256,
-        },
+        types::{I256, U256},
     },
 };
 
@@ -35,12 +29,10 @@ pub const SURGE_THRESHOLD_1: u64 = 40_000;
 pub const SURGE_THRESHOLD_2: u64 = 100_000;
 pub const SURGE_THRESHOLD_3: u64 = 200_000;
 
-
 /// The threshold max change/difference (in %) at which we will ignore the fee history values
 /// under it.
 pub const EIP1559_FEE_ESTIMATION_THRESHOLD_MAX_CHANGE: i64 = 200;
 
-
 /// Gas oracle from a [`Middleware`] implementation such as an
 /// Ethereum RPC provider.
 #[derive(Clone, Debug)]

+ 16 - 56
apps/fortuna/src/chain/ethereum.rs

@@ -4,64 +4,24 @@ use {
         chain::{
             eth_gas_oracle::EthProviderOracle,
             nonce_manager::NonceManagerMiddleware,
-            reader::{
-                self,
-                BlockNumber,
-                BlockStatus,
-                EntropyReader,
-                RequestedWithCallbackEvent,
-            },
-            traced_client::{
-                RpcMetrics,
-                TracedClient,
-            },
+            reader::{self, BlockNumber, BlockStatus, EntropyReader, RequestedWithCallbackEvent},
+            traced_client::{RpcMetrics, TracedClient},
         },
         config::EthereumConfig,
     },
-    anyhow::{
-        anyhow,
-        Error,
-        Result,
-    },
+    anyhow::{anyhow, Error, Result},
     axum::async_trait,
     ethers::{
         abi::RawLog,
-        contract::{
-            abigen,
-            ContractCall,
-            EthLogDecode,
-        },
+        contract::{abigen, ContractCall, EthLogDecode},
         core::types::Address,
-        middleware::{
-            gas_oracle::GasOracleMiddleware,
-            MiddlewareError,
-            SignerMiddleware,
-        },
-        prelude::{
-            BlockId,
-            JsonRpcClient,
-            PendingTransaction,
-            TransactionRequest,
-        },
-        providers::{
-            Http,
-            Middleware,
-            Provider,
-        },
-        signers::{
-            LocalWallet,
-            Signer,
-        },
-        types::{
-            transaction::eip2718::TypedTransaction,
-            BlockNumber as EthersBlockNumber,
-            U256,
-        },
-    },
-    sha3::{
-        Digest,
-        Keccak256,
+        middleware::{gas_oracle::GasOracleMiddleware, MiddlewareError, SignerMiddleware},
+        prelude::{BlockId, JsonRpcClient, PendingTransaction, TransactionRequest},
+        providers::{Http, Middleware, Provider},
+        signers::{LocalWallet, Signer},
+        types::{transaction::eip2718::TypedTransaction, BlockNumber as EthersBlockNumber, U256},
     },
+    sha3::{Digest, Keccak256},
     std::sync::Arc,
     thiserror::Error,
 };
@@ -94,7 +54,7 @@ pub type InstrumentedPythContract = PythRandom<Provider<TracedClient>>;
 #[derive(Clone, Debug)]
 pub struct LegacyTxMiddleware<M> {
     use_legacy_tx: bool,
-    inner:         M,
+    inner: M,
 }
 
 impl<M> LegacyTxMiddleware<M> {
@@ -333,10 +293,10 @@ impl<T: JsonRpcClient + 'static> EntropyReader for PythRandom<Provider<T>> {
         // sequence_number == 0 means the request does not exist.
         if r.sequence_number != 0 {
             Ok(Some(reader::Request {
-                provider:        r.provider,
+                provider: r.provider,
                 sequence_number: r.sequence_number,
-                block_number:    r.block_number.try_into()?,
-                use_blockhash:   r.use_blockhash,
+                block_number: r.block_number.try_into()?,
+                use_blockhash: r.use_blockhash,
             }))
         } else {
             Ok(None)
@@ -370,9 +330,9 @@ impl<T: JsonRpcClient + 'static> EntropyReader for PythRandom<Provider<T>> {
         Ok(res
             .iter()
             .map(|r| RequestedWithCallbackEvent {
-                sequence_number:    r.sequence_number,
+                sequence_number: r.sequence_number,
                 user_random_number: r.user_random_number,
-                provider_address:   r.request.provider,
+                provider_address: r.request.provider,
             })
             .collect())
     }

+ 7 - 18
apps/fortuna/src/chain/nonce_manager.rs

@@ -4,21 +4,10 @@
 use {
     axum::async_trait,
     ethers::{
-        providers::{
-            Middleware,
-            MiddlewareError,
-            PendingTransaction,
-        },
-        types::{
-            transaction::eip2718::TypedTransaction,
-            *,
-        },
-    },
-    std::sync::atomic::{
-        AtomicBool,
-        AtomicU64,
-        Ordering,
+        providers::{Middleware, MiddlewareError, PendingTransaction},
+        types::{transaction::eip2718::TypedTransaction, *},
     },
+    std::sync::atomic::{AtomicBool, AtomicU64, Ordering},
     thiserror::Error,
 };
 
@@ -26,11 +15,11 @@ use {
 /// Middleware used for calculating nonces locally, useful for signing multiple
 /// consecutive transactions without waiting for them to hit the mempool
 pub struct NonceManagerMiddleware<M> {
-    inner:       M,
-    init_guard:  futures_locks::Mutex<()>,
+    inner: M,
+    init_guard: futures_locks::Mutex<()>,
     initialized: AtomicBool,
-    nonce:       AtomicU64,
-    address:     Address,
+    nonce: AtomicU64,
+    address: Address,
 }
 
 impl<M> NonceManagerMiddleware<M>

+ 13 - 26
apps/fortuna/src/chain/reader.rs

@@ -1,11 +1,7 @@
 use {
     anyhow::Result,
     axum::async_trait,
-    ethers::types::{
-        Address,
-        BlockNumber as EthersBlockNumber,
-        U256,
-    },
+    ethers::types::{Address, BlockNumber as EthersBlockNumber, U256},
 };
 
 pub type BlockNumber = u64;
@@ -35,9 +31,9 @@ impl From<BlockStatus> for EthersBlockNumber {
 
 #[derive(Clone)]
 pub struct RequestedWithCallbackEvent {
-    pub sequence_number:    u64,
+    pub sequence_number: u64,
     pub user_random_number: [u8; 32],
-    pub provider_address:   Address,
+    pub provider_address: Address,
 }
 
 /// EntropyReader is the read-only interface of the Entropy contract.
@@ -73,29 +69,20 @@ pub trait EntropyReader: Send + Sync {
 /// aren't used in fortuna anywhere. Feel free to add any missing fields as necessary.)
 #[derive(Clone, Debug)]
 pub struct Request {
-    pub provider:        Address,
+    pub provider: Address,
     pub sequence_number: u64,
     // The block number where this request was created
-    pub block_number:    BlockNumber,
-    pub use_blockhash:   bool,
+    pub block_number: BlockNumber,
+    pub use_blockhash: bool,
 }
 
-
 #[cfg(test)]
 pub mod mock {
     use {
-        crate::chain::reader::{
-            BlockNumber,
-            BlockStatus,
-            EntropyReader,
-            Request,
-        },
+        crate::chain::reader::{BlockNumber, BlockStatus, EntropyReader, Request},
         anyhow::Result,
         axum::async_trait,
-        ethers::types::{
-            Address,
-            U256,
-        },
+        ethers::types::{Address, U256},
         std::sync::RwLock,
     };
 
@@ -105,7 +92,7 @@ pub mod mock {
     pub struct MockEntropyReader {
         block_number: RwLock<BlockNumber>,
         /// The set of requests that are currently in-flight.
-        requests:     RwLock<Vec<Request>>,
+        requests: RwLock<Vec<Request>>,
     }
 
     impl MockEntropyReader {
@@ -115,14 +102,14 @@ pub mod mock {
         ) -> MockEntropyReader {
             MockEntropyReader {
                 block_number: RwLock::new(block_number),
-                requests:     RwLock::new(
+                requests: RwLock::new(
                     requests
                         .iter()
                         .map(|&(a, s, b, u)| Request {
-                            provider:        a,
+                            provider: a,
                             sequence_number: s,
-                            block_number:    b,
-                            use_blockhash:   u,
+                            block_number: b,
+                            use_blockhash: u,
                         })
                         .collect(),
                 ),

+ 9 - 23
apps/fortuna/src/chain/traced_client.rs

@@ -4,41 +4,27 @@ use {
     axum::async_trait,
     ethers::{
         prelude::Http,
-        providers::{
-            HttpClientError,
-            JsonRpcClient,
-            Provider,
-        },
+        providers::{HttpClientError, JsonRpcClient, Provider},
     },
     prometheus_client::{
         encoding::EncodeLabelSet,
-        metrics::{
-            counter::Counter,
-            family::Family,
-            histogram::Histogram,
-        },
+        metrics::{counter::Counter, family::Family, histogram::Histogram},
         registry::Registry,
     },
-    std::{
-        str::FromStr,
-        sync::Arc,
-    },
-    tokio::{
-        sync::RwLock,
-        time::Instant,
-    },
+    std::{str::FromStr, sync::Arc},
+    tokio::{sync::RwLock, time::Instant},
 };
 
 #[derive(Debug, Clone, PartialEq, Eq, Hash, EncodeLabelSet)]
 pub struct RpcLabel {
     chain_id: ChainId,
-    method:   String,
+    method: String,
 }
 
 #[derive(Debug)]
 pub struct RpcMetrics {
-    count:        Family<RpcLabel, Counter>,
-    latency:      Family<RpcLabel, Histogram>,
+    count: Family<RpcLabel, Counter>,
+    latency: Family<RpcLabel, Histogram>,
     errors_count: Family<RpcLabel, Counter>,
 }
 
@@ -87,7 +73,7 @@ pub struct TracedClient {
     inner: Http,
 
     chain_id: ChainId,
-    metrics:  Arc<RpcMetrics>,
+    metrics: Arc<RpcMetrics>,
 }
 
 #[async_trait]
@@ -105,7 +91,7 @@ impl JsonRpcClient for TracedClient {
         let start = Instant::now();
         let label = &RpcLabel {
             chain_id: self.chain_id.clone(),
-            method:   method.to_string(),
+            method: method.to_string(),
         };
         self.metrics.count.get_or_create(label).inc();
         let res = match self.inner.request(method, params).await {

+ 3 - 8
apps/fortuna/src/command.rs

@@ -8,12 +8,7 @@ mod setup_provider;
 mod withdraw_fees;
 
 pub use {
-    generate::generate,
-    get_request::get_request,
-    inspect::inspect,
-    register_provider::register_provider,
-    request_randomness::request_randomness,
-    run::run,
-    setup_provider::setup_provider,
-    withdraw_fees::withdraw_fees,
+    generate::generate, get_request::get_request, inspect::inspect,
+    register_provider::register_provider, request_randomness::request_randomness, run::run,
+    setup_provider::setup_provider, withdraw_fees::withdraw_fees,
 };

+ 2 - 8
apps/fortuna/src/command/generate.rs

@@ -2,16 +2,10 @@ use {
     crate::{
         api::GetRandomValueResponse,
         chain::ethereum::SignablePythContract,
-        config::{
-            Config,
-            GenerateOptions,
-        },
+        config::{Config, GenerateOptions},
     },
     anyhow::Result,
-    base64::{
-        engine::general_purpose::STANDARD as base64_standard_engine,
-        Engine as _,
-    },
+    base64::{engine::general_purpose::STANDARD as base64_standard_engine, Engine as _},
     std::sync::Arc,
 };
 

+ 1 - 4
apps/fortuna/src/command/get_request.rs

@@ -1,10 +1,7 @@
 use {
     crate::{
         chain::ethereum::PythContract,
-        config::{
-            Config,
-            GetRequestOptions,
-        },
+        config::{Config, GetRequestOptions},
     },
     anyhow::Result,
     std::sync::Arc,

+ 3 - 13
apps/fortuna/src/command/inspect.rs

@@ -1,23 +1,13 @@
 use {
     crate::{
-        chain::ethereum::{
-            PythContract,
-            Request,
-        },
-        config::{
-            Config,
-            EthereumConfig,
-            InspectOptions,
-        },
+        chain::ethereum::{PythContract, Request},
+        config::{Config, EthereumConfig, InspectOptions},
     },
     anyhow::Result,
     ethers::{
         contract::Multicall,
         middleware::Middleware,
-        prelude::{
-            Http,
-            Provider,
-        },
+        prelude::{Http, Provider},
     },
 };
 

+ 6 - 20
apps/fortuna/src/command/register_provider.rs

@@ -1,28 +1,14 @@
 use {
     crate::{
-        api::{
-            get_register_uri,
-            ChainId,
-        },
+        api::{get_register_uri, ChainId},
         chain::ethereum::SignablePythContract,
-        config::{
-            Config,
-            EthereumConfig,
-            ProviderConfig,
-            RegisterProviderOptions,
-        },
+        config::{Config, EthereumConfig, ProviderConfig, RegisterProviderOptions},
         state::PebbleHashChain,
     },
-    anyhow::{
-        anyhow,
-        Result,
-    },
+    anyhow::{anyhow, Result},
     ethers::{
         abi::Bytes,
-        signers::{
-            LocalWallet,
-            Signer,
-        },
+        signers::{LocalWallet, Signer},
         types::U256,
     },
     std::sync::Arc,
@@ -30,7 +16,7 @@ use {
 
 #[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
 pub struct CommitmentMetadata {
-    pub seed:         [u8; 32],
+    pub seed: [u8; 32],
     pub chain_length: u64,
 }
 
@@ -83,7 +69,7 @@ pub async fn register_provider_from_config(
     // Store the random seed and chain length in the metadata field so that we can regenerate the hash
     // chain at-will. (This is secure because you can't generate the chain unless you also have the secret)
     let commitment_metadata = CommitmentMetadata {
-        seed:         random,
+        seed: random,
         chain_length: commitment_length,
     };
     let uri = get_register_uri(&provider_config.uri, chain_id)?;

+ 1 - 4
apps/fortuna/src/command/request_randomness.rs

@@ -1,10 +1,7 @@
 use {
     crate::{
         chain::ethereum::SignablePythContract,
-        config::{
-            Config,
-            RequestRandomnessOptions,
-        },
+        config::{Config, RequestRandomnessOptions},
     },
     anyhow::Result,
     std::sync::Arc,

+ 12 - 52
apps/fortuna/src/command/run.rs

@@ -1,71 +1,36 @@
 use {
     crate::{
-        api::{
-            self,
-            BlockchainState,
-            ChainId,
-        },
+        api::{self, BlockchainState, ChainId},
         chain::{
             ethereum::InstrumentedPythContract,
-            traced_client::{
-                RpcMetrics,
-                TracedClient,
-            },
+            traced_client::{RpcMetrics, TracedClient},
         },
         command::register_provider::CommitmentMetadata,
-        config::{
-            Commitment,
-            Config,
-            EthereumConfig,
-            RunOptions,
-        },
-        keeper::{
-            self,
-            KeeperMetrics,
-        },
-        state::{
-            HashChainState,
-            PebbleHashChain,
-        },
-    },
-    anyhow::{
-        anyhow,
-        Error,
-        Result,
+        config::{Commitment, Config, EthereumConfig, RunOptions},
+        keeper::{self, KeeperMetrics},
+        state::{HashChainState, PebbleHashChain},
     },
+    anyhow::{anyhow, Error, Result},
     axum::Router,
     ethers::{
         middleware::Middleware,
-        types::{
-            Address,
-            BlockNumber,
-        },
+        types::{Address, BlockNumber},
     },
     futures::future::join_all,
     prometheus_client::{
         encoding::EncodeLabelSet,
-        metrics::{
-            family::Family,
-            gauge::Gauge,
-        },
+        metrics::{family::Family, gauge::Gauge},
         registry::Registry,
     },
     std::{
         collections::HashMap,
         net::SocketAddr,
         sync::Arc,
-        time::{
-            Duration,
-            SystemTime,
-            UNIX_EPOCH,
-        },
+        time::{Duration, SystemTime, UNIX_EPOCH},
     },
     tokio::{
         spawn,
-        sync::{
-            watch,
-            RwLock,
-        },
+        sync::{watch, RwLock},
         time,
     },
     tower_http::cors::CorsLayer,
@@ -130,7 +95,6 @@ pub async fn run_api(
     Ok(())
 }
 
-
 pub async fn run_keeper(
     chains: HashMap<String, api::BlockchainState>,
     config: Config,
@@ -205,7 +169,6 @@ pub async fn run(opts: &RunOptions) -> Result<()> {
         return Err(anyhow!("No chains were successfully setup"));
     }
 
-
     // Listen for Ctrl+C so we can set the exit flag and wait for a graceful shutdown.
     spawn(async move {
         tracing::info!("Registered shutdown signal handler...");
@@ -284,8 +247,8 @@ async fn setup_chain_state(
     }
 
     provider_commitments.push(Commitment {
-        seed:                                latest_metadata.seed,
-        chain_length:                        latest_metadata.chain_length,
+        seed: latest_metadata.seed,
+        chain_length: latest_metadata.chain_length,
         original_commitment_sequence_number: provider_info.original_commitment_sequence_number,
     });
 
@@ -337,13 +300,11 @@ async fn setup_chain_state(
     Ok(state)
 }
 
-
 #[derive(Clone, Debug, Hash, PartialEq, Eq, EncodeLabelSet)]
 pub struct ChainLabel {
     pub chain_id: String,
 }
 
-
 #[tracing::instrument(name = "block_timestamp_lag", skip_all, fields(chain_id = chain_id))]
 pub async fn check_block_timestamp_lag(
     chain_id: String,
@@ -360,7 +321,6 @@ pub async fn check_block_timestamp_lag(
             }
         };
 
-
     const INF_LAG: i64 = 1000000; // value that definitely triggers an alert
     let lag = match provider.get_block(BlockNumber::Latest).await {
         Ok(block) => match block {

+ 9 - 38
apps/fortuna/src/command/setup_provider.rs

@@ -1,41 +1,16 @@
 use {
     crate::{
-        api::{
-            get_register_uri,
-            ChainId,
-        },
-        chain::ethereum::{
-            ProviderInfo,
-            SignablePythContract,
-        },
-        command::register_provider::{
-            register_provider_from_config,
-            CommitmentMetadata,
-        },
-        config::{
-            Config,
-            EthereumConfig,
-            SetupProviderOptions,
-        },
-        state::{
-            HashChainState,
-            PebbleHashChain,
-        },
-    },
-    anyhow::{
-        anyhow,
-        Result,
+        api::{get_register_uri, ChainId},
+        chain::ethereum::{ProviderInfo, SignablePythContract},
+        command::register_provider::{register_provider_from_config, CommitmentMetadata},
+        config::{Config, EthereumConfig, SetupProviderOptions},
+        state::{HashChainState, PebbleHashChain},
     },
+    anyhow::{anyhow, Result},
     ethers::{
         abi::Bytes as AbiBytes,
-        signers::{
-            LocalWallet,
-            Signer,
-        },
-        types::{
-            Address,
-            Bytes,
-        },
+        signers::{LocalWallet, Signer},
+        types::{Address, Bytes},
     },
     futures::future::join_all,
     std::sync::Arc,
@@ -79,7 +54,6 @@ pub async fn setup_provider(opts: &SetupProviderOptions) -> Result<()> {
     }
 }
 
-
 /// Setup provider for a single chain.
 /// 1. Register if there was no previous registration.
 /// 2. Re-register if there are no more random numbers to request on the contract.
@@ -148,13 +122,12 @@ async fn setup_chain_provider(
                 provider_config.chain_sample_interval,
             )?;
             let chain_state = HashChainState {
-                offsets:     vec![provider_info
+                offsets: vec![provider_info
                     .original_commitment_sequence_number
                     .try_into()?],
                 hash_chains: vec![hash_chain],
             };
 
-
             if chain_state.reveal(provider_info.original_commitment_sequence_number)?
                 != provider_info.original_commitment
             {
@@ -173,7 +146,6 @@ async fn setup_chain_provider(
         tracing::info!("Registered");
     }
 
-
     let provider_info = contract.get_provider_info(provider_address).call().await?;
 
     sync_fee(&contract, &provider_info, chain_config.fee)
@@ -257,7 +229,6 @@ async fn sync_fee_manager(
     Ok(())
 }
 
-
 async fn sync_max_num_hashes(
     contract: &Arc<SignablePythContract>,
     provider_info: &ProviderInfo,

+ 3 - 13
apps/fortuna/src/command/withdraw_fees.rs

@@ -1,22 +1,12 @@
 use {
     crate::{
         chain::ethereum::SignablePythContract,
-        config::{
-            Config,
-            WithdrawFeesOptions,
-        },
-    },
-    anyhow::{
-        anyhow,
-        Result,
-    },
-    ethers::{
-        signers::Signer,
-        types::Address,
+        config::{Config, WithdrawFeesOptions},
     },
+    anyhow::{anyhow, Result},
+    ethers::{signers::Signer, types::Address},
 };
 
-
 pub async fn withdraw_fees(opts: &WithdrawFeesOptions) -> Result<()> {
     let config = Config::load(&opts.config.config)?;
 

+ 11 - 33
apps/fortuna/src/config.rs

@@ -1,38 +1,17 @@
 use {
     crate::{
         api::ChainId,
-        chain::reader::{
-            BlockNumber,
-            BlockStatus,
-        },
-    },
-    anyhow::{
-        anyhow,
-        Result,
-    },
-    clap::{
-        crate_authors,
-        crate_description,
-        crate_name,
-        crate_version,
-        Args,
-        Parser,
+        chain::reader::{BlockNumber, BlockStatus},
     },
+    anyhow::{anyhow, Result},
+    clap::{crate_authors, crate_description, crate_name, crate_version, Args, Parser},
     ethers::types::Address,
-    std::{
-        collections::HashMap,
-        fs,
-    },
+    std::{collections::HashMap, fs},
 };
 pub use {
-    generate::GenerateOptions,
-    get_request::GetRequestOptions,
-    inspect::InspectOptions,
-    register_provider::RegisterProviderOptions,
-    request_randomness::RequestRandomnessOptions,
-    run::RunOptions,
-    setup_provider::SetupProviderOptions,
-    withdraw_fees::WithdrawFeesOptions,
+    generate::GenerateOptions, get_request::GetRequestOptions, inspect::InspectOptions,
+    register_provider::RegisterProviderOptions, request_randomness::RequestRandomnessOptions,
+    run::RunOptions, setup_provider::SetupProviderOptions, withdraw_fees::WithdrawFeesOptions,
 };
 
 mod generate;
@@ -93,9 +72,9 @@ pub struct ConfigOptions {
 
 #[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
 pub struct Config {
-    pub chains:   HashMap<ChainId, EthereumConfig>,
+    pub chains: HashMap<ChainId, EthereumConfig>,
     pub provider: ProviderConfig,
-    pub keeper:   KeeperConfig,
+    pub keeper: KeeperConfig,
 }
 
 impl Config {
@@ -189,15 +168,14 @@ pub struct EthereumConfig {
     pub max_num_hashes: Option<u32>,
 }
 
-
 /// A commitment that the provider used to generate random numbers at some point in the past.
 /// These historical commitments need to be stored in the configuration to support transition points where
 /// the commitment changes. In theory, this information is stored on the blockchain, but unfortunately it
 /// is hard to retrieve from there.
 #[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
 pub struct Commitment {
-    pub seed:                                [u8; 32],
-    pub chain_length:                        u64,
+    pub seed: [u8; 32],
+    pub chain_length: u64,
     pub original_commitment_sequence_number: u64,
 }
 

+ 1 - 4
apps/fortuna/src/config/generate.rs

@@ -1,8 +1,5 @@
 use {
-    crate::{
-        api::ChainId,
-        config::ConfigOptions,
-    },
+    crate::{api::ChainId, config::ConfigOptions},
     clap::Args,
     ethers::types::Address,
     reqwest::Url,

+ 1 - 4
apps/fortuna/src/config/get_request.rs

@@ -1,8 +1,5 @@
 use {
-    crate::{
-        api::ChainId,
-        config::ConfigOptions,
-    },
+    crate::{api::ChainId, config::ConfigOptions},
     clap::Args,
     ethers::types::Address,
 };

+ 1 - 5
apps/fortuna/src/config/inspect.rs

@@ -1,12 +1,8 @@
 use {
-    crate::{
-        api::ChainId,
-        config::ConfigOptions,
-    },
+    crate::{api::ChainId, config::ConfigOptions},
     clap::Args,
 };
 
-
 #[derive(Args, Clone, Debug)]
 #[command(next_help_heading = "Inspect Options")]
 #[group(id = "Inspect")]

+ 1 - 4
apps/fortuna/src/config/register_provider.rs

@@ -1,8 +1,5 @@
 use {
-    crate::{
-        api::ChainId,
-        config::ConfigOptions,
-    },
+    crate::{api::ChainId, config::ConfigOptions},
     clap::Args,
 };
 

+ 1 - 4
apps/fortuna/src/config/request_randomness.rs

@@ -1,8 +1,5 @@
 use {
-    crate::{
-        api::ChainId,
-        config::ConfigOptions,
-    },
+    crate::{api::ChainId, config::ConfigOptions},
     clap::Args,
     ethers::types::Address,
 };

+ 1 - 5
apps/fortuna/src/config/run.rs

@@ -1,8 +1,4 @@
-use {
-    crate::config::ConfigOptions,
-    clap::Args,
-    std::net::SocketAddr,
-};
+use {crate::config::ConfigOptions, clap::Args, std::net::SocketAddr};
 
 /// Run the webservice
 #[derive(Args, Clone, Debug)]

+ 1 - 4
apps/fortuna/src/config/setup_provider.rs

@@ -1,7 +1,4 @@
-use {
-    crate::config::ConfigOptions,
-    clap::Args,
-};
+use {crate::config::ConfigOptions, clap::Args};
 
 #[derive(Args, Clone, Debug)]
 #[command(next_help_heading = "Setup Provider Options")]

+ 1 - 4
apps/fortuna/src/config/withdraw_fees.rs

@@ -1,8 +1,5 @@
 use {
-    crate::{
-        api::ChainId,
-        config::ConfigOptions,
-    },
+    crate::{api::ChainId, config::ConfigOptions},
     clap::Args,
 };
 

+ 34 - 81
apps/fortuna/src/keeper.rs

@@ -1,78 +1,39 @@
 use {
     crate::{
-        api::{
-            self,
-            BlockchainState,
-            ChainId,
-        },
+        api::{self, BlockchainState, ChainId},
         chain::{
             eth_gas_oracle::eip1559_default_estimator,
             ethereum::{
-                InstrumentedPythContract,
-                InstrumentedSignablePythContract,
-                PythContractCall,
-            },
-            reader::{
-                BlockNumber,
-                RequestedWithCallbackEvent,
-            },
-            traced_client::{
-                RpcMetrics,
-                TracedClient,
+                InstrumentedPythContract, InstrumentedSignablePythContract, PythContractCall,
             },
+            reader::{BlockNumber, RequestedWithCallbackEvent},
+            traced_client::{RpcMetrics, TracedClient},
         },
         config::EthereumConfig,
     },
-    anyhow::{
-        anyhow,
-        Result,
-    },
+    anyhow::{anyhow, Result},
     backoff::ExponentialBackoff,
     ethers::{
-        providers::{
-            Middleware,
-            Provider,
-            Ws,
-        },
+        providers::{Middleware, Provider, Ws},
         signers::Signer,
-        types::{
-            Address,
-            U256,
-        },
+        types::{Address, U256},
     },
     futures::StreamExt,
     prometheus_client::{
         encoding::EncodeLabelSet,
-        metrics::{
-            counter::Counter,
-            family::Family,
-            gauge::Gauge,
-        },
+        metrics::{counter::Counter, family::Family, gauge::Gauge},
         registry::Registry,
     },
     std::{
         collections::HashSet,
-        sync::{
-            atomic::AtomicU64,
-            Arc,
-        },
+        sync::{atomic::AtomicU64, Arc},
     },
     tokio::{
         spawn,
-        sync::{
-            mpsc,
-            RwLock,
-        },
-        time::{
-            self,
-            timeout,
-            Duration,
-        },
-    },
-    tracing::{
-        self,
-        Instrument,
+        sync::{mpsc, RwLock},
+        time::{self, timeout, Duration},
     },
+    tracing::{self, Instrument},
 };
 
 /// How much to wait before retrying in case of an RPC error
@@ -99,21 +60,21 @@ const RETRY_PREVIOUS_BLOCKS: u64 = 100;
 #[derive(Clone, Debug, Hash, PartialEq, Eq, EncodeLabelSet)]
 pub struct AccountLabel {
     pub chain_id: String,
-    pub address:  String,
+    pub address: String,
 }
 
 #[derive(Default)]
 pub struct KeeperMetrics {
     pub current_sequence_number: Family<AccountLabel, Gauge>,
-    pub end_sequence_number:     Family<AccountLabel, Gauge>,
-    pub balance:                 Family<AccountLabel, Gauge<f64, AtomicU64>>,
-    pub collected_fee:           Family<AccountLabel, Gauge<f64, AtomicU64>>,
-    pub current_fee:             Family<AccountLabel, Gauge<f64, AtomicU64>>,
-    pub total_gas_spent:         Family<AccountLabel, Gauge<f64, AtomicU64>>,
-    pub requests:                Family<AccountLabel, Counter>,
-    pub requests_processed:      Family<AccountLabel, Counter>,
-    pub requests_reprocessed:    Family<AccountLabel, Counter>,
-    pub reveals:                 Family<AccountLabel, Counter>,
+    pub end_sequence_number: Family<AccountLabel, Gauge>,
+    pub balance: Family<AccountLabel, Gauge<f64, AtomicU64>>,
+    pub collected_fee: Family<AccountLabel, Gauge<f64, AtomicU64>>,
+    pub current_fee: Family<AccountLabel, Gauge<f64, AtomicU64>>,
+    pub total_gas_spent: Family<AccountLabel, Gauge<f64, AtomicU64>>,
+    pub requests: Family<AccountLabel, Counter>,
+    pub requests_processed: Family<AccountLabel, Counter>,
+    pub requests_reprocessed: Family<AccountLabel, Counter>,
+    pub reveals: Family<AccountLabel, Counter>,
 }
 
 impl KeeperMetrics {
@@ -188,7 +149,7 @@ impl KeeperMetrics {
 #[derive(Debug)]
 pub struct BlockRange {
     pub from: BlockNumber,
-    pub to:   BlockNumber,
+    pub to: BlockNumber,
 }
 
 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
@@ -258,7 +219,7 @@ pub async fn run_keeper_threads(
         process_backlog(
             BlockRange {
                 from: latest_safe_block.saturating_sub(BACKLOG_RANGE),
-                to:   latest_safe_block,
+                to: latest_safe_block,
             },
             contract.clone(),
             gas_limit,
@@ -322,7 +283,6 @@ pub async fn run_keeper_threads(
 
     spawn(update_commitments_loop(contract.clone(), chain_state.clone()).in_current_span());
 
-
     // Spawn a thread to track the provider info and the balance of the keeper
     spawn(
         async move {
@@ -372,7 +332,6 @@ pub async fn run_keeper_threads(
     );
 }
 
-
 /// Process an event with backoff. It will retry the reveal on failure for 5 minutes.
 #[tracing::instrument(name = "process_event_with_backoff", skip_all, fields(
     sequence_number = event.sequence_number
@@ -388,7 +347,7 @@ pub async fn process_event_with_backoff(
         .requests
         .get_or_create(&AccountLabel {
             chain_id: chain_state.id.clone(),
-            address:  chain_state.provider_address.to_string(),
+            address: chain_state.provider_address.to_string(),
         })
         .inc();
     tracing::info!("Started processing event");
@@ -416,12 +375,11 @@ pub async fn process_event_with_backoff(
         .requests_processed
         .get_or_create(&AccountLabel {
             chain_id: chain_state.id.clone(),
-            address:  chain_state.provider_address.to_string(),
+            address: chain_state.provider_address.to_string(),
         })
         .inc();
 }
 
-
 const TX_CONFIRMATION_TIMEOUT_SECS: u64 = 30;
 
 /// Process a callback on a chain. It estimates the gas for the reveal with callback and
@@ -463,7 +421,6 @@ pub async fn process_event(
         backoff::Error::transient(anyhow!("Error estimating gas for reveal: {:?}", e))
     })?;
 
-
     if gas_estimate > gas_limit {
         return Err(backoff::Error::permanent(anyhow!(
             "Gas estimate for reveal with callback is higher than the gas limit {} > {}",
@@ -557,7 +514,7 @@ pub async fn process_event(
             .total_gas_spent
             .get_or_create(&AccountLabel {
                 chain_id: chain_config.id.clone(),
-                address:  client
+                address: client
                     .inner()
                     .inner()
                     .inner()
@@ -572,14 +529,13 @@ pub async fn process_event(
         .reveals
         .get_or_create(&AccountLabel {
             chain_id: chain_config.id.clone(),
-            address:  chain_config.provider_address.to_string(),
+            address: chain_config.provider_address.to_string(),
         })
         .inc();
 
     Ok(())
 }
 
-
 /// Process a range of blocks in batches. It calls the `process_single_block_batch` method for each batch.
 #[tracing::instrument(skip_all, fields(
     range_from_block = block_range.from, range_to_block = block_range.to
@@ -607,7 +563,7 @@ pub async fn process_block_range(
         process_single_block_batch(
             BlockRange {
                 from: current_block,
-                to:   to_block,
+                to: to_block,
             },
             contract.clone(),
             gas_limit,
@@ -849,7 +805,6 @@ pub async fn process_backlog(
     tracing::info!("Backlog processed");
 }
 
-
 /// tracks the balance of the given address on the given chain
 /// if there was an error, the function will just return
 #[tracing::instrument(skip_all)]
@@ -876,7 +831,7 @@ pub async fn track_balance(
         .balance
         .get_or_create(&AccountLabel {
             chain_id: chain_id.clone(),
-            address:  address.to_string(),
+            address: address.to_string(),
         })
         .set(balance);
 }
@@ -910,7 +865,7 @@ pub async fn track_provider(
         .collected_fee
         .get_or_create(&AccountLabel {
             chain_id: chain_id.clone(),
-            address:  provider_address.to_string(),
+            address: provider_address.to_string(),
         })
         .set(collected_fee);
 
@@ -918,7 +873,7 @@ pub async fn track_provider(
         .current_fee
         .get_or_create(&AccountLabel {
             chain_id: chain_id.clone(),
-            address:  provider_address.to_string(),
+            address: provider_address.to_string(),
         })
         .set(current_fee);
 
@@ -926,7 +881,7 @@ pub async fn track_provider(
         .current_sequence_number
         .get_or_create(&AccountLabel {
             chain_id: chain_id.clone(),
-            address:  provider_address.to_string(),
+            address: provider_address.to_string(),
         })
         // sequence_number type on chain is u64 but practically it will take
         // a long time for it to cross the limits of i64.
@@ -936,7 +891,7 @@ pub async fn track_provider(
         .end_sequence_number
         .get_or_create(&AccountLabel {
             chain_id: chain_id.clone(),
-            address:  provider_address.to_string(),
+            address: provider_address.to_string(),
         })
         .set(end_sequence_number as i64);
 }
@@ -1082,7 +1037,6 @@ pub async fn update_commitments_loop(
     }
 }
 
-
 pub async fn update_commitments_if_necessary(
     contract: Arc<InstrumentedSignablePythContract>,
     chain_state: &BlockchainState,
@@ -1231,7 +1185,6 @@ pub async fn adjust_fee_if_necessary(
         }
     };
 
-
     Ok(())
 }
 

+ 1 - 5
apps/fortuna/src/main.rs

@@ -1,10 +1,6 @@
 #![allow(clippy::just_underscores_and_digits)]
 
-use {
-    anyhow::Result,
-    clap::Parser,
-    std::io::IsTerminal,
-};
+use {anyhow::Result, clap::Parser, std::io::IsTerminal};
 
 pub mod api;
 pub mod chain;

+ 7 - 17
apps/fortuna/src/state.rs

@@ -1,14 +1,8 @@
 use {
     crate::api::ChainId,
-    anyhow::{
-        ensure,
-        Result,
-    },
+    anyhow::{ensure, Result},
     ethers::types::Address,
-    sha3::{
-        Digest,
-        Keccak256,
-    },
+    sha3::{Digest, Keccak256},
 };
 
 /// A hash chain of a specific length. The hash chain has the property that
@@ -18,9 +12,9 @@ use {
 /// to keep the chain around.
 #[derive(Clone)]
 pub struct PebbleHashChain {
-    hash:            Vec<[u8; 32]>,
+    hash: Vec<[u8; 32]>,
     sample_interval: usize,
-    length:          usize,
+    length: usize,
 }
 
 impl PebbleHashChain {
@@ -48,7 +42,6 @@ impl PebbleHashChain {
         }
     }
 
-
     pub fn from_config(
         secret: &str,
         chain_id: &ChainId,
@@ -100,14 +93,14 @@ impl PebbleHashChain {
 /// which requires tracking multiple hash chains here.
 pub struct HashChainState {
     // The sequence number where the hash chain starts. Must be stored in sorted order.
-    pub offsets:     Vec<usize>,
+    pub offsets: Vec<usize>,
     pub hash_chains: Vec<PebbleHashChain>,
 }
 
 impl HashChainState {
     pub fn from_chain_at_offset(offset: usize, chain: PebbleHashChain) -> HashChainState {
         HashChainState {
-            offsets:     vec![offset],
+            offsets: vec![offset],
             hash_chains: vec![chain],
         }
     }
@@ -129,10 +122,7 @@ impl HashChainState {
 mod test {
     use {
         crate::state::PebbleHashChain,
-        sha3::{
-            Digest,
-            Keccak256,
-        },
+        sha3::{Digest, Keccak256},
     };
 
     fn run_hash_chain_test(secret: [u8; 32], length: usize, sample_interval: usize) {

+ 6 - 16
apps/hermes/server/src/api.rs

@@ -1,20 +1,10 @@
 use {
     crate::{
         config::RunOptions,
-        state::{
-            Aggregates,
-            Benchmarks,
-            Cache,
-            Metrics,
-        },
+        state::{Aggregates, Benchmarks, Cache, Metrics},
     },
     anyhow::Result,
-    axum::{
-        extract::Extension,
-        middleware::from_fn_with_state,
-        routing::get,
-        Router,
-    },
+    axum::{extract::Extension, middleware::from_fn_with_state, routing::get, Router},
     ipnet::IpNet,
     serde_qs::axum::QsQueryConfig,
     std::sync::Arc,
@@ -30,8 +20,8 @@ pub mod types;
 mod ws;
 
 pub struct ApiState<S> {
-    pub state:   Arc<S>,
-    pub ws:      Arc<ws::WsState>,
+    pub state: Arc<S>,
+    pub ws: Arc<ws::WsState>,
     pub metrics: Arc<metrics_middleware::ApiMetrics>,
 }
 
@@ -40,8 +30,8 @@ pub struct ApiState<S> {
 impl<S> Clone for ApiState<S> {
     fn clone(&self) -> Self {
         Self {
-            state:   self.state.clone(),
-            ws:      self.ws.clone(),
+            state: self.state.clone(),
+            ws: self.ws.clone(),
             metrics: self.metrics.clone(),
         }
     }

+ 5 - 12
apps/hermes/server/src/api/metrics_middleware.rs

@@ -2,28 +2,21 @@ use {
     super::ApiState,
     crate::state::metrics::Metrics,
     axum::{
-        extract::{
-            MatchedPath,
-            State,
-        },
+        extract::{MatchedPath, State},
         http::Request,
         middleware::Next,
         response::IntoResponse,
     },
     prometheus_client::{
         encoding::EncodeLabelSet,
-        metrics::{
-            counter::Counter,
-            family::Family,
-            histogram::Histogram,
-        },
+        metrics::{counter::Counter, family::Family, histogram::Histogram},
     },
     std::sync::Arc,
     tokio::time::Instant,
 };
 
 pub struct ApiMetrics {
-    pub requests:  Family<Labels, Counter>,
+    pub requests: Family<Labels, Counter>,
     pub latencies: Family<Labels, Histogram>,
 }
 
@@ -34,7 +27,7 @@ impl ApiMetrics {
         S: Send + Sync + 'static,
     {
         let new = Self {
-            requests:  Family::default(),
+            requests: Family::default(),
             latencies: Family::new_with_constructor(|| {
                 Histogram::new(
                     [
@@ -75,7 +68,7 @@ impl ApiMetrics {
 #[derive(Clone, Debug, PartialEq, Eq, Hash, EncodeLabelSet)]
 pub struct Labels {
     pub method: String,
-    pub path:   String,
+    pub path: String,
     pub status: u16,
 }
 

+ 5 - 19
apps/hermes/server/src/api/rest.rs

@@ -3,10 +3,7 @@ use {
     crate::state::aggregate::Aggregates,
     axum::{
         http::StatusCode,
-        response::{
-            IntoResponse,
-            Response,
-        },
+        response::{IntoResponse, Response},
     },
     pyth_sdk::PriceIdentifier,
 };
@@ -22,7 +19,6 @@ mod price_feed_ids;
 mod ready;
 mod v2;
 
-
 pub use {
     get_price_feed::*,
     get_vaa::*,
@@ -34,10 +30,7 @@ pub use {
     price_feed_ids::*,
     ready::*,
     v2::{
-        latest_price_updates::*,
-        latest_publisher_stake_caps::*,
-        price_feeds_metadata::*,
-        sse::*,
+        latest_price_updates::*, latest_publisher_stake_caps::*, price_feeds_metadata::*, sse::*,
         timestamp_price_updates::*,
     },
 };
@@ -131,12 +124,8 @@ mod tests {
         super::*,
         crate::state::{
             aggregate::{
-                AggregationEvent,
-                PriceFeedsWithUpdateData,
-                PublisherStakeCapsWithUpdateData,
-                ReadinessMetadata,
-                RequestTime,
-                Update,
+                AggregationEvent, PriceFeedsWithUpdateData, PublisherStakeCapsWithUpdateData,
+                ReadinessMetadata, RequestTime, Update,
             },
             benchmarks::BenchmarksState,
             cache::CacheState,
@@ -144,10 +133,7 @@ mod tests {
             price_feeds_metadata::PriceFeedMetaState,
         },
         anyhow::Result,
-        std::{
-            collections::HashSet,
-            sync::Arc,
-        },
+        std::{collections::HashSet, sync::Arc},
         tokio::sync::broadcast::Receiver,
     };
 

+ 3 - 13
apps/hermes/server/src/api/rest/get_price_feed.rs

@@ -4,23 +4,13 @@ use {
         api::{
             doc_examples,
             rest::RestError,
-            types::{
-                PriceIdInput,
-                RpcPriceFeed,
-            },
+            types::{PriceIdInput, RpcPriceFeed},
             ApiState,
         },
-        state::aggregate::{
-            Aggregates,
-            RequestTime,
-            UnixTimestamp,
-        },
+        state::aggregate::{Aggregates, RequestTime, UnixTimestamp},
     },
     anyhow::Result,
-    axum::{
-        extract::State,
-        Json,
-    },
+    axum::{extract::State, Json},
     pyth_sdk::PriceIdentifier,
     serde_qs::axum::QsQuery,
     utoipa::IntoParams,

+ 5 - 23
apps/hermes/server/src/api/rest/get_vaa.rs

@@ -1,33 +1,15 @@
 use {
     super::validate_price_ids,
     crate::{
-        api::{
-            doc_examples,
-            rest::RestError,
-            types::PriceIdInput,
-            ApiState,
-        },
-        state::aggregate::{
-            Aggregates,
-            RequestTime,
-            UnixTimestamp,
-        },
+        api::{doc_examples, rest::RestError, types::PriceIdInput, ApiState},
+        state::aggregate::{Aggregates, RequestTime, UnixTimestamp},
     },
     anyhow::Result,
-    axum::{
-        extract::State,
-        Json,
-    },
-    base64::{
-        engine::general_purpose::STANDARD as base64_standard_engine,
-        Engine as _,
-    },
+    axum::{extract::State, Json},
+    base64::{engine::general_purpose::STANDARD as base64_standard_engine, Engine as _},
     pyth_sdk::PriceIdentifier,
     serde_qs::axum::QsQuery,
-    utoipa::{
-        IntoParams,
-        ToSchema,
-    },
+    utoipa::{IntoParams, ToSchema},
 };
 
 #[derive(Debug, serde::Deserialize, IntoParams)]

+ 6 - 25
apps/hermes/server/src/api/rest/get_vaa_ccip.rs

@@ -1,35 +1,16 @@
 use {
     super::validate_price_ids,
     crate::{
-        api::{
-            rest::RestError,
-            ApiState,
-        },
-        state::aggregate::{
-            Aggregates,
-            RequestTime,
-            UnixTimestamp,
-        },
+        api::{rest::RestError, ApiState},
+        state::aggregate::{Aggregates, RequestTime, UnixTimestamp},
     },
     anyhow::Result,
-    axum::{
-        extract::State,
-        Json,
-    },
-    derive_more::{
-        Deref,
-        DerefMut,
-    },
+    axum::{extract::State, Json},
+    derive_more::{Deref, DerefMut},
     pyth_sdk::PriceIdentifier,
-    serde::{
-        Deserialize,
-        Serialize,
-    },
+    serde::{Deserialize, Serialize},
     serde_qs::axum::QsQuery,
-    utoipa::{
-        IntoParams,
-        ToSchema,
-    },
+    utoipa::{IntoParams, ToSchema},
 };
 
 #[derive(Clone, Debug, Deref, DerefMut, Deserialize, Serialize, ToSchema)]

+ 1 - 4
apps/hermes/server/src/api/rest/index.rs

@@ -1,7 +1,4 @@
-use axum::{
-    response::IntoResponse,
-    Json,
-};
+use axum::{response::IntoResponse, Json};
 
 /// This is the index page for the REST service. It lists all the available endpoints.
 ///

+ 3 - 12
apps/hermes/server/src/api/rest/latest_price_feeds.rs

@@ -3,22 +3,13 @@ use {
     crate::{
         api::{
             rest::RestError,
-            types::{
-                PriceIdInput,
-                RpcPriceFeed,
-            },
+            types::{PriceIdInput, RpcPriceFeed},
             ApiState,
         },
-        state::aggregate::{
-            Aggregates,
-            RequestTime,
-        },
+        state::aggregate::{Aggregates, RequestTime},
     },
     anyhow::Result,
-    axum::{
-        extract::State,
-        Json,
-    },
+    axum::{extract::State, Json},
     pyth_sdk::PriceIdentifier,
     serde_qs::axum::QsQuery,
     utoipa::IntoParams,

+ 4 - 19
apps/hermes/server/src/api/rest/latest_vaas.rs

@@ -1,26 +1,12 @@
 use {
     super::validate_price_ids,
     crate::{
-        api::{
-            doc_examples,
-            rest::RestError,
-            types::PriceIdInput,
-            ApiState,
-        },
-        state::aggregate::{
-            Aggregates,
-            RequestTime,
-        },
+        api::{doc_examples, rest::RestError, types::PriceIdInput, ApiState},
+        state::aggregate::{Aggregates, RequestTime},
     },
     anyhow::Result,
-    axum::{
-        extract::State,
-        Json,
-    },
-    base64::{
-        engine::general_purpose::STANDARD as base64_standard_engine,
-        Engine as _,
-    },
+    axum::{extract::State, Json},
+    base64::{engine::general_purpose::STANDARD as base64_standard_engine, Engine as _},
     pyth_sdk::PriceIdentifier,
     serde_qs::axum::QsQuery,
     utoipa::IntoParams,
@@ -42,7 +28,6 @@ pub struct LatestVaasQueryParams {
     ids: Vec<PriceIdInput>,
 }
 
-
 /// **Deprecated: use /v2/updates/price/latest instead**
 ///
 /// Get VAAs for a set of price feed ids.

+ 1 - 4
apps/hermes/server/src/api/rest/live.rs

@@ -1,9 +1,6 @@
 use axum::{
     http::StatusCode,
-    response::{
-        IntoResponse,
-        Response,
-    },
+    response::{IntoResponse, Response},
 };
 
 pub async fn live() -> Response {

+ 2 - 9
apps/hermes/server/src/api/rest/price_feed_ids.rs

@@ -1,17 +1,10 @@
 use {
     crate::{
-        api::{
-            rest::RestError,
-            types::RpcPriceIdentifier,
-            ApiState,
-        },
+        api::{rest::RestError, types::RpcPriceIdentifier, ApiState},
         state::aggregate::Aggregates,
     },
     anyhow::Result,
-    axum::{
-        extract::State,
-        Json,
-    },
+    axum::{extract::State, Json},
 };
 
 /// **Deprecated: use /v2/price_feeds instead**

+ 2 - 8
apps/hermes/server/src/api/rest/ready.rs

@@ -1,15 +1,9 @@
 use {
-    crate::{
-        api::ApiState,
-        state::aggregate::Aggregates,
-    },
+    crate::{api::ApiState, state::aggregate::Aggregates},
     axum::{
         extract::State,
         http::StatusCode,
-        response::{
-            IntoResponse,
-            Response,
-        },
+        response::{IntoResponse, Response},
         Json,
     },
 };

+ 6 - 26
apps/hermes/server/src/api/rest/v2/latest_price_updates.rs

@@ -1,40 +1,21 @@
 use {
     crate::{
         api::{
-            rest::{
-                validate_price_ids,
-                RestError,
-            },
-            types::{
-                BinaryUpdate,
-                EncodingType,
-                ParsedPriceUpdate,
-                PriceIdInput,
-                PriceUpdate,
-            },
+            rest::{validate_price_ids, RestError},
+            types::{BinaryUpdate, EncodingType, ParsedPriceUpdate, PriceIdInput, PriceUpdate},
             ApiState,
         },
-        state::aggregate::{
-            Aggregates,
-            RequestTime,
-        },
+        state::aggregate::{Aggregates, RequestTime},
     },
     anyhow::Result,
-    axum::{
-        extract::State,
-        Json,
-    },
-    base64::{
-        engine::general_purpose::STANDARD as base64_standard_engine,
-        Engine as _,
-    },
+    axum::{extract::State, Json},
+    base64::{engine::general_purpose::STANDARD as base64_standard_engine, Engine as _},
     pyth_sdk::PriceIdentifier,
     serde::Deserialize,
     serde_qs::axum::QsQuery,
     utoipa::IntoParams,
 };
 
-
 #[derive(Debug, Deserialize, IntoParams)]
 #[into_params(parameter_in=Query)]
 pub struct LatestPriceUpdatesQueryParams {
@@ -116,7 +97,7 @@ where
         .collect();
     let binary_price_update = BinaryUpdate {
         encoding: params.encoding,
-        data:     encoded_data,
+        data: encoded_data,
     };
     let parsed_price_updates: Option<Vec<ParsedPriceUpdate>> = if params.parsed {
         Some(
@@ -135,6 +116,5 @@ where
         parsed: parsed_price_updates,
     };
 
-
     Ok(Json(compressed_price_update))
 }

+ 4 - 13
apps/hermes/server/src/api/rest/v2/latest_publisher_stake_caps.rs

@@ -3,9 +3,7 @@ use {
         api::{
             rest::RestError,
             types::{
-                BinaryUpdate,
-                EncodingType,
-                LatestPublisherStakeCapsUpdateDataResponse,
+                BinaryUpdate, EncodingType, LatestPublisherStakeCapsUpdateDataResponse,
                 ParsedPublisherStakeCapsUpdate,
             },
             ApiState,
@@ -13,20 +11,13 @@ use {
         state::Aggregates,
     },
     anyhow::Result,
-    axum::{
-        extract::State,
-        Json,
-    },
-    base64::{
-        engine::general_purpose::STANDARD as base64_standard_engine,
-        Engine as _,
-    },
+    axum::{extract::State, Json},
+    base64::{engine::general_purpose::STANDARD as base64_standard_engine, Engine as _},
     serde::Deserialize,
     serde_qs::axum::QsQuery,
     utoipa::IntoParams,
 };
 
-
 #[derive(Debug, Deserialize, IntoParams)]
 #[into_params(parameter_in=Query)]
 pub struct LatestPublisherStakeCapsUpdateData {
@@ -86,7 +77,7 @@ where
 
     let binary = BinaryUpdate {
         encoding: params.encoding,
-        data:     encoded_data,
+        data: encoded_data,
     };
 
     let parsed: Option<Vec<ParsedPublisherStakeCapsUpdate>> = if params.parsed {

+ 2 - 9
apps/hermes/server/src/api/rest/v2/price_feeds_metadata.rs

@@ -2,25 +2,18 @@ use {
     crate::{
         api::{
             rest::RestError,
-            types::{
-                AssetType,
-                PriceFeedMetadata,
-            },
+            types::{AssetType, PriceFeedMetadata},
             ApiState,
         },
         state::price_feeds_metadata::PriceFeedMeta,
     },
     anyhow::Result,
-    axum::{
-        extract::State,
-        Json,
-    },
+    axum::{extract::State, Json},
     serde::Deserialize,
     serde_qs::axum::QsQuery,
     utoipa::IntoParams,
 };
 
-
 #[derive(Debug, Deserialize, IntoParams)]
 #[into_params(parameter_in=Query)]
 pub struct PriceFeedsMetadataQueryParams {

+ 5 - 23
apps/hermes/server/src/api/rest/v2/sse.rs

@@ -1,34 +1,19 @@
 use {
     crate::{
         api::{
-            rest::{
-                validate_price_ids,
-                RestError,
-            },
+            rest::{validate_price_ids, RestError},
             types::{
-                BinaryUpdate,
-                EncodingType,
-                ParsedPriceUpdate,
-                PriceIdInput,
-                PriceUpdate,
+                BinaryUpdate, EncodingType, ParsedPriceUpdate, PriceIdInput, PriceUpdate,
                 RpcPriceIdentifier,
             },
             ApiState,
         },
-        state::aggregate::{
-            Aggregates,
-            AggregationEvent,
-            RequestTime,
-        },
+        state::aggregate::{Aggregates, AggregationEvent, RequestTime},
     },
     anyhow::Result,
     axum::{
         extract::State,
-        response::sse::{
-            Event,
-            KeepAlive,
-            Sse,
-        },
+        response::sse::{Event, KeepAlive, Sse},
     },
     futures::Stream,
     pyth_sdk::PriceIdentifier,
@@ -36,10 +21,7 @@ use {
     serde_qs::axum::QsQuery,
     std::convert::Infallible,
     tokio::sync::broadcast,
-    tokio_stream::{
-        wrappers::BroadcastStream,
-        StreamExt as _,
-    },
+    tokio_stream::{wrappers::BroadcastStream, StreamExt as _},
     utoipa::IntoParams,
 };
 

+ 5 - 23
apps/hermes/server/src/api/rest/v2/timestamp_price_updates.rs

@@ -2,31 +2,15 @@ use {
     crate::{
         api::{
             doc_examples,
-            rest::{
-                validate_price_ids,
-                RestError,
-            },
-            types::{
-                BinaryUpdate,
-                EncodingType,
-                ParsedPriceUpdate,
-                PriceIdInput,
-                PriceUpdate,
-            },
+            rest::{validate_price_ids, RestError},
+            types::{BinaryUpdate, EncodingType, ParsedPriceUpdate, PriceIdInput, PriceUpdate},
             ApiState,
         },
-        state::aggregate::{
-            Aggregates,
-            RequestTime,
-            UnixTimestamp,
-        },
+        state::aggregate::{Aggregates, RequestTime, UnixTimestamp},
     },
     anyhow::Result,
     axum::{
-        extract::{
-            Path,
-            State,
-        },
+        extract::{Path, State},
         Json,
     },
     pyth_sdk::PriceIdentifier,
@@ -73,7 +57,6 @@ pub struct TimestampPriceUpdatesQueryParams {
     ignore_invalid_price_ids: bool,
 }
 
-
 fn default_true() -> bool {
     true
 }
@@ -133,7 +116,7 @@ where
         .collect();
     let binary_price_update = BinaryUpdate {
         encoding: query_params.encoding,
-        data:     encoded_data,
+        data: encoded_data,
     };
     let parsed_price_updates: Option<Vec<ParsedPriceUpdate>> = if query_params.parsed {
         Some(
@@ -152,6 +135,5 @@ where
         parsed: parsed_price_updates,
     };
 
-
     Ok(Json(compressed_price_update))
 }

+ 59 - 86
apps/hermes/server/src/api/types.rs

@@ -1,46 +1,20 @@
 use {
     super::doc_examples,
-    crate::state::aggregate::{
-        PriceFeedUpdate,
-        PriceFeedsWithUpdateData,
-        Slot,
-        UnixTimestamp,
-    },
+    crate::state::aggregate::{PriceFeedUpdate, PriceFeedsWithUpdateData, Slot, UnixTimestamp},
     anyhow::Result,
-    base64::{
-        engine::general_purpose::STANDARD as base64_standard_engine,
-        Engine as _,
-    },
-    borsh::{
-        BorshDeserialize,
-        BorshSerialize,
-    },
-    derive_more::{
-        Deref,
-        DerefMut,
-    },
-    pyth_sdk::{
-        Price,
-        PriceFeed,
-        PriceIdentifier,
-    },
-    serde::{
-        Deserialize,
-        Serialize,
-    },
+    base64::{engine::general_purpose::STANDARD as base64_standard_engine, Engine as _},
+    borsh::{BorshDeserialize, BorshSerialize},
+    derive_more::{Deref, DerefMut},
+    pyth_sdk::{Price, PriceFeed, PriceIdentifier},
+    serde::{Deserialize, Serialize},
     std::{
         collections::BTreeMap,
-        fmt::{
-            Display,
-            Formatter,
-            Result as FmtResult,
-        },
+        fmt::{Display, Formatter, Result as FmtResult},
     },
     utoipa::ToSchema,
     wormhole_sdk::Chain,
 };
 
-
 /// A price id is a 32-byte hex string, optionally prefixed with "0x".
 /// Price ids are case insensitive.
 ///
@@ -64,36 +38,36 @@ type Base64String = String;
 #[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]
 pub struct RpcPriceFeedMetadata {
     #[schema(value_type = Option<u64>, example=85480034)]
-    pub slot:                       Option<Slot>,
+    pub slot: Option<Slot>,
     #[schema(example = 26)]
-    pub emitter_chain:              u16,
+    pub emitter_chain: u16,
     #[schema(value_type = Option<i64>, example=doc_examples::timestamp_example)]
     pub price_service_receive_time: Option<UnixTimestamp>,
     #[schema(value_type = Option<i64>, example=doc_examples::timestamp_example)]
-    pub prev_publish_time:          Option<UnixTimestamp>,
+    pub prev_publish_time: Option<UnixTimestamp>,
 }
 
 #[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]
 pub struct RpcPriceFeedMetadataV2 {
     #[schema(value_type = Option<u64>, example=85480034)]
-    pub slot:                 Option<Slot>,
+    pub slot: Option<Slot>,
     #[schema(value_type = Option<i64>, example=doc_examples::timestamp_example)]
     pub proof_available_time: Option<UnixTimestamp>,
     #[schema(value_type = Option<i64>, example=doc_examples::timestamp_example)]
-    pub prev_publish_time:    Option<UnixTimestamp>,
+    pub prev_publish_time: Option<UnixTimestamp>,
 }
 
 #[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]
 pub struct RpcPriceFeed {
-    pub id:        RpcPriceIdentifier,
-    pub price:     RpcPrice,
+    pub id: RpcPriceIdentifier,
+    pub price: RpcPrice,
     pub ema_price: RpcPrice,
     #[serde(skip_serializing_if = "Option::is_none")]
-    pub metadata:  Option<RpcPriceFeedMetadata>,
+    pub metadata: Option<RpcPriceFeedMetadata>,
     /// The VAA binary represented as a base64 string.
     #[serde(skip_serializing_if = "Option::is_none")]
     #[schema(value_type = Option<String>, example=doc_examples::vaa_example)]
-    pub vaa:       Option<Base64String>,
+    pub vaa: Option<Base64String>,
 }
 
 impl RpcPriceFeed {
@@ -107,26 +81,26 @@ impl RpcPriceFeed {
         let price_feed = price_feed_update.price_feed;
 
         Self {
-            id:        RpcPriceIdentifier::new(price_feed.id.to_bytes()),
-            price:     RpcPrice {
-                price:        price_feed.get_price_unchecked().price,
-                conf:         price_feed.get_price_unchecked().conf,
-                expo:         price_feed.get_price_unchecked().expo,
+            id: RpcPriceIdentifier::new(price_feed.id.to_bytes()),
+            price: RpcPrice {
+                price: price_feed.get_price_unchecked().price,
+                conf: price_feed.get_price_unchecked().conf,
+                expo: price_feed.get_price_unchecked().expo,
                 publish_time: price_feed.get_price_unchecked().publish_time,
             },
             ema_price: RpcPrice {
-                price:        price_feed.get_ema_price_unchecked().price,
-                conf:         price_feed.get_ema_price_unchecked().conf,
-                expo:         price_feed.get_ema_price_unchecked().expo,
+                price: price_feed.get_ema_price_unchecked().price,
+                conf: price_feed.get_ema_price_unchecked().conf,
+                expo: price_feed.get_ema_price_unchecked().expo,
                 publish_time: price_feed.get_ema_price_unchecked().publish_time,
             },
-            metadata:  verbose.then_some(RpcPriceFeedMetadata {
-                emitter_chain:              Chain::Pythnet.into(),
+            metadata: verbose.then_some(RpcPriceFeedMetadata {
+                emitter_chain: Chain::Pythnet.into(),
                 price_service_receive_time: price_feed_update.received_at,
-                slot:                       price_feed_update.slot,
-                prev_publish_time:          price_feed_update.prev_publish_time,
+                slot: price_feed_update.slot,
+                prev_publish_time: price_feed_update.prev_publish_time,
             }),
-            vaa:       match binary {
+            vaa: match binary {
                 false => None,
                 true => price_feed_update
                     .update_data
@@ -159,22 +133,21 @@ pub struct RpcPrice {
     /// The price itself, stored as a string to avoid precision loss
     #[serde(with = "pyth_sdk::utils::as_string")]
     #[schema(value_type = String, example="2920679499999")]
-    pub price:        i64,
+    pub price: i64,
     /// The confidence interval associated with the price, stored as a string to avoid precision loss
     #[serde(with = "pyth_sdk::utils::as_string")]
     #[schema(value_type = String, example="509500001")]
-    pub conf:         u64,
+    pub conf: u64,
     /// The exponent associated with both the price and confidence interval. Multiply those values
     /// by `10^expo` to get the real value.
     #[schema(example=-8)]
-    pub expo:         i32,
+    pub expo: i32,
     /// When the price was published. The `publish_time` is a unix timestamp, i.e., the number of
     /// seconds since the Unix epoch (00:00:00 UTC on 1 Jan 1970).
     #[schema(value_type = i64, example=doc_examples::timestamp_example)]
     pub publish_time: UnixTimestamp,
 }
 
-
 #[derive(
     Copy,
     Clone,
@@ -234,15 +207,15 @@ impl EncodingType {
 #[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]
 pub struct BinaryUpdate {
     pub encoding: EncodingType,
-    pub data:     Vec<String>,
+    pub data: Vec<String>,
 }
 
 #[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]
 pub struct ParsedPriceUpdate {
-    pub id:        RpcPriceIdentifier,
-    pub price:     RpcPrice,
+    pub id: RpcPriceIdentifier,
+    pub price: RpcPrice,
     pub ema_price: RpcPrice,
-    pub metadata:  RpcPriceFeedMetadataV2,
+    pub metadata: RpcPriceFeedMetadataV2,
 }
 
 impl From<PriceFeedUpdate> for ParsedPriceUpdate {
@@ -250,23 +223,23 @@ impl From<PriceFeedUpdate> for ParsedPriceUpdate {
         let price_feed = price_feed_update.price_feed;
 
         Self {
-            id:        RpcPriceIdentifier::from(price_feed.id),
-            price:     RpcPrice {
-                price:        price_feed.get_price_unchecked().price,
-                conf:         price_feed.get_price_unchecked().conf,
-                expo:         price_feed.get_price_unchecked().expo,
+            id: RpcPriceIdentifier::from(price_feed.id),
+            price: RpcPrice {
+                price: price_feed.get_price_unchecked().price,
+                conf: price_feed.get_price_unchecked().conf,
+                expo: price_feed.get_price_unchecked().expo,
                 publish_time: price_feed.get_price_unchecked().publish_time,
             },
             ema_price: RpcPrice {
-                price:        price_feed.get_ema_price_unchecked().price,
-                conf:         price_feed.get_ema_price_unchecked().conf,
-                expo:         price_feed.get_ema_price_unchecked().expo,
+                price: price_feed.get_ema_price_unchecked().price,
+                conf: price_feed.get_ema_price_unchecked().conf,
+                expo: price_feed.get_ema_price_unchecked().expo,
                 publish_time: price_feed.get_ema_price_unchecked().publish_time,
             },
-            metadata:  RpcPriceFeedMetadataV2 {
+            metadata: RpcPriceFeedMetadataV2 {
                 proof_available_time: price_feed_update.received_at,
-                slot:                 price_feed_update.slot,
-                prev_publish_time:    price_feed_update.prev_publish_time,
+                slot: price_feed_update.slot,
+                prev_publish_time: price_feed_update.prev_publish_time,
             },
         }
     }
@@ -280,7 +253,7 @@ pub struct ParsedPublisherStakeCapsUpdate {
 #[derive(Debug, PartialEq, serde::Serialize, serde::Deserialize, Clone, ToSchema)]
 pub struct ParsedPublisherStakeCap {
     pub publisher: String,
-    pub cap:       u64,
+    pub cap: u64,
 }
 
 #[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]
@@ -305,24 +278,24 @@ impl TryFrom<PriceUpdate> for PriceFeedsWithUpdateData {
                 .into_iter()
                 .map(|parsed_price_update| {
                     Ok(PriceFeedUpdate {
-                        price_feed:        PriceFeed::new(
+                        price_feed: PriceFeed::new(
                             parsed_price_update.id.into(),
                             Price {
-                                price:        parsed_price_update.price.price,
-                                conf:         parsed_price_update.price.conf,
-                                expo:         parsed_price_update.price.expo,
+                                price: parsed_price_update.price.price,
+                                conf: parsed_price_update.price.conf,
+                                expo: parsed_price_update.price.expo,
                                 publish_time: parsed_price_update.price.publish_time,
                             },
                             Price {
-                                price:        parsed_price_update.ema_price.price,
-                                conf:         parsed_price_update.ema_price.conf,
-                                expo:         parsed_price_update.ema_price.expo,
+                                price: parsed_price_update.ema_price.price,
+                                conf: parsed_price_update.ema_price.conf,
+                                expo: parsed_price_update.ema_price.expo,
                                 publish_time: parsed_price_update.ema_price.publish_time,
                             },
                         ),
-                        slot:              parsed_price_update.metadata.slot,
-                        received_at:       parsed_price_update.metadata.proof_available_time,
-                        update_data:       None, // This field is not available in ParsedPriceUpdate
+                        slot: parsed_price_update.metadata.slot,
+                        received_at: parsed_price_update.metadata.proof_available_time,
+                        update_data: None, // This field is not available in ParsedPriceUpdate
                         prev_publish_time: parsed_price_update.metadata.prev_publish_time,
                     })
                 })
@@ -346,7 +319,7 @@ impl TryFrom<PriceUpdate> for PriceFeedsWithUpdateData {
 
 #[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]
 pub struct PriceFeedMetadata {
-    pub id:         RpcPriceIdentifier,
+    pub id: RpcPriceIdentifier,
     // BTreeMap is used to automatically sort the keys to ensure consistent ordering of attributes in the JSON response.
     // This enhances user experience by providing a predictable structure, avoiding confusion from varying orders in different responses.
     pub attributes: BTreeMap<String, String>,

+ 41 - 83
apps/hermes/server/src/api/ws.rs

@@ -1,85 +1,46 @@
 use {
     super::{
-        types::{
-            PriceIdInput,
-            RpcPriceFeed,
-        },
+        types::{PriceIdInput, RpcPriceFeed},
         ApiState,
     },
     crate::state::{
-        aggregate::{
-            Aggregates,
-            AggregationEvent,
-            RequestTime,
-        },
+        aggregate::{Aggregates, AggregationEvent, RequestTime},
         metrics::Metrics,
-        Benchmarks,
-        Cache,
-        PriceFeedMeta,
-    },
-    anyhow::{
-        anyhow,
-        Result,
+        Benchmarks, Cache, PriceFeedMeta,
     },
+    anyhow::{anyhow, Result},
     axum::{
         extract::{
-            ws::{
-                Message,
-                WebSocket,
-                WebSocketUpgrade,
-            },
+            ws::{Message, WebSocket, WebSocketUpgrade},
             State as AxumState,
         },
         http::HeaderMap,
         response::IntoResponse,
     },
     futures::{
-        stream::{
-            SplitSink,
-            SplitStream,
-        },
-        SinkExt,
-        StreamExt,
-    },
-    governor::{
-        DefaultKeyedRateLimiter,
-        Quota,
-        RateLimiter,
+        stream::{SplitSink, SplitStream},
+        SinkExt, StreamExt,
     },
+    governor::{DefaultKeyedRateLimiter, Quota, RateLimiter},
     ipnet::IpNet,
     nonzero_ext::nonzero,
     prometheus_client::{
-        encoding::{
-            EncodeLabelSet,
-            EncodeLabelValue,
-        },
-        metrics::{
-            counter::Counter,
-            family::Family,
-        },
+        encoding::{EncodeLabelSet, EncodeLabelValue},
+        metrics::{counter::Counter, family::Family},
     },
     pyth_sdk::PriceIdentifier,
-    serde::{
-        Deserialize,
-        Serialize,
-    },
+    serde::{Deserialize, Serialize},
     std::{
         collections::HashMap,
         net::IpAddr,
         num::NonZeroU32,
         sync::{
-            atomic::{
-                AtomicUsize,
-                Ordering,
-            },
+            atomic::{AtomicUsize, Ordering},
             Arc,
         },
         time::Duration,
     },
-    tokio::sync::{
-        broadcast::Receiver,
-        watch,
-    },
+    tokio::sync::{broadcast::Receiver, watch},
 };
 
 const PING_INTERVAL_DURATION: Duration = Duration::from_secs(30);
@@ -91,8 +52,8 @@ const BYTES_LIMIT_PER_IP_PER_SECOND: u32 = 256 * 1024; // 256 KiB
 
 #[derive(Clone)]
 pub struct PriceFeedClientConfig {
-    verbose:            bool,
-    binary:             bool,
+    verbose: bool,
+    binary: bool,
     allow_out_of_order: bool,
 }
 
@@ -115,7 +76,7 @@ pub enum Status {
 #[derive(Clone, Debug, PartialEq, Eq, Hash, EncodeLabelSet)]
 pub struct Labels {
     pub interaction: Interaction,
-    pub status:      Status,
+    pub status: Status,
 }
 
 pub struct WsMetrics {
@@ -153,11 +114,11 @@ impl WsMetrics {
 }
 
 pub struct WsState {
-    pub subscriber_counter:       AtomicUsize,
-    pub bytes_limit_whitelist:    Vec<IpNet>,
-    pub rate_limiter:             DefaultKeyedRateLimiter<IpAddr>,
+    pub subscriber_counter: AtomicUsize,
+    pub bytes_limit_whitelist: Vec<IpNet>,
+    pub rate_limiter: DefaultKeyedRateLimiter<IpAddr>,
     pub requester_ip_header_name: String,
-    pub metrics:                  WsMetrics,
+    pub metrics: WsMetrics,
 }
 
 impl WsState {
@@ -178,17 +139,16 @@ impl WsState {
     }
 }
 
-
 #[derive(Deserialize, Debug, Clone)]
 #[serde(tag = "type")]
 enum ClientMessage {
     #[serde(rename = "subscribe")]
     Subscribe {
-        ids:                Vec<PriceIdInput>,
+        ids: Vec<PriceIdInput>,
         #[serde(default)]
-        verbose:            bool,
+        verbose: bool,
         #[serde(default)]
-        binary:             bool,
+        binary: bool,
         #[serde(default)]
         allow_out_of_order: bool,
     },
@@ -196,7 +156,6 @@ enum ClientMessage {
     Unsubscribe { ids: Vec<PriceIdInput> },
 }
 
-
 #[derive(Serialize, Debug, Clone)]
 #[serde(tag = "type")]
 enum ServerMessage {
@@ -257,7 +216,7 @@ where
         .interactions
         .get_or_create(&Labels {
             interaction: Interaction::NewConnection,
-            status:      Status::Success,
+            status: Status::Success,
         })
         .inc();
 
@@ -281,18 +240,18 @@ pub type SubscriberId = usize;
 /// Subscriber is an actor that handles a single websocket connection.
 /// It listens to the store for updates and sends them to the client.
 pub struct Subscriber<S> {
-    id:                      SubscriberId,
-    ip_addr:                 Option<IpAddr>,
-    closed:                  bool,
-    state:                   Arc<S>,
-    ws_state:                Arc<WsState>,
-    notify_receiver:         Receiver<AggregationEvent>,
-    receiver:                SplitStream<WebSocket>,
-    sender:                  SplitSink<WebSocket, Message>,
+    id: SubscriberId,
+    ip_addr: Option<IpAddr>,
+    closed: bool,
+    state: Arc<S>,
+    ws_state: Arc<WsState>,
+    notify_receiver: Receiver<AggregationEvent>,
+    receiver: SplitStream<WebSocket>,
+    sender: SplitSink<WebSocket, Message>,
     price_feeds_with_config: HashMap<PriceIdentifier, PriceFeedClientConfig>,
-    ping_interval:           tokio::time::Interval,
-    exit:                    watch::Receiver<bool>,
-    responded_to_ping:       bool,
+    ping_interval: tokio::time::Interval,
+    exit: watch::Receiver<bool>,
+    responded_to_ping: bool,
 }
 
 impl<S> Subscriber<S>
@@ -460,11 +419,10 @@ where
                         .interactions
                         .get_or_create(&Labels {
                             interaction: Interaction::RateLimit,
-                            status:      Status::Error,
+                            status: Status::Error,
                         })
                         .inc();
 
-
                     self.sender
                         .send(
                             serde_json::to_string(&ServerResponseMessage::Err {
@@ -488,7 +446,7 @@ where
                 .interactions
                 .get_or_create(&Labels {
                     interaction: Interaction::PriceUpdate,
-                    status:      Status::Success,
+                    status: Status::Success,
                 })
                 .inc();
         }
@@ -511,7 +469,7 @@ where
                     .interactions
                     .get_or_create(&Labels {
                         interaction: Interaction::CloseConnection,
-                        status:      Status::Success,
+                        status: Status::Success,
                     })
                     .inc();
 
@@ -535,7 +493,7 @@ where
                     .interactions
                     .get_or_create(&Labels {
                         interaction: Interaction::ClientHeartbeat,
-                        status:      Status::Success,
+                        status: Status::Success,
                     })
                     .inc();
 
@@ -551,7 +509,7 @@ where
                     .interactions
                     .get_or_create(&Labels {
                         interaction: Interaction::ClientMessage,
-                        status:      Status::Error,
+                        status: Status::Error,
                     })
                     .inc();
                 self.sender
@@ -624,7 +582,7 @@ where
             .interactions
             .get_or_create(&Labels {
                 interaction: Interaction::ClientMessage,
-                status:      Status::Success,
+                status: Status::Success,
             })
             .inc();
 

+ 1 - 8
apps/hermes/server/src/config.rs

@@ -1,11 +1,4 @@
-use clap::{
-    crate_authors,
-    crate_description,
-    crate_name,
-    crate_version,
-    Args,
-    Parser,
-};
+use clap::{crate_authors, crate_description, crate_name, crate_version, Args, Parser};
 
 mod aggregate;
 mod benchmarks;

+ 1 - 4
apps/hermes/server/src/config/aggregate.rs

@@ -1,7 +1,4 @@
-use {
-    clap::Args,
-    humantime::Duration,
-};
+use {clap::Args, humantime::Duration};
 
 #[derive(Args, Clone, Debug)]
 #[command(next_help_heading = "Aggregate Options")]

+ 1 - 4
apps/hermes/server/src/config/benchmarks.rs

@@ -1,7 +1,4 @@
-use {
-    clap::Args,
-    reqwest::Url,
-};
+use {clap::Args, reqwest::Url};
 
 #[derive(Args, Clone, Debug)]
 #[command(next_help_heading = "Benchmark Options")]

+ 1 - 4
apps/hermes/server/src/config/metrics.rs

@@ -1,7 +1,4 @@
-use {
-    clap::Args,
-    std::net::SocketAddr,
-};
+use {clap::Args, std::net::SocketAddr};
 
 const DEFAULT_METRICS_SERVER_LISTEN_ADDR: &str = "127.0.0.1:33888";
 

+ 1 - 4
apps/hermes/server/src/config/pythnet.rs

@@ -1,7 +1,4 @@
-use {
-    clap::Args,
-    solana_sdk::pubkey::Pubkey,
-};
+use {clap::Args, solana_sdk::pubkey::Pubkey};
 
 const DEFAULT_PYTHNET_MAPPING_ADDR: &str = "AHtgzX45WTKfkPG53L6WYhGEXwQkN1BVknET3sVsLL8J";
 

+ 1 - 5
apps/hermes/server/src/config/rpc.rs

@@ -1,8 +1,4 @@
-use {
-    clap::Args,
-    ipnet::IpNet,
-    std::net::SocketAddr,
-};
+use {clap::Args, ipnet::IpNet, std::net::SocketAddr};
 
 const DEFAULT_RPC_LISTEN_ADDR: &str = "127.0.0.1:33999";
 const DEFAULT_RPC_REQUESTER_IP_HEADER_NAME: &str = "X-Forwarded-For";

+ 1 - 4
apps/hermes/server/src/config/wormhole.rs

@@ -1,7 +1,4 @@
-use {
-    clap::Args,
-    solana_sdk::pubkey::Pubkey,
-};
+use {clap::Args, solana_sdk::pubkey::Pubkey};
 
 const DEFAULT_CONTRACT_ADDR: &str = "H3fxXJ86ADW2PNuDDmZJg6mzTtPxkYCpNuQUTgmJ7AjU";
 

+ 2 - 8
apps/hermes/server/src/main.rs

@@ -1,16 +1,10 @@
 use {
     anyhow::Result,
-    clap::{
-        CommandFactory,
-        Parser,
-    },
+    clap::{CommandFactory, Parser},
     futures::future::join_all,
     lazy_static::lazy_static,
     std::io::IsTerminal,
-    tokio::{
-        spawn,
-        sync::watch,
-    },
+    tokio::{spawn, sync::watch},
 };
 
 mod api;

+ 2 - 12
apps/hermes/server/src/metrics_server.rs

@@ -3,22 +3,12 @@
 //! This server serves metrics over /metrics in OpenMetrics format.
 
 use {
-    crate::{
-        config::RunOptions,
-        state::metrics::Metrics,
-    },
+    crate::{config::RunOptions, state::metrics::Metrics},
     anyhow::Result,
-    axum::{
-        extract::State,
-        http::header,
-        response::IntoResponse,
-        routing::get,
-        Router,
-    },
+    axum::{extract::State, http::header, response::IntoResponse, routing::get, Router},
     std::sync::Arc,
 };
 
-
 #[tracing::instrument(skip(opts, state))]
 pub async fn run<S>(opts: RunOptions, state: Arc<S>) -> Result<()>
 where

+ 13 - 54
apps/hermes/server/src/network/pythnet.rs

@@ -4,68 +4,30 @@
 
 use {
     crate::{
-        api::types::{
-            PriceFeedMetadata,
-            RpcPriceIdentifier,
-        },
+        api::types::{PriceFeedMetadata, RpcPriceIdentifier},
         config::RunOptions,
-        network::wormhole::{
-            BridgeData,
-            GuardianSet,
-            GuardianSetData,
-        },
+        network::wormhole::{BridgeData, GuardianSet, GuardianSetData},
         state::{
-            aggregate::{
-                AccumulatorMessages,
-                Aggregates,
-                Update,
-            },
-            price_feeds_metadata::{
-                PriceFeedMeta,
-                DEFAULT_PRICE_FEEDS_CACHE_UPDATE_INTERVAL,
-            },
+            aggregate::{AccumulatorMessages, Aggregates, Update},
+            price_feeds_metadata::{PriceFeedMeta, DEFAULT_PRICE_FEEDS_CACHE_UPDATE_INTERVAL},
             wormhole::Wormhole,
         },
     },
-    anyhow::{
-        anyhow,
-        Result,
-    },
+    anyhow::{anyhow, Result},
     borsh::BorshDeserialize,
     futures::stream::StreamExt,
     pyth_sdk::PriceIdentifier,
-    pyth_sdk_solana::state::{
-        load_mapping_account,
-        load_product_account,
-    },
+    pyth_sdk_solana::state::{load_mapping_account, load_product_account},
     solana_account_decoder::UiAccountEncoding,
     solana_client::{
-        nonblocking::{
-            pubsub_client::PubsubClient,
-            rpc_client::RpcClient,
-        },
-        rpc_config::{
-            RpcAccountInfoConfig,
-            RpcProgramAccountsConfig,
-        },
-        rpc_filter::{
-            Memcmp,
-            MemcmpEncodedBytes,
-            RpcFilterType,
-        },
+        nonblocking::{pubsub_client::PubsubClient, rpc_client::RpcClient},
+        rpc_config::{RpcAccountInfoConfig, RpcProgramAccountsConfig},
+        rpc_filter::{Memcmp, MemcmpEncodedBytes, RpcFilterType},
     },
     solana_sdk::{
-        account::Account,
-        bs58,
-        commitment_config::CommitmentConfig,
-        pubkey::Pubkey,
-        system_program,
-    },
-    std::{
-        collections::BTreeMap,
-        sync::Arc,
-        time::Duration,
+        account::Account, bs58, commitment_config::CommitmentConfig, pubkey::Pubkey, system_program,
     },
+    std::{collections::BTreeMap, sync::Arc, time::Duration},
     tokio::time::Instant,
 };
 
@@ -155,11 +117,11 @@ where
             encoding: Some(UiAccountEncoding::Base64Zstd),
             ..Default::default()
         },
-        filters:        Some(vec![RpcFilterType::Memcmp(Memcmp::new(
+        filters: Some(vec![RpcFilterType::Memcmp(Memcmp::new(
             0,                                           // offset
             MemcmpEncodedBytes::Bytes(b"PAS1".to_vec()), // bytes
         ))]),
-        with_context:   Some(true),
+        with_context: Some(true),
     };
 
     // Listen for all PythNet accounts, we will filter down to the Accumulator related accounts.
@@ -333,7 +295,6 @@ where
         })
     };
 
-
     let task_price_feeds_metadata_updater = {
         let price_feeds_state = state.clone();
         let mut exit = crate::EXIT.subscribe();
@@ -378,7 +339,6 @@ where
     Ok(())
 }
 
-
 pub async fn fetch_and_store_price_feeds_metadata<S>(
     state: &S,
     mapping_address: &Pubkey,
@@ -396,7 +356,6 @@ where
         .filter(|metadata| all_ids.contains(&PriceIdentifier::from(metadata.id)))
         .collect();
 
-
     state.store_price_feeds_metadata(&filtered_metadata).await?;
     Ok(filtered_metadata)
 }

+ 12 - 24
apps/hermes/server/src/network/wormhole.rs

@@ -5,27 +5,15 @@
 //! application.
 
 use {
-    crate::{
-        config::RunOptions,
-        state::wormhole::Wormhole,
-    },
-    anyhow::{
-        anyhow,
-        Result,
-    },
+    crate::{config::RunOptions, state::wormhole::Wormhole},
+    anyhow::{anyhow, Result},
     futures::StreamExt,
     proto::spy::v1::{
-        filter_entry::Filter,
-        spy_rpc_service_client::SpyRpcServiceClient,
-        EmitterFilter,
-        FilterEntry,
-        SubscribeSignedVaaRequest,
+        filter_entry::Filter, spy_rpc_service_client::SpyRpcServiceClient, EmitterFilter,
+        FilterEntry, SubscribeSignedVaaRequest,
     },
     pythnet_sdk::ACCUMULATOR_EMITTER_ADDRESS,
-    std::{
-        sync::Arc,
-        time::Duration,
-    },
+    std::{sync::Arc, time::Duration},
     tokio::time::Instant,
     tonic::Request,
     wormhole_sdk::Chain,
@@ -58,8 +46,8 @@ impl std::fmt::Display for GuardianSet {
 #[allow(dead_code)]
 pub struct BridgeData {
     pub guardian_set_index: u32,
-    pub last_lamports:      u64,
-    pub config:             BridgeConfig,
+    pub last_lamports: u64,
+    pub config: BridgeConfig,
 }
 
 /// BridgeConfig extracted from wormhole bridge account, due to no API.
@@ -67,15 +55,15 @@ pub struct BridgeData {
 #[allow(dead_code)]
 pub struct BridgeConfig {
     pub guardian_set_expiration_time: u32,
-    pub fee:                          u64,
+    pub fee: u64,
 }
 
 /// GuardianSetData extracted from wormhole bridge account, due to no API.
 #[derive(borsh::BorshDeserialize)]
 pub struct GuardianSetData {
-    pub _index:           u32,
-    pub keys:             Vec<[u8; 20]>,
-    pub _creation_time:   u32,
+    pub _index: u32,
+    pub keys: Vec<[u8; 20]>,
+    pub _creation_time: u32,
     pub _expiration_time: u32,
 }
 
@@ -150,7 +138,7 @@ where
         .subscribe_signed_vaa(Request::new(SubscribeSignedVaaRequest {
             filters: vec![FilterEntry {
                 filter: Some(Filter::EmitterFilter(EmitterFilter {
-                    chain_id:        Into::<u16>::into(Chain::Pythnet).into(),
+                    chain_id: Into::<u16>::into(Chain::Pythnet).into(),
                     emitter_address: hex::encode(ACCUMULATOR_EMITTER_ADDRESS),
                 })),
             }],

+ 1 - 6
apps/hermes/server/src/serde.rs

@@ -1,12 +1,7 @@
 pub mod hex {
     use {
         hex::FromHex,
-        serde::{
-            de::IntoDeserializer,
-            Deserialize,
-            Deserializer,
-            Serializer,
-        },
+        serde::{de::IntoDeserializer, Deserialize, Deserializer, Serializer},
     };
 
     pub fn serialize<S, const N: usize>(b: &[u8; N], s: S) -> Result<S::Ok, S::Error>

+ 11 - 28
apps/hermes/server/src/state.rs

@@ -2,10 +2,7 @@
 
 use {
     self::{
-        aggregate::{
-            AggregateState,
-            AggregationEvent,
-        },
+        aggregate::{AggregateState, AggregationEvent},
         benchmarks::BenchmarksState,
         cache::CacheState,
         metrics::MetricsState,
@@ -15,10 +12,7 @@ use {
     aggregate::Slot,
     prometheus_client::registry::Registry,
     reqwest::Url,
-    std::{
-        sync::Arc,
-        time::Duration,
-    },
+    std::{sync::Arc, time::Duration},
     tokio::sync::broadcast::Sender,
 };
 
@@ -31,12 +25,8 @@ pub mod wormhole;
 
 // Expose State interfaces and types for other modules.
 pub use {
-    aggregate::Aggregates,
-    benchmarks::Benchmarks,
-    cache::Cache,
-    metrics::Metrics,
-    price_feeds_metadata::PriceFeedMeta,
-    wormhole::Wormhole,
+    aggregate::Aggregates, benchmarks::Benchmarks, cache::Cache, metrics::Metrics,
+    price_feeds_metadata::PriceFeedMeta, wormhole::Wormhole,
 };
 
 /// State contains all relevant shared application state.
@@ -73,33 +63,26 @@ pub fn new(
 ) -> Arc<impl Metrics + Wormhole> {
     let mut metrics_registry = Registry::default();
     Arc::new(State {
-        cache:           CacheState::new(cache_size),
-        benchmarks:      BenchmarksState::new(benchmarks_endpoint),
+        cache: CacheState::new(cache_size),
+        benchmarks: BenchmarksState::new(benchmarks_endpoint),
         price_feed_meta: PriceFeedMetaState::new(),
-        aggregates:      AggregateState::new(
+        aggregates: AggregateState::new(
             update_tx,
             readiness_staleness_threshold,
             readiness_max_allowed_slot_lag,
             &mut metrics_registry,
         ),
-        wormhole:        WormholeState::new(),
-        metrics:         MetricsState::new(metrics_registry),
+        wormhole: WormholeState::new(),
+        metrics: MetricsState::new(metrics_registry),
     })
 }
 
 #[cfg(test)]
 pub mod test {
     use {
-        super::{
-            aggregate::AggregationEvent,
-            Aggregates,
-            Wormhole,
-        },
+        super::{aggregate::AggregationEvent, Aggregates, Wormhole},
         crate::network::wormhole::GuardianSet,
-        std::{
-            sync::Arc,
-            time::Duration,
-        },
+        std::{sync::Arc, time::Duration},
         tokio::sync::broadcast::Receiver,
     };
 

+ 65 - 115
apps/hermes/server/src/state/aggregate.rs

@@ -1,75 +1,39 @@
 #[cfg(test)]
-use mock_instant::{
-    SystemTime,
-    UNIX_EPOCH,
-};
+use mock_instant::{SystemTime, UNIX_EPOCH};
 #[cfg(not(test))]
-use std::time::{
-    SystemTime,
-    UNIX_EPOCH,
-};
+use std::time::{SystemTime, UNIX_EPOCH};
 use {
     self::wormhole_merkle::{
-        construct_message_states_proofs,
-        construct_update_data,
-        store_wormhole_merkle_verified_message,
-        WormholeMerkleMessageProof,
-        WormholeMerkleState,
+        construct_message_states_proofs, construct_update_data,
+        store_wormhole_merkle_verified_message, WormholeMerkleMessageProof, WormholeMerkleState,
     },
     crate::{
-        api::types::{
-            ParsedPublisherStakeCap,
-            ParsedPublisherStakeCapsUpdate,
-        },
+        api::types::{ParsedPublisherStakeCap, ParsedPublisherStakeCapsUpdate},
         network::wormhole::VaaBytes,
         state::{
             benchmarks::Benchmarks,
-            cache::{
-                Cache,
-                MessageState,
-                MessageStateFilter,
-            },
+            cache::{Cache, MessageState, MessageStateFilter},
             price_feeds_metadata::PriceFeedMeta,
             State,
         },
     },
-    anyhow::{
-        anyhow,
-        Result,
-    },
+    anyhow::{anyhow, Result},
     borsh::BorshDeserialize,
     byteorder::BigEndian,
     prometheus_client::registry::Registry,
-    pyth_sdk::{
-        Price,
-        PriceFeed,
-        PriceIdentifier,
-    },
+    pyth_sdk::{Price, PriceFeed, PriceIdentifier},
     pythnet_sdk::{
-        messages::{
-            Message,
-            MessageType,
-            PUBLISHER_STAKE_CAPS_MESSAGE_FEED_ID,
-        },
+        messages::{Message, MessageType, PUBLISHER_STAKE_CAPS_MESSAGE_FEED_ID},
         wire::{
             from_slice,
-            v1::{
-                WormholeMessage,
-                WormholePayload,
-            },
+            v1::{WormholeMessage, WormholePayload},
         },
     },
     serde::Serialize,
     solana_sdk::pubkey::Pubkey,
-    std::{
-        collections::HashSet,
-        time::Duration,
-    },
+    std::{collections::HashSet, time::Duration},
     tokio::sync::{
-        broadcast::{
-            Receiver,
-            Sender,
-        },
+        broadcast::{Receiver, Sender},
         RwLock,
     },
     wormhole_sdk::Vaa,
@@ -157,7 +121,7 @@ impl AggregateStateData {
 }
 
 pub struct AggregateState {
-    pub data:          RwLock<AggregateStateData>,
+    pub data: RwLock<AggregateStateData>,
     pub api_update_tx: Sender<AggregationEvent>,
 }
 
@@ -169,7 +133,7 @@ impl AggregateState {
         metrics_registry: &mut Registry,
     ) -> Self {
         Self {
-            data:          RwLock::new(AggregateStateData::new(
+            data: RwLock::new(AggregateStateData::new(
                 readiness_staleness_threshold,
                 readiness_max_allowed_slot_lag,
                 metrics_registry,
@@ -187,9 +151,9 @@ impl AggregateState {
 /// uses little-endian byte order.
 #[derive(Clone, PartialEq, Debug, BorshDeserialize)]
 pub struct AccumulatorMessages {
-    pub magic:        [u8; 4],
-    pub slot:         u64,
-    pub ring_size:    u32,
+    pub magic: [u8; 4],
+    pub slot: u64,
+    pub ring_size: u32,
     pub raw_messages: Vec<RawMessage>,
 }
 
@@ -207,10 +171,10 @@ pub enum Update {
 
 #[derive(Debug, PartialEq)]
 pub struct PriceFeedUpdate {
-    pub price_feed:        PriceFeed,
-    pub slot:              Option<Slot>,
-    pub received_at:       Option<UnixTimestamp>,
-    pub update_data:       Option<Vec<u8>>,
+    pub price_feed: PriceFeed,
+    pub slot: Option<Slot>,
+    pub received_at: Option<UnixTimestamp>,
+    pub update_data: Option<Vec<u8>>,
     pub prev_publish_time: Option<UnixTimestamp>,
 }
 
@@ -223,18 +187,18 @@ pub struct PriceFeedsWithUpdateData {
 #[derive(Debug, PartialEq)]
 pub struct PublisherStakeCapsWithUpdateData {
     pub publisher_stake_caps: Vec<ParsedPublisherStakeCapsUpdate>,
-    pub update_data:          Vec<Vec<u8>>,
+    pub update_data: Vec<Vec<u8>>,
 }
 
 #[derive(Debug, Serialize)]
 pub struct ReadinessMetadata {
-    pub has_completed_recently:          bool,
-    pub is_not_behind:                   bool,
-    pub is_metadata_loaded:              bool,
-    pub latest_completed_slot:           Option<Slot>,
-    pub latest_observed_slot:            Option<Slot>,
+    pub has_completed_recently: bool,
+    pub is_not_behind: bool,
+    pub is_metadata_loaded: bool,
+    pub latest_completed_slot: Option<Slot>,
+    pub latest_observed_slot: Option<Slot>,
     pub latest_completed_unix_timestamp: Option<UnixTimestamp>,
-    pub price_feeds_metadata_len:        usize,
+    pub price_feeds_metadata_len: usize,
 }
 
 #[async_trait::async_trait]
@@ -437,7 +401,7 @@ where
                         .iter()
                         .map(|cap| ParsedPublisherStakeCap {
                             publisher: Pubkey::from(cap.publisher).to_string(),
-                            cap:       cap.cap,
+                            cap: cap.cap,
                         })
                         .collect(),
                 }),
@@ -567,24 +531,24 @@ where
         .iter()
         .map(|message_state| match message_state.message {
             Message::PriceFeedMessage(price_feed) => Ok(PriceFeedUpdate {
-                price_feed:        PriceFeed::new(
+                price_feed: PriceFeed::new(
                     PriceIdentifier::new(price_feed.feed_id),
                     Price {
-                        price:        price_feed.price,
-                        conf:         price_feed.conf,
-                        expo:         price_feed.exponent,
+                        price: price_feed.price,
+                        conf: price_feed.conf,
+                        expo: price_feed.exponent,
                         publish_time: price_feed.publish_time,
                     },
                     Price {
-                        price:        price_feed.ema_price,
-                        conf:         price_feed.ema_conf,
-                        expo:         price_feed.exponent,
+                        price: price_feed.ema_price,
+                        conf: price_feed.ema_conf,
+                        expo: price_feed.exponent,
                         publish_time: price_feed.publish_time,
                     },
                 ),
-                received_at:       Some(message_state.received_at),
-                slot:              Some(message_state.slot),
-                update_data:       Some(
+                received_at: Some(message_state.received_at),
+                slot: Some(message_state.slot),
+                update_data: Some(
                     construct_update_data(vec![message_state.clone().into()])?
                         .into_iter()
                         .next()
@@ -609,37 +573,24 @@ mod test {
     use {
         super::*,
         crate::{
-            api::types::{
-                PriceFeedMetadata,
-                RpcPriceIdentifier,
-            },
+            api::types::{PriceFeedMetadata, RpcPriceIdentifier},
             state::test::setup_state,
         },
         futures::future::join_all,
         mock_instant::MockClock,
         pythnet_sdk::{
             accumulators::{
-                merkle::{
-                    MerkleRoot,
-                    MerkleTree,
-                },
+                merkle::{MerkleRoot, MerkleTree},
                 Accumulator,
             },
             hashers::keccak256_160::Keccak160,
             messages::PriceFeedMessage,
-            wire::v1::{
-                AccumulatorUpdateData,
-                Proof,
-                WormholeMerkleRoot,
-            },
+            wire::v1::{AccumulatorUpdateData, Proof, WormholeMerkleRoot},
         },
         rand::seq::SliceRandom,
         serde_wormhole::RawMessage,
         std::sync::Arc,
-        wormhole_sdk::{
-            Address,
-            Chain,
-        },
+        wormhole_sdk::{Address, Chain},
     };
 
     /// Generate list of updates for the given list of messages at a given slot with given sequence
@@ -761,24 +712,24 @@ mod test {
         assert_eq!(
             price_feeds_with_update_data.price_feeds,
             vec![PriceFeedUpdate {
-                price_feed:        PriceFeed::new(
+                price_feed: PriceFeed::new(
                     PriceIdentifier::new(price_feed_message.feed_id),
                     Price {
-                        price:        price_feed_message.price,
-                        conf:         price_feed_message.conf,
-                        expo:         price_feed_message.exponent,
+                        price: price_feed_message.price,
+                        conf: price_feed_message.conf,
+                        expo: price_feed_message.exponent,
                         publish_time: price_feed_message.publish_time,
                     },
                     Price {
-                        price:        price_feed_message.ema_price,
-                        conf:         price_feed_message.ema_conf,
-                        expo:         price_feed_message.exponent,
+                        price: price_feed_message.ema_price,
+                        conf: price_feed_message.ema_conf,
+                        expo: price_feed_message.exponent,
                         publish_time: price_feed_message.publish_time,
                     }
                 ),
-                slot:              Some(10),
-                received_at:       price_feeds_with_update_data.price_feeds[0].received_at, // Ignore checking this field.
-                update_data:       price_feeds_with_update_data.price_feeds[0]
+                slot: Some(10),
+                received_at: price_feeds_with_update_data.price_feeds[0].received_at, // Ignore checking this field.
+                update_data: price_feeds_with_update_data.price_feeds[0]
                     .update_data
                     .clone(), // Ignore checking this field.
                 prev_publish_time: Some(9),
@@ -797,16 +748,16 @@ mod test {
                 assert_eq!(
                     vaa,
                     Vaa {
-                        nonce:              0,
-                        version:            0,
-                        sequence:           20,
-                        timestamp:          0,
-                        signatures:         vec![],
+                        nonce: 0,
+                        version: 0,
+                        sequence: 20,
+                        timestamp: 0,
+                        signatures: vec![],
                         guardian_set_index: 0,
-                        emitter_chain:      Chain::Pythnet,
-                        emitter_address:    Address(pythnet_sdk::ACCUMULATOR_EMITTER_ADDRESS),
-                        consistency_level:  0,
-                        payload:            vaa.payload, // Ignore checking this field.
+                        emitter_chain: Chain::Pythnet,
+                        emitter_address: Address(pythnet_sdk::ACCUMULATOR_EMITTER_ADDRESS),
+                        consistency_level: 0,
+                        payload: vaa.payload, // Ignore checking this field.
                     }
                 );
                 let merkle_root = WormholeMessage::try_from_bytes(vaa.payload.as_ref()).unwrap();
@@ -814,9 +765,9 @@ mod test {
                 assert_eq!(
                     merkle_root,
                     WormholeMerkleRoot {
-                        slot:      10,
+                        slot: 10,
                         ring_size: 100,
-                        root:      merkle_root.root, // Ignore checking this field.
+                        root: merkle_root.root, // Ignore checking this field.
                     }
                 );
 
@@ -967,11 +918,10 @@ mod test {
             Some(unix_timestamp as i64)
         );
 
-
         // Add a dummy price feeds metadata
         state
             .store_price_feeds_metadata(&[PriceFeedMetadata {
-                id:         RpcPriceIdentifier::new([100; 32]),
+                id: RpcPriceIdentifier::new([100; 32]),
                 attributes: Default::default(),
             }])
             .await

+ 9 - 19
apps/hermes/server/src/state/aggregate/metrics.rs

@@ -1,21 +1,11 @@
 use {
     super::Slot,
     prometheus_client::{
-        encoding::{
-            EncodeLabelSet,
-            EncodeLabelValue,
-        },
-        metrics::{
-            counter::Counter,
-            family::Family,
-            histogram::Histogram,
-        },
+        encoding::{EncodeLabelSet, EncodeLabelValue},
+        metrics::{counter::Counter, family::Family, histogram::Histogram},
         registry::Registry,
     },
-    std::collections::{
-        BTreeMap,
-        HashMap,
-    },
+    std::collections::{BTreeMap, HashMap},
     tokio::time::Instant,
 };
 
@@ -42,17 +32,17 @@ struct ObservedSlotLabels {
 
 #[derive(Clone, Debug)]
 pub struct Metrics {
-    observed_slot:               Family<ObservedSlotLabels, Counter>,
-    observed_slot_latency:       Family<ObservedSlotLabels, Histogram>,
+    observed_slot: Family<ObservedSlotLabels, Counter>,
+    observed_slot_latency: Family<ObservedSlotLabels, Histogram>,
     first_observed_time_of_slot: BTreeMap<Slot, Instant>,
-    newest_observed_slot:        HashMap<Event, Slot>,
+    newest_observed_slot: HashMap<Event, Slot>,
 }
 
 impl Metrics {
     pub fn new(metrics_registry: &mut Registry) -> Self {
         let new = Self {
-            observed_slot:               Family::default(),
-            observed_slot_latency:       Family::new_with_constructor(|| {
+            observed_slot: Family::default(),
+            observed_slot_latency: Family::new_with_constructor(|| {
                 Histogram::new(
                     [
                         0.1, 0.2, 0.3, 0.4, 0.5, 0.7, 1.0, 1.3, 1.7, 2.0, 3.0, 5.0, 10.0, 20.0,
@@ -61,7 +51,7 @@ impl Metrics {
                 )
             }),
             first_observed_time_of_slot: BTreeMap::new(),
-            newest_observed_slot:        HashMap::new(),
+            newest_observed_slot: HashMap::new(),
         };
 
         {

+ 25 - 46
apps/hermes/server/src/state/aggregate/wormhole_merkle.rs

@@ -1,37 +1,19 @@
 use {
-    super::{
-        AccumulatorMessages,
-        RawMessage,
-        Slot,
-    },
+    super::{AccumulatorMessages, RawMessage, Slot},
     crate::{
         network::wormhole::VaaBytes,
-        state::cache::{
-            Cache,
-            MessageState,
-        },
-    },
-    anyhow::{
-        anyhow,
-        Result,
+        state::cache::{Cache, MessageState},
     },
+    anyhow::{anyhow, Result},
     pythnet_sdk::{
         accumulators::{
-            merkle::{
-                MerklePath,
-                MerkleTree,
-            },
+            merkle::{MerklePath, MerkleTree},
             Accumulator,
         },
         hashers::keccak256_160::Keccak160,
         wire::{
             to_vec,
-            v1::{
-                AccumulatorUpdateData,
-                MerklePriceUpdate,
-                Proof,
-                WormholeMerkleRoot,
-            },
+            v1::{AccumulatorUpdateData, MerklePriceUpdate, Proof, WormholeMerkleRoot},
         },
     },
 };
@@ -43,28 +25,28 @@ pub const MAX_MESSAGE_IN_SINGLE_UPDATE_DATA: usize = 255;
 #[derive(Clone, PartialEq, Debug)]
 pub struct WormholeMerkleState {
     pub root: WormholeMerkleRoot,
-    pub vaa:  VaaBytes,
+    pub vaa: VaaBytes,
 }
 
 #[derive(Clone, PartialEq, Debug)]
 pub struct WormholeMerkleMessageProof {
     pub proof: MerklePath<Keccak160>,
-    pub vaa:   VaaBytes,
+    pub vaa: VaaBytes,
 }
 
 #[derive(Clone, PartialEq, Debug)]
 pub struct RawMessageWithMerkleProof {
-    pub slot:        Slot,
+    pub slot: Slot,
     pub raw_message: RawMessage,
-    pub proof:       WormholeMerkleMessageProof,
+    pub proof: WormholeMerkleMessageProof,
 }
 
 impl From<MessageState> for RawMessageWithMerkleProof {
     fn from(message_state: MessageState) -> Self {
         Self {
-            slot:        message_state.slot,
+            slot: message_state.slot,
             raw_message: message_state.raw_message,
-            proof:       message_state.proof_set.wormhole_merkle_proof,
+            proof: message_state.proof_set.wormhole_merkle_proof,
         }
     }
 }
@@ -104,7 +86,7 @@ pub fn construct_message_states_proofs(
         .iter()
         .map(|m| {
             Ok(WormholeMerkleMessageProof {
-                vaa:   wormhole_merkle_state.vaa.clone(),
+                vaa: wormhole_merkle_state.vaa.clone(),
                 proof: merkle_acc
                     .prove(m.as_ref())
                     .ok_or(anyhow!("Failed to prove message"))?,
@@ -126,14 +108,14 @@ pub fn construct_update_data(mut messages: Vec<RawMessageWithMerkleProof>) -> Re
         let vaa = message.proof.vaa;
         let mut updates = vec![MerklePriceUpdate {
             message: message.raw_message.into(),
-            proof:   message.proof.proof,
+            proof: message.proof.proof,
         }];
 
         while updates.len() < MAX_MESSAGE_IN_SINGLE_UPDATE_DATA {
             if let Some(message) = iter.next_if(|m| m.slot == slot) {
                 updates.push(MerklePriceUpdate {
                     message: message.raw_message.into(),
-                    proof:   message.proof.proof,
+                    proof: message.proof.proof,
                 });
             } else {
                 break;
@@ -162,10 +144,7 @@ mod test {
     use {
         super::*,
         pythnet_sdk::{
-            messages::{
-                Message,
-                PriceFeedMessage,
-            },
+            messages::{Message, PriceFeedMessage},
             wire::from_slice,
         },
     };
@@ -174,19 +153,19 @@ mod test {
         slot_and_pubtime: u64,
     ) -> RawMessageWithMerkleProof {
         let price_feed_message = Message::PriceFeedMessage(PriceFeedMessage {
-            conf:              0,
-            price:             0,
-            feed_id:           [0; 32],
-            exponent:          0,
-            ema_conf:          0,
-            ema_price:         0,
-            publish_time:      slot_and_pubtime as i64,
+            conf: 0,
+            price: 0,
+            feed_id: [0; 32],
+            exponent: 0,
+            ema_conf: 0,
+            ema_price: 0,
+            publish_time: slot_and_pubtime as i64,
             prev_publish_time: 0,
         });
         RawMessageWithMerkleProof {
-            slot:        slot_and_pubtime,
-            proof:       WormholeMerkleMessageProof {
-                vaa:   vec![],
+            slot: slot_and_pubtime,
+            proof: WormholeMerkleMessageProof {
+                vaa: vec![],
                 proof: MerklePath::default(),
             },
             raw_message: to_vec::<_, byteorder::BE>(&price_feed_message).unwrap(),

+ 3 - 9
apps/hermes/server/src/state/benchmarks.rs

@@ -2,18 +2,12 @@
 
 use {
     super::{
-        aggregate::{
-            PriceFeedsWithUpdateData,
-            UnixTimestamp,
-        },
+        aggregate::{PriceFeedsWithUpdateData, UnixTimestamp},
         State,
     },
     crate::api::types::PriceUpdate,
     anyhow::Result,
-    base64::{
-        engine::general_purpose::STANDARD as base64_standard_engine,
-        Engine as _,
-    },
+    base64::{engine::general_purpose::STANDARD as base64_standard_engine, Engine as _},
     pyth_sdk::PriceIdentifier,
     reqwest::Url,
     serde::Deserialize,
@@ -32,7 +26,7 @@ enum BlobEncoding {
 #[derive(Deserialize, Debug, Clone)]
 struct BinaryBlob {
     pub encoding: BlobEncoding,
-    pub data:     Vec<String>,
+    pub data: Vec<String>,
 }
 
 impl TryFrom<BinaryBlob> for Vec<Vec<u8>> {

+ 25 - 47
apps/hermes/server/src/state/cache.rs

@@ -1,30 +1,14 @@
 use {
     super::State,
     crate::state::aggregate::{
-        wormhole_merkle::WormholeMerkleState,
-        AccumulatorMessages,
-        ProofSet,
-        RawMessage,
-        RequestTime,
-        Slot,
-        UnixTimestamp,
-    },
-    anyhow::{
-        anyhow,
-        Result,
+        wormhole_merkle::WormholeMerkleState, AccumulatorMessages, ProofSet, RawMessage,
+        RequestTime, Slot, UnixTimestamp,
     },
+    anyhow::{anyhow, Result},
     futures::future::join_all,
-    pythnet_sdk::messages::{
-        FeedId,
-        Message,
-        MessageType,
-    },
+    pythnet_sdk::messages::{FeedId, Message, MessageType},
     std::{
-        collections::{
-            BTreeMap,
-            HashMap,
-            HashSet,
-        },
+        collections::{BTreeMap, HashMap, HashSet},
         sync::Arc,
     },
     strum::IntoEnumIterator,
@@ -34,26 +18,26 @@ use {
 #[derive(Clone, PartialEq, Eq, Debug, Hash)]
 pub struct MessageStateKey {
     pub feed_id: FeedId,
-    pub type_:   MessageType,
+    pub type_: MessageType,
 }
 
 #[derive(Clone, PartialEq, Eq, Debug, PartialOrd, Ord)]
 pub struct MessageStateTime {
     pub publish_time: UnixTimestamp,
-    pub slot:         Slot,
+    pub slot: Slot,
 }
 
 #[derive(Clone, PartialEq, Debug)]
 pub struct MessageState {
-    pub slot:        Slot,
-    pub message:     Message,
+    pub slot: Slot,
+    pub message: Message,
     /// The raw updated message.
     ///
     /// We need to store the raw message binary because the Message
     /// struct might lose some data due to its support for forward
     /// compatibility.
     pub raw_message: RawMessage,
-    pub proof_set:   ProofSet,
+    pub proof_set: ProofSet,
     pub received_at: UnixTimestamp,
 }
 
@@ -61,14 +45,14 @@ impl MessageState {
     pub fn time(&self) -> MessageStateTime {
         MessageStateTime {
             publish_time: self.message.publish_time(),
-            slot:         self.slot,
+            slot: self.slot,
         }
     }
 
     pub fn key(&self) -> MessageStateKey {
         MessageStateKey {
             feed_id: self.message.feed_id(),
-            type_:   self.message.clone().into(),
+            type_: self.message.clone().into(),
         }
     }
 
@@ -107,19 +91,19 @@ type MessageCache = Arc<RwLock<HashMap<MessageStateKey, BTreeMap<MessageStateTim
 
 /// A collection of caches for various program state.
 pub struct CacheState {
-    accumulator_messages_cache:  AccumulatorMessagesCache,
+    accumulator_messages_cache: AccumulatorMessagesCache,
     wormhole_merkle_state_cache: WormholeMerkleStateCache,
-    message_cache:               MessageCache,
-    cache_size:                  u64,
+    message_cache: MessageCache,
+    cache_size: u64,
 }
 
 impl CacheState {
     pub fn new(size: u64) -> Self {
         Self {
-            accumulator_messages_cache:  Arc::new(RwLock::new(BTreeMap::new())),
+            accumulator_messages_cache: Arc::new(RwLock::new(BTreeMap::new())),
             wormhole_merkle_state_cache: Arc::new(RwLock::new(BTreeMap::new())),
-            message_cache:               Arc::new(RwLock::new(HashMap::new())),
-            cache_size:                  size,
+            message_cache: Arc::new(RwLock::new(HashMap::new())),
+            cache_size: size,
         }
     }
 }
@@ -228,7 +212,7 @@ where
             message_types.into_iter().map(move |message_type| {
                 let key = MessageStateKey {
                     feed_id: id,
-                    type_:   message_type,
+                    type_: message_type,
                 };
                 retrieve_message_state(self.into(), key, request_time.clone())
             })
@@ -294,7 +278,7 @@ async fn retrieve_message_state(
 
                     let lookup_time = MessageStateTime {
                         publish_time: time,
-                        slot:         0,
+                        slot: 0,
                     };
 
                     // Get the first element that is greater than or equal to the lookup time.
@@ -323,16 +307,11 @@ async fn retrieve_message_state(
 mod test {
     use {
         super::*,
-        crate::state::{
-            aggregate::wormhole_merkle::WormholeMerkleMessageProof,
-            test::setup_state,
-        },
+        crate::state::{aggregate::wormhole_merkle::WormholeMerkleMessageProof, test::setup_state},
         pyth_sdk::UnixTimestamp,
         pythnet_sdk::{
-            accumulators::merkle::MerklePath,
-            hashers::keccak256_160::Keccak160,
-            messages::PriceFeedMessage,
-            wire::v1::WormholeMerkleRoot,
+            accumulators::merkle::MerklePath, hashers::keccak256_160::Keccak160,
+            messages::PriceFeedMessage, wire::v1::WormholeMerkleRoot,
         },
     };
 
@@ -357,7 +336,7 @@ mod test {
             received_at: publish_time,
             proof_set: ProofSet {
                 wormhole_merkle_proof: WormholeMerkleMessageProof {
-                    vaa:   vec![],
+                    vaa: vec![],
                     proof: MerklePath::<Keccak160>::new(vec![]),
                 },
             },
@@ -593,7 +572,6 @@ mod test {
         );
     }
 
-
     #[tokio::test]
     pub async fn test_store_and_retrieve_first_after_message_state_fails_for_past_time() {
         // Initialize state with a cache size of 2 per key.
@@ -771,7 +749,7 @@ mod test {
 
     pub fn create_empty_wormhole_merkle_state_at_slot(slot: Slot) -> WormholeMerkleState {
         WormholeMerkleState {
-            vaa:  vec![],
+            vaa: vec![],
             root: WormholeMerkleRoot {
                 slot,
                 root: [0; 20],

+ 1 - 4
apps/hermes/server/src/state/metrics.rs

@@ -2,10 +2,7 @@ use {
     super::State,
     prometheus_client::{
         encoding::text::encode,
-        registry::{
-            Metric,
-            Registry,
-        },
+        registry::{Metric, Registry},
     },
     tokio::sync::RwLock,
 };

+ 1 - 5
apps/hermes/server/src/state/price_feeds_metadata.rs

@@ -1,9 +1,6 @@
 use {
     crate::{
-        api::types::{
-            AssetType,
-            PriceFeedMetadata,
-        },
+        api::types::{AssetType, PriceFeedMetadata},
         state::State,
     },
     anyhow::Result,
@@ -66,7 +63,6 @@ where
         Ok(())
     }
 
-
     async fn get_price_feeds_metadata(
         &self,
         query: Option<String>,

+ 10 - 35
apps/hermes/server/src/state/wormhole.rs

@@ -1,51 +1,26 @@
 use {
     super::{
-        aggregate::{
-            Aggregates,
-            Update,
-        },
+        aggregate::{Aggregates, Update},
         State,
     },
     crate::network::wormhole::GuardianSet,
-    anyhow::{
-        anyhow,
-        ensure,
-        Result,
-    },
+    anyhow::{anyhow, ensure, Result},
     chrono::DateTime,
     pythnet_sdk::{
-        wire::v1::{
-            WormholeMessage,
-            WormholePayload,
-        },
+        wire::v1::{WormholeMessage, WormholePayload},
         ACCUMULATOR_EMITTER_ADDRESS,
     },
     secp256k1::{
-        ecdsa::{
-            RecoverableSignature,
-            RecoveryId,
-        },
-        Message,
-        Secp256k1,
+        ecdsa::{RecoverableSignature, RecoveryId},
+        Message, Secp256k1,
     },
     serde_wormhole::RawMessage,
-    sha3::{
-        Digest,
-        Keccak256,
-    },
-    std::collections::{
-        BTreeMap,
-        BTreeSet,
-    },
+    sha3::{Digest, Keccak256},
+    std::collections::{BTreeMap, BTreeSet},
     tokio::sync::RwLock,
     wormhole_sdk::{
-        vaa::{
-            Body,
-            Header,
-        },
-        Address,
-        Chain,
-        Vaa,
+        vaa::{Body, Header},
+        Address, Chain, Vaa,
     },
 };
 
@@ -71,7 +46,7 @@ impl WormholeState {
     pub fn new() -> Self {
         Self {
             observed_vaa_seqs: RwLock::new(BTreeSet::new()),
-            guardian_set:      RwLock::new(BTreeMap::new()),
+            guardian_set: RwLock::new(BTreeMap::new()),
         }
     }
 }

+ 10 - 16
governance/remote_executor/cli/src/cli.rs

@@ -1,14 +1,8 @@
 //! CLI options
 use {
-    clap::{
-        Parser,
-        Subcommand,
-    },
+    clap::{Parser, Subcommand},
     remote_executor::state::governance_payload::CHAIN_ID_ARRAY,
-    solana_sdk::{
-        commitment_config::CommitmentConfig,
-        pubkey::Pubkey,
-    },
+    solana_sdk::{commitment_config::CommitmentConfig, pubkey::Pubkey},
 };
 
 #[derive(Parser, Debug)]
@@ -20,11 +14,11 @@ pub struct Cli {
     #[clap(long, default_value = "confirmed")]
     pub commitment: CommitmentConfig,
     #[clap(long, default_value = "pythnet", parse(try_from_str = parse_chain))]
-    pub chain:      u16,
+    pub chain: u16,
     #[clap(long, default_value = "https://pythnet.rpcpool.com/")]
-    pub rpc_url:    String,
+    pub rpc_url: String,
     #[clap(subcommand)]
-    pub action:     Action,
+    pub action: Action,
 }
 
 fn parse_chain(chain: &str) -> Result<u16, String> {
@@ -40,7 +34,7 @@ pub enum Action {
     #[clap(about = "Post a VAA and execute it through the remote executor")]
     PostAndExecute {
         #[clap(short = 'v', long = "vaa")]
-        vaa:     String,
+        vaa: String,
         #[clap(
             long,
             default_value = "~/.config/solana/id.json",
@@ -62,22 +56,22 @@ pub enum Action {
     #[clap(about = "Get set upgrade authority payload for squads-cli")]
     GetSetUpgradeAuthorityPayload {
         #[clap(short, long, help = "Current authority")]
-        current:    Pubkey,
+        current: Pubkey,
         #[clap(short, long, help = "New authority")]
-        new:        Pubkey,
+        new: Pubkey,
         #[clap(short, long, help = "Program id")]
         program_id: Pubkey,
     },
     #[clap(about = "Get upgrade program payload for squads-cli")]
     GetUpgradeProgramPayload {
         #[clap(short, long, help = "Current authority")]
-        authority:  Pubkey,
+        authority: Pubkey,
         #[clap(short, long, help = "Program id")]
         program_id: Pubkey,
         #[clap(short, long, help = "New buffer")]
         new_buffer: Pubkey,
         #[clap(short, long, help = "Spill address")]
-        spill:      Pubkey,
+        spill: Pubkey,
     },
     #[clap(about = "Map solana key to pythnet key")]
     MapKey {

+ 30 - 64
governance/remote_executor/cli/src/main.rs

@@ -2,75 +2,41 @@
 
 use {
     serde_wormhole::RawMessage,
-    wormhole_sdk::vaa::{
-        Body,
-        Header,
-        Vaa,
-    },
+    wormhole_sdk::vaa::{Body, Header, Vaa},
 };
 pub mod cli;
 use {
     anchor_client::{
         anchor_lang::{
-            AccountDeserialize,
-            AnchorDeserialize,
-            AnchorSerialize,
-            InstructionData as AnchorInstructionData,
-            Owner,
-            ToAccountMetas,
+            AccountDeserialize, AnchorDeserialize, AnchorSerialize,
+            InstructionData as AnchorInstructionData, Owner, ToAccountMetas,
         },
         solana_sdk::bpf_loader_upgradeable,
     },
     anyhow::Result,
     clap::Parser,
-    cli::{
-        Action,
-        Cli,
-    },
+    cli::{Action, Cli},
     remote_executor::{
         accounts::ExecutePostedVaa,
         state::{
-            governance_payload::{
-                ExecutorPayload,
-                GovernanceHeader,
-                InstructionData,
-            },
+            governance_payload::{ExecutorPayload, GovernanceHeader, InstructionData},
             posted_vaa::AnchorVaa,
         },
-        EXECUTOR_KEY_SEED,
-        ID,
-    },
-    solana_client::{
-        rpc_client::RpcClient,
-        rpc_config::RpcSendTransactionConfig,
+        EXECUTOR_KEY_SEED, ID,
     },
+    solana_client::{rpc_client::RpcClient, rpc_config::RpcSendTransactionConfig},
     solana_sdk::{
-        instruction::{
-            AccountMeta,
-            Instruction,
-        },
+        instruction::{AccountMeta, Instruction},
         pubkey::Pubkey,
-        signature::{
-            read_keypair_file,
-            Keypair,
-        },
+        signature::{read_keypair_file, Keypair},
         signer::Signer,
-        system_instruction::{self,},
+        system_instruction::{self},
         transaction::Transaction,
     },
     std::str::FromStr,
     wormhole_solana::{
-        instructions::{
-            post_message,
-            post_vaa,
-            verify_signatures_txs,
-            PostVAAData,
-        },
-        Account,
-        Config,
-        FeeCollector,
-        GuardianSet,
-        VAA as PostedVAA,
+        instructions::{post_message, post_vaa, verify_signatures_txs, PostVAAData},
+        Account, Config, FeeCollector, GuardianSet, VAA as PostedVAA,
     },
 };
 
@@ -119,15 +85,15 @@ fn main() -> Result<()> {
 
             // Post VAA
             let post_vaa_data = PostVAAData {
-                version:            header.version,
+                version: header.version,
                 guardian_set_index: header.guardian_set_index,
-                timestamp:          body.timestamp,
-                nonce:              body.nonce,
-                emitter_chain:      body.emitter_chain.into(),
-                emitter_address:    body.emitter_address.0,
-                sequence:           body.sequence,
-                consistency_level:  body.consistency_level,
-                payload:            body.payload.to_vec(),
+                timestamp: body.timestamp,
+                nonce: body.nonce,
+                emitter_chain: body.emitter_chain.into(),
+                emitter_address: body.emitter_address.0,
+                sequence: body.sequence,
+                consistency_level: body.consistency_level,
+                payload: body.payload.to_vec(),
             };
 
             process_transaction(
@@ -178,7 +144,7 @@ fn main() -> Result<()> {
             )
             .0;
             let payload = ExecutorPayload {
-                header:       GovernanceHeader::executor_governance_header(cli.chain),
+                header: GovernanceHeader::executor_governance_header(cli.chain),
                 instructions: vec![InstructionData::from(&system_instruction::transfer(
                     &executor_key,
                     &payer.pubkey(),
@@ -210,7 +176,7 @@ fn main() -> Result<()> {
         }
         Action::GetTestPayload {} => {
             let payload = ExecutorPayload {
-                header:       GovernanceHeader::executor_governance_header(cli.chain),
+                header: GovernanceHeader::executor_governance_header(cli.chain),
                 instructions: vec![],
             }
             .try_to_vec()?;
@@ -237,7 +203,7 @@ fn main() -> Result<()> {
             instruction.accounts[2].is_signer = true; // Require signature of new authority for safety
             println!("New authority : {:}", instruction.accounts[2].pubkey);
             let payload = ExecutorPayload {
-                header:       GovernanceHeader::executor_governance_header(cli.chain),
+                header: GovernanceHeader::executor_governance_header(cli.chain),
                 instructions: vec![InstructionData::from(&instruction)],
             }
             .try_to_vec()?;
@@ -259,7 +225,7 @@ fn main() -> Result<()> {
                 instruction.accounts[3].pubkey
             );
             let payload = ExecutorPayload {
-                header:       GovernanceHeader::executor_governance_header(cli.chain),
+                header: GovernanceHeader::executor_governance_header(cli.chain),
                 instructions: vec![InstructionData::from(&instruction)],
             }
             .try_to_vec()?;
@@ -338,8 +304,8 @@ pub fn get_execute_instruction(
     .0;
 
     account_metas.push(AccountMeta {
-        pubkey:      executor_key,
-        is_signer:   false,
+        pubkey: executor_key,
+        is_signer: false,
         is_writable: true,
     });
 
@@ -347,8 +313,8 @@ pub fn get_execute_instruction(
     for instruction in executor_payload.instructions {
         // Push program_id
         account_metas.push(AccountMeta {
-            pubkey:      instruction.program_id,
-            is_signer:   false,
+            pubkey: instruction.program_id,
+            is_signer: false,
             is_writable: false,
         });
         // Push other accounts
@@ -361,7 +327,7 @@ pub fn get_execute_instruction(
 
     Ok(Instruction {
         program_id: ID,
-        accounts:   account_metas,
-        data:       remote_executor::instruction::ExecutePostedVaa.data(),
+        accounts: account_metas,
+        data: remote_executor::instruction::ExecutePostedVaa.data(),
     })
 }

+ 7 - 20
governance/remote_executor/programs/remote-executor/src/lib.rs

@@ -3,20 +3,10 @@
 #![allow(clippy::result_large_err)]
 
 use {
-    anchor_lang::{
-        prelude::*,
-        solana_program::borsh::get_packed_len,
-        system_program,
-    },
+    anchor_lang::{prelude::*, solana_program::borsh::get_packed_len, system_program},
     error::ExecutorError,
-    state::{
-        claim_record::ClaimRecord,
-        posted_vaa::AnchorVaa,
-    },
-    wormhole_sdk::Chain::{
-        self,
-        Solana,
-    },
+    state::{claim_record::ClaimRecord, posted_vaa::AnchorVaa},
+    wormhole_sdk::Chain::{self, Solana},
 };
 
 mod error;
@@ -33,10 +23,7 @@ pub mod remote_executor {
     use {
         super::*,
         crate::state::governance_payload::ExecutorPayload,
-        anchor_lang::solana_program::{
-            instruction::Instruction,
-            program::invoke_signed,
-        },
+        anchor_lang::solana_program::{instruction::Instruction, program::invoke_signed},
     };
 
     pub fn execute_posted_vaa(ctx: Context<ExecutePostedVaa>) -> Result<()> {
@@ -74,12 +61,12 @@ pub const CLAIM_RECORD_SEED: &str = "CLAIM_RECORD";
 #[derive(Accounts)]
 pub struct ExecutePostedVaa<'info> {
     #[account(mut)]
-    pub payer:          Signer<'info>,
+    pub payer: Signer<'info>,
     #[account(constraint = Chain::from(posted_vaa.emitter_chain) == Solana @ ExecutorError::EmitterChainNotSolana, constraint = posted_vaa.sequence > claim_record.sequence @ExecutorError::NonIncreasingSequence, constraint = (&posted_vaa.magic == b"vaa" || &posted_vaa.magic == b"msg" || &posted_vaa.magic == b"msu") @ExecutorError::PostedVaaHeaderWrongMagicNumber )]
-    pub posted_vaa:     Account<'info, AnchorVaa>,
+    pub posted_vaa: Account<'info, AnchorVaa>,
     /// The reason claim_record has different seeds than executor_key is that executor key might need to pay in the CPI, so we want it to be a native wallet
     #[account(init_if_needed, space = 8 + get_packed_len::<ClaimRecord>(), payer=payer, seeds = [CLAIM_RECORD_SEED.as_bytes(), &posted_vaa.emitter_address], bump)]
-    pub claim_record:   Account<'info, ClaimRecord>,
+    pub claim_record: Account<'info, ClaimRecord>,
     pub system_program: Program<'info, System>,
     // Additional accounts passed to the instruction will be passed down to the CPIs. Very importantly executor_key needs to be passed as it will be the signer of the CPIs.
     // Below is the "anchor specification" of that account

+ 1 - 4
governance/remote_executor/programs/remote-executor/src/state/claim_record.rs

@@ -1,9 +1,6 @@
 use anchor_lang::{
     account,
-    prelude::{
-        borsh::BorshSchema,
-        *,
-    },
+    prelude::{borsh::BorshSchema, *},
 };
 
 #[account]

+ 24 - 38
governance/remote_executor/programs/remote-executor/src/state/governance_payload.rs

@@ -1,15 +1,8 @@
 use {
     crate::error::ExecutorError,
-    anchor_lang::{
-        prelude::*,
-        solana_program::instruction::Instruction,
-    },
+    anchor_lang::{prelude::*, solana_program::instruction::Instruction},
     boolinator::Boolinator,
-    std::{
-        io::ErrorKind,
-        mem::size_of,
-        ops::Deref,
-    },
+    std::{io::ErrorKind, mem::size_of, ops::Deref},
 };
 
 pub const MAGIC_NUMBER: u32 = 0x4d475450; // Reverse order of the solidity contract because borsh uses little endian numbers (the solidity contract uses 0x5054474d)
@@ -76,9 +69,9 @@ pub enum Action {
 #[derive(AnchorDeserialize, AnchorSerialize, Eq, PartialEq, Debug)]
 pub struct GovernanceHeader {
     pub magic_number: u32,
-    pub module:       Module,
-    pub action:       Action,
-    pub chain:        BigEndianU16,
+    pub module: Module,
+    pub action: Action,
+    pub chain: BigEndianU16,
 }
 
 impl GovernanceHeader {
@@ -86,9 +79,9 @@ impl GovernanceHeader {
     pub fn executor_governance_header(chain: u16) -> Self {
         Self {
             magic_number: MAGIC_NUMBER,
-            module:       Module::Executor,
-            action:       Action::ExecutePostedVaa,
-            chain:        BigEndianU16 { value: chain },
+            module: Module::Executor,
+            action: Action::ExecutePostedVaa,
+            chain: BigEndianU16 { value: chain },
         }
     }
 }
@@ -133,18 +126,18 @@ pub struct InstructionData {
     /// Pubkey of the instruction processor that executes this instruction
     pub program_id: Pubkey,
     /// Metadata for what accounts should be passed to the instruction processor
-    pub accounts:   Vec<AccountMetaData>,
+    pub accounts: Vec<AccountMetaData>,
     /// Opaque data passed to the instruction processor
-    pub data:       Vec<u8>,
+    pub data: Vec<u8>,
 }
 
 /// Account metadata used to define Instructions
 #[derive(Clone, Debug, PartialEq, Eq, AnchorDeserialize, AnchorSerialize)]
 pub struct AccountMetaData {
     /// An account's public key
-    pub pubkey:      Pubkey,
+    pub pubkey: Pubkey,
     /// True if an Instruction requires a Transaction signature matching `pubkey`.
-    pub is_signer:   bool,
+    pub is_signer: bool,
     /// True if the `pubkey` can be loaded as a read-write account.
     pub is_writable: bool,
 }
@@ -153,16 +146,16 @@ impl From<&InstructionData> for Instruction {
     fn from(instruction: &InstructionData) -> Self {
         Instruction {
             program_id: instruction.program_id,
-            accounts:   instruction
+            accounts: instruction
                 .accounts
                 .iter()
                 .map(|a| AccountMeta {
-                    pubkey:      a.pubkey,
-                    is_signer:   a.is_signer,
+                    pubkey: a.pubkey,
+                    is_signer: a.is_signer,
                     is_writable: a.is_writable,
                 })
                 .collect(),
-            data:       instruction.data.clone(),
+            data: instruction.data.clone(),
         }
     }
 }
@@ -171,16 +164,16 @@ impl From<&Instruction> for InstructionData {
     fn from(instruction: &Instruction) -> Self {
         InstructionData {
             program_id: instruction.program_id,
-            accounts:   instruction
+            accounts: instruction
                 .accounts
                 .iter()
                 .map(|a| AccountMetaData {
-                    pubkey:      a.pubkey,
-                    is_signer:   a.is_signer,
+                    pubkey: a.pubkey,
+                    is_signer: a.is_signer,
                     is_writable: a.is_writable,
                 })
                 .collect(),
-            data:       instruction.data.clone(),
+            data: instruction.data.clone(),
         }
     }
 }
@@ -207,18 +200,11 @@ pub mod tests {
         super::ExecutorPayload,
         crate::{
             error::ExecutorError,
-            state::governance_payload::{
-                InstructionData,
-                CHAIN_ID,
-            },
+            state::governance_payload::{InstructionData, CHAIN_ID},
         },
         anchor_lang::{
-            prelude::{
-                Pubkey,
-                *,
-            },
-            AnchorDeserialize,
-            AnchorSerialize,
+            prelude::{Pubkey, *},
+            AnchorDeserialize, AnchorSerialize,
         },
     };
 
@@ -226,7 +212,7 @@ pub mod tests {
     fn test_check_deserialization_serialization() {
         // No instructions
         let payload = ExecutorPayload {
-            header:       super::GovernanceHeader::executor_governance_header(CHAIN_ID),
+            header: super::GovernanceHeader::executor_governance_header(CHAIN_ID),
             instructions: vec![],
         };
 

+ 2 - 6
governance/remote_executor/programs/remote-executor/src/state/posted_vaa.rs

@@ -1,10 +1,6 @@
 use {
     anchor_lang::prelude::*,
-    std::{
-        io::Write,
-        ops::Deref,
-        str::FromStr,
-    },
+    std::{io::Write, ops::Deref, str::FromStr},
     wormhole_solana::VAA,
 };
 
@@ -65,5 +61,5 @@ impl Deref for AnchorVaa {
 #[derive(Clone, AnchorDeserialize, AnchorSerialize)]
 pub struct AnchorVaa {
     pub magic: [u8; 3],
-    pub vaa:   VAA,
+    pub vaa: VAA,
 }

+ 29 - 59
governance/remote_executor/programs/remote-executor/src/tests/executor_simulator.rs

@@ -3,61 +3,31 @@ use {
         error::ExecutorError,
         state::{
             claim_record::ClaimRecord,
-            governance_payload::{
-                ExecutorPayload,
-                GovernanceHeader,
-                InstructionData,
-                CHAIN_ID,
-            },
+            governance_payload::{ExecutorPayload, GovernanceHeader, InstructionData, CHAIN_ID},
             posted_vaa::AnchorVaa,
         },
-        CLAIM_RECORD_SEED,
-        EXECUTOR_KEY_SEED,
+        CLAIM_RECORD_SEED, EXECUTOR_KEY_SEED,
     },
     anchor_lang::{
-        prelude::{
-            AccountMeta,
-            ProgramError,
-            Pubkey,
-            Rent,
-            UpgradeableLoaderState,
-        },
+        prelude::{AccountMeta, ProgramError, Pubkey, Rent, UpgradeableLoaderState},
         solana_program::hash::Hash,
-        AccountDeserialize,
-        AnchorDeserialize,
-        AnchorSerialize,
-        InstructionData as AnchorInstructionData,
-        Key,
-        Owner,
-        ToAccountMetas,
+        AccountDeserialize, AnchorDeserialize, AnchorSerialize,
+        InstructionData as AnchorInstructionData, Key, Owner, ToAccountMetas,
     },
     solana_program_test::{
-        read_file,
-        BanksClient,
-        BanksClientError,
-        ProgramTest,
-        ProgramTestBanksClientExt,
+        read_file, BanksClient, BanksClientError, ProgramTest, ProgramTestBanksClientExt,
     },
     solana_sdk::{
         account::Account,
         bpf_loader_upgradeable,
-        instruction::{
-            Instruction,
-            InstructionError,
-        },
+        instruction::{Instruction, InstructionError},
         signature::Keypair,
         signer::Signer,
         stake_history::Epoch,
         system_instruction,
-        transaction::{
-            Transaction,
-            TransactionError,
-        },
-    },
-    std::{
-        collections::HashMap,
-        path::Path,
+        transaction::{Transaction, TransactionError},
     },
+    std::{collections::HashMap, path::Path},
     wormhole_sdk::Chain,
     wormhole_solana::VAA,
 };
@@ -65,8 +35,8 @@ use {
 /// Bench for the tests, the goal of this struct is to be able to setup solana accounts before starting the local validator
 pub struct ExecutorBench {
     program_test: ProgramTest,
-    program_id:   Pubkey,
-    seqno:        HashMap<Pubkey, u64>,
+    program_id: Pubkey,
+    seqno: HashMap<Pubkey, u64>,
 }
 
 /// When passed to `add_vaa_account` modify the posted vaa in a way that makes the vaa invalid
@@ -100,7 +70,7 @@ impl ExecutorBench {
             programdata_address: programdata_key,
         };
         let programdata_deserialized = UpgradeableLoaderState::ProgramData {
-            slot:                      1,
+            slot: 1,
             upgrade_authority_address: Some(upgrade_authority_keypair.pubkey()),
         };
 
@@ -111,16 +81,16 @@ impl ExecutorBench {
         programdata_vec.append(&mut bpf_data);
 
         let program_account = Account {
-            lamports:   Rent::default().minimum_balance(program_vec.len()),
-            data:       program_vec,
-            owner:      bpf_loader_upgradeable::ID,
+            lamports: Rent::default().minimum_balance(program_vec.len()),
+            data: program_vec,
+            owner: bpf_loader_upgradeable::ID,
             executable: true,
             rent_epoch: Epoch::default(),
         };
         let programdata_account = Account {
-            lamports:   Rent::default().minimum_balance(programdata_vec.len()),
-            data:       programdata_vec,
-            owner:      bpf_loader_upgradeable::ID,
+            lamports: Rent::default().minimum_balance(programdata_vec.len()),
+            data: programdata_vec,
+            owner: bpf_loader_upgradeable::ID,
             executable: false,
             rent_epoch: Epoch::default(),
         };
@@ -172,7 +142,7 @@ impl ExecutorBench {
         };
 
         let payload = ExecutorPayload {
-            header:       GovernanceHeader::executor_governance_header(CHAIN_ID),
+            header: GovernanceHeader::executor_governance_header(CHAIN_ID),
             instructions: instructions.iter().map(InstructionData::from).collect(),
         };
 
@@ -180,7 +150,7 @@ impl ExecutorBench {
 
         let vaa = AnchorVaa {
             magic: *vaa_magic,
-            vaa:   VAA {
+            vaa: VAA {
                 vaa_version: 0,
                 consistency_level: 0,
                 vaa_time: 0,
@@ -235,10 +205,10 @@ impl ExecutorBench {
     }
 }
 pub struct ExecutorSimulator {
-    banks_client:   BanksClient,
-    payer:          Keypair,
+    banks_client: BanksClient,
+    payer: Keypair,
     last_blockhash: Hash,
-    program_id:     Pubkey,
+    program_id: Pubkey,
 }
 
 /// When passed to execute_posted_vaa, try to impersonate some of the accounts
@@ -336,8 +306,8 @@ impl ExecutorSimulator {
 
         // We need to add `executor_key` to the list of accounts
         account_metas.push(AccountMeta {
-            pubkey:      executor_key,
-            is_signer:   false,
+            pubkey: executor_key,
+            is_signer: false,
             is_writable: true,
         });
 
@@ -345,8 +315,8 @@ impl ExecutorSimulator {
         for instruction in executor_payload.instructions {
             // Push program_id
             account_metas.push(AccountMeta {
-                pubkey:      instruction.program_id,
-                is_signer:   false,
+                pubkey: instruction.program_id,
+                is_signer: false,
                 is_writable: false,
             });
             // Push other accounts
@@ -359,8 +329,8 @@ impl ExecutorSimulator {
 
         let instruction = Instruction {
             program_id: self.program_id,
-            accounts:   account_metas,
-            data:       crate::instruction::ExecutePostedVaa.data(),
+            accounts: account_metas,
+            data: crate::instruction::ExecutePostedVaa.data(),
         };
 
         self.process_ix(instruction, signers).await

+ 4 - 15
governance/remote_executor/programs/remote-executor/src/tests/test_adversarial.rs

@@ -1,21 +1,10 @@
 use {
-    super::executor_simulator::{
-        ExecutorAttack,
-        ExecutorBench,
-        VaaAttack,
-    },
+    super::executor_simulator::{ExecutorAttack, ExecutorBench, VaaAttack},
     crate::error::ExecutorError,
-    anchor_lang::prelude::{
-        ErrorCode,
-        ProgramError,
-        Pubkey,
-        Rent,
-    },
+    anchor_lang::prelude::{ErrorCode, ProgramError, Pubkey, Rent},
     solana_sdk::{
-        instruction::InstructionError,
-        native_token::LAMPORTS_PER_SOL,
-        system_instruction::transfer,
-        transaction::TransactionError,
+        instruction::InstructionError, native_token::LAMPORTS_PER_SOL,
+        system_instruction::transfer, transaction::TransactionError,
     },
 };
 

+ 4 - 15
governance/remote_executor/programs/remote-executor/src/tests/test_basic_instructions.rs

@@ -2,25 +2,14 @@ use {
     super::executor_simulator::ExecutorBench,
     crate::{
         error::ExecutorError,
-        tests::executor_simulator::{
-            ExecutorAttack,
-            VaaAttack,
-        },
+        tests::executor_simulator::{ExecutorAttack, VaaAttack},
     },
     anchor_lang::{
-        prelude::{
-            Pubkey,
-            Rent,
-        },
-        solana_program::{
-            system_instruction::create_account,
-            system_program,
-        },
+        prelude::{Pubkey, Rent},
+        solana_program::{system_instruction::create_account, system_program},
     },
     solana_sdk::{
-        native_token::LAMPORTS_PER_SOL,
-        signature::Keypair,
-        signer::Signer,
+        native_token::LAMPORTS_PER_SOL, signature::Keypair, signer::Signer,
         system_instruction::transfer,
     },
 };

+ 3 - 14
pythnet/message_buffer/programs/message_buffer/src/instructions/create_buffer.rs

@@ -1,20 +1,11 @@
 use {
     crate::{
-        instructions::is_uninitialized_account,
-        state::*,
-        MessageBufferError,
-        MESSAGE,
-        WHITELIST,
+        instructions::is_uninitialized_account, state::*, MessageBufferError, MESSAGE, WHITELIST,
     },
     anchor_lang::{
         prelude::*,
         solana_program::entrypoint::MAX_PERMITTED_DATA_INCREASE,
-        system_program::{
-            self,
-            Allocate,
-            Assign,
-            Transfer,
-        },
+        system_program::{self, Allocate, Assign, Transfer},
     },
 };
 
@@ -85,7 +76,6 @@ pub fn create_buffer<'info>(
     Ok(())
 }
 
-
 #[derive(Accounts)]
 pub struct CreateBuffer<'info> {
     #[account(
@@ -105,7 +95,6 @@ pub struct CreateBuffer<'info> {
     // remaining_accounts:  - [AccumulatorInput PDA]
 }
 
-
 impl<'info> CreateBuffer<'info> {
     /// Manually invoke transfer, allocate & assign ixs to create an account
     /// to handle situation where an account already has lamports
@@ -124,7 +113,7 @@ impl<'info> CreateBuffer<'info> {
                     system_program.to_account_info(),
                     Transfer {
                         from: payer.to_account_info(),
-                        to:   new_account_info.to_account_info(),
+                        to: new_account_info.to_account_info(),
                     },
                     seeds,
                 ),

+ 1 - 5
pythnet/message_buffer/programs/message_buffer/src/instructions/delete_buffer.rs

@@ -1,9 +1,5 @@
 use {
-    crate::{
-        state::*,
-        MESSAGE,
-        WHITELIST,
-    },
+    crate::{state::*, MESSAGE, WHITELIST},
     anchor_lang::prelude::*,
 };
 

+ 2 - 11
pythnet/message_buffer/programs/message_buffer/src/instructions/mod.rs

@@ -1,14 +1,5 @@
-use anchor_lang::{
-    prelude::*,
-    system_program,
-};
-pub use {
-    create_buffer::*,
-    delete_buffer::*,
-    put_all::*,
-    resize_buffer::*,
-};
-
+use anchor_lang::{prelude::*, system_program};
+pub use {create_buffer::*, delete_buffer::*, put_all::*, resize_buffer::*};
 
 mod create_buffer;
 mod delete_buffer;

+ 2 - 6
pythnet/message_buffer/programs/message_buffer/src/instructions/put_all.rs

@@ -1,12 +1,8 @@
 use {
-    crate::{
-        state::*,
-        MESSAGE,
-    },
+    crate::{state::*, MESSAGE},
     anchor_lang::prelude::*,
 };
 
-
 pub fn put_all<'info>(
     ctx: Context<'_, '_, '_, 'info, PutAll<'info>>,
     _base_account_key: Pubkey,
@@ -39,5 +35,5 @@ pub struct PutAll<'info> {
         seeds = [whitelist_verifier.cpi_caller_auth.key().as_ref(), MESSAGE.as_bytes(), base_account_key.as_ref()],
         bump = message_buffer.load()?.bump,
     )]
-    pub message_buffer:     AccountLoader<'info, MessageBuffer>,
+    pub message_buffer: AccountLoader<'info, MessageBuffer>,
 }

+ 1 - 7
pythnet/message_buffer/programs/message_buffer/src/instructions/resize_buffer.rs

@@ -1,14 +1,8 @@
 use {
-    crate::{
-        state::*,
-        MessageBufferError,
-        MESSAGE,
-        WHITELIST,
-    },
+    crate::{state::*, MessageBufferError, MESSAGE, WHITELIST},
     anchor_lang::prelude::*,
 };
 
-
 pub fn resize_buffer<'info>(
     ctx: Context<'_, '_, '_, 'info, ResizeBuffer<'info>>,
     allowed_program_auth: Pubkey,

+ 4 - 13
pythnet/message_buffer/programs/message_buffer/src/lib.rs

@@ -1,12 +1,8 @@
 pub mod instructions;
 mod state;
 
-
 use {
-    crate::{
-        MESSAGE,
-        WHITELIST,
-    },
+    crate::{MESSAGE, WHITELIST},
     anchor_lang::prelude::*,
     instructions::*,
     state::*,
@@ -18,7 +14,6 @@ declare_id!("7Vbmv1jt4vyuqBZcpYPpnVhrqVe5e6ZPb6JxDcffRHUM");
 pub mod message_buffer {
     use super::*;
 
-
     /// Initializes the whitelist and sets it's admin. Once initialized,
     /// the admin must sign all further changes to the whitelist.
     pub fn initialize(ctx: Context<Initialize>) -> Result<()> {
@@ -51,7 +46,6 @@ pub mod message_buffer {
         Ok(())
     }
 
-
     /// Put messages into the Accumulator. All messages put for the same
     /// `base_account_key` go into the same buffer PDA. The PDA's address is
     /// `[allowed_program_auth, MESSAGE, base_account_key]`, where `allowed_program_auth`
@@ -83,7 +77,6 @@ pub mod message_buffer {
         instructions::put_all(ctx, base_account_key, messages)
     }
 
-
     /// Initializes the buffer account with the `target_size`
     ///
     /// *`allowed_program_auth` - The whitelisted pubkey representing an
@@ -148,7 +141,7 @@ pub struct Initialize<'info> {
     pub admin: Signer<'info>,
 
     #[account(mut)]
-    pub payer:          Signer<'info>,
+    pub payer: Signer<'info>,
     #[account(
         init,
         payer = payer,
@@ -156,14 +149,13 @@ pub struct Initialize<'info> {
         bump,
         space = 8 + Whitelist::INIT_SPACE,
     )]
-    pub whitelist:      Account<'info, Whitelist>,
+    pub whitelist: Account<'info, Whitelist>,
     pub system_program: Program<'info, System>,
 }
 
-
 #[derive(Accounts)]
 pub struct UpdateWhitelist<'info> {
-    pub admin:     Signer<'info>,
+    pub admin: Signer<'info>,
     #[account(
         mut,
         seeds = [MESSAGE.as_bytes(), WHITELIST.as_bytes()],
@@ -173,7 +165,6 @@ pub struct UpdateWhitelist<'info> {
     pub whitelist: Account<'info, Whitelist>,
 }
 
-
 #[error_code]
 pub enum MessageBufferError {
     #[msg("CPI Caller not allowed")]

+ 9 - 30
pythnet/message_buffer/programs/message_buffer/src/state/message_buffer.rs

@@ -27,24 +27,23 @@ use anchor_lang::prelude::*;
 #[derive(InitSpace, Debug)]
 pub struct MessageBuffer {
     /* header */
-    pub bump:        u8, // 1
-    pub version:     u8, // 1
+    pub bump: u8,    // 1
+    pub version: u8, // 1
     // byte offset of accounts where data starts
     // e.g. account_info.data[offset + header_len]
-    pub header_len:  u16, // 2
+    pub header_len: u16, // 2
     /// endpoints of every message.
     /// ex: [10, 14]
     /// => msg1 = account_info.data[(header_len + 0)..(header_len + 10)]
     /// => msg2 = account_info.data[(header_len + 10)..(header_len + 14)]
     pub end_offsets: [u16; 255], // 510
 
-                          /* messages */
-                          //  not defined in struct since needs to support variable length
-                          //  and work with zero_copy
-                          // pub messages: [u8; accountInfo.data.len - header_len]
+                         /* messages */
+                         //  not defined in struct since needs to support variable length
+                         //  and work with zero_copy
+                         // pub messages: [u8; accountInfo.data.len - header_len]
 }
 
-
 impl MessageBuffer {
     // HEADER_LEN allows for append-only forward-compatibility for the header.
     // this is the number of bytes from the beginning of the account_info.data
@@ -72,7 +71,6 @@ impl MessageBuffer {
         self.end_offsets = [0u16; u8::MAX as usize];
     }
 
-
     /// `put_all` writes all the messages to the `AccumulatorInput` account
     /// and updates the `end_offsets` array.
     ///
@@ -124,10 +122,7 @@ mod test {
         bytemuck::bytes_of_mut,
         std::{
             io::Write,
-            mem::{
-                align_of,
-                size_of,
-            },
+            mem::{align_of, size_of},
         },
     };
 
@@ -157,7 +152,6 @@ mod test {
         let discriminator = &mut sighash("accounts", "MessageBuffer");
         let destination = &mut vec![0u8; destination_size];
 
-
         account_info_data.write_all(discriminator).unwrap();
         account_info_data
             .write_all(bytes_of_mut(message_buffer))
@@ -166,7 +160,6 @@ mod test {
         account_info_data.to_vec()
     }
 
-
     #[test]
     fn test_sizes_and_alignments() {
         let (message_buffer_size, message_buffer_align) =
@@ -193,7 +186,6 @@ mod test {
         assert_eq!(num_msgs, 2);
         assert_eq!(num_bytes, 5);
 
-
         assert_eq!(message_buffer.end_offsets[0], 2);
         assert_eq!(message_buffer.end_offsets[1], 5);
 
@@ -218,7 +210,6 @@ mod test {
         }
     }
 
-
     #[test]
     fn test_put_all_exceed_max() {
         let data = vec![vec![0u8; 9_718 - 2], vec![0u8], vec![0u8; 2]];
@@ -244,11 +235,9 @@ mod test {
         assert_eq!(message_buffer.end_offsets[0], 9_718 - 2);
         assert_eq!(message_buffer.end_offsets[1], 9_718 - 1);
 
-
         let message_buffer: &MessageBuffer =
             bytemuck::from_bytes(&account_info_data.as_slice()[8..header_len]);
 
-
         let iter = message_buffer.end_offsets.iter().take_while(|x| **x != 0);
         let mut start = header_len;
         let mut data_iter = data_bytes.iter();
@@ -284,14 +273,12 @@ mod test {
 
         let (num_msgs, num_bytes) = message_buffer.put_all_in_buffer(body_bytes, &data_bytes);
 
-
         assert_eq!(num_msgs, 3);
         assert_eq!(
             num_bytes,
             data_bytes[0..3].iter().map(|x| x.len()).sum::<usize>() as u16
         );
 
-
         let message_buffer: &MessageBuffer =
             bytemuck::from_bytes(&account_info_data.as_slice()[8..header_len]);
 
@@ -315,10 +302,7 @@ mod test {
 
     #[test]
     pub fn test_cursor_read() {
-        use byteorder::{
-            LittleEndian,
-            ReadBytesExt,
-        };
+        use byteorder::{LittleEndian, ReadBytesExt};
 
         let data = vec![vec![12, 34], vec![56, 78, 90]];
         let data_bytes: Vec<Vec<u8>> = data.into_iter().map(data_bytes).collect();
@@ -336,7 +320,6 @@ mod test {
         assert_eq!(message_buffer.end_offsets[0], 2);
         assert_eq!(message_buffer.end_offsets[1], 5);
 
-
         let mut cursor = std::io::Cursor::new(&account_info_data[10..]);
         let header_len = cursor.read_u16::<LittleEndian>().unwrap();
         println!("header_len: {}", header_len);
@@ -383,7 +366,6 @@ mod test {
 
         let (num_msgs, num_bytes) = message_buffer.put_all_in_buffer(body_bytes, &data_bytes);
 
-
         assert_eq!(num_msgs, u8::MAX as usize);
         assert_eq!(
             num_bytes,
@@ -393,7 +375,6 @@ mod test {
                 .sum::<usize>() as u16
         );
 
-
         let message_buffer: &MessageBuffer =
             bytemuck::from_bytes(&account_info_data.as_slice()[8..header_len]);
 
@@ -439,14 +420,12 @@ mod test {
 
         let (num_msgs, num_bytes) = message_buffer.put_all_in_buffer(body_bytes, &data_bytes);
 
-
         assert_eq!(num_msgs, 3);
         assert_eq!(
             num_bytes,
             data_bytes[0..3].iter().map(|x| x.len()).sum::<usize>() as u16
         );
 
-
         let message_buffer: &MessageBuffer =
             bytemuck::from_bytes(&account_info_data.as_slice()[8..header_len]);
 

+ 1 - 4
pythnet/message_buffer/programs/message_buffer/src/state/mod.rs

@@ -1,7 +1,4 @@
-pub use {
-    self::message_buffer::*,
-    whitelist::*,
-};
+pub use {self::message_buffer::*, whitelist::*};
 
 mod message_buffer;
 mod whitelist;

+ 3 - 7
pythnet/message_buffer/programs/message_buffer/src/state/whitelist.rs

@@ -1,9 +1,5 @@
 use {
-    crate::{
-        MessageBufferError,
-        MESSAGE,
-        WHITELIST,
-    },
+    crate::{MessageBufferError, MESSAGE, WHITELIST},
     anchor_lang::prelude::*,
 };
 
@@ -13,8 +9,8 @@ use {
 #[account]
 #[derive(InitSpace)]
 pub struct Whitelist {
-    pub bump:             u8,
-    pub admin:            Pubkey,
+    pub bump: u8,
+    pub admin: Pubkey,
     // This is used by the `#[derive(InitSpace)]`
     // to determine initial account size
     #[max_len(32)]

+ 13 - 29
pythnet/message_buffer/programs/mock-cpi-caller/src/instructions/add_price.rs

@@ -1,27 +1,14 @@
 use {
     crate::{
-        instructions::{
-            sighash,
-            ACCUMULATOR_UPDATER_IX_NAME,
-            UPD_PRICE_WRITE,
-        },
+        instructions::{sighash, ACCUMULATOR_UPDATER_IX_NAME, UPD_PRICE_WRITE},
         message::{
             get_schemas,
-            price::{
-                CompactPriceMessage,
-                FullPriceMessage,
-            },
+            price::{CompactPriceMessage, FullPriceMessage},
             AccumulatorSerializer,
         },
-        state::{
-            PriceAccount,
-            PythAccountType,
-        },
-    },
-    anchor_lang::{
-        prelude::*,
-        system_program,
+        state::{PriceAccount, PythAccountType},
     },
+    anchor_lang::{prelude::*, system_program},
     message_buffer::program::MessageBuffer as MessageBufferProgram,
 };
 
@@ -41,20 +28,17 @@ pub fn add_price<'info>(
 
         inputs.push(price_full_data);
 
-
         let price_compact_data =
             CompactPriceMessage::from(&**pyth_price_acct).accumulator_serialize()?;
         inputs.push(price_compact_data);
     }
 
-
     // Note: normally pyth oracle add_price wouldn't call emit_accumulator_inputs
     // since add_price doesn't actually add/update any price data we would
     // want included in the accumulator anyways. This is just for testing
     AddPrice::emit_messages(ctx, inputs)
 }
 
-
 impl<'info> AddPrice<'info> {
     /// Invoke message_buffer::put_all ix cpi call using solana
     pub fn emit_messages(
@@ -109,11 +93,11 @@ impl<'info> AddPrice<'info> {
 
 #[derive(AnchorSerialize, AnchorDeserialize, Clone, Debug, PartialEq, Eq)]
 pub struct AddPriceParams {
-    pub id:         u64,
-    pub price:      u64,
+    pub id: u64,
+    pub price: u64,
     pub price_expo: u64,
-    pub ema:        u64,
-    pub ema_expo:   u64,
+    pub ema: u64,
+    pub ema_expo: u64,
 }
 
 #[derive(Accounts)]
@@ -126,13 +110,13 @@ pub struct AddPrice<'info> {
         bump,
         space = 8 + PriceAccount::INIT_SPACE
     )]
-    pub pyth_price_account:     AccountLoader<'info, PriceAccount>,
+    pub pyth_price_account: AccountLoader<'info, PriceAccount>,
     #[account(mut)]
-    pub payer:                  Signer<'info>,
+    pub payer: Signer<'info>,
     /// also needed for accumulator_updater
-    pub system_program:         Program<'info, System>,
+    pub system_program: Program<'info, System>,
     /// CHECK: whitelist
-    pub accumulator_whitelist:  UncheckedAccount<'info>,
+    pub accumulator_whitelist: UncheckedAccount<'info>,
     /// PDA representing this program's authority
     /// to call the accumulator program
     #[account(
@@ -140,7 +124,7 @@ pub struct AddPrice<'info> {
         owner = system_program::System::id(),
         bump,
     )]
-    pub auth:                   SystemAccount<'info>,
+    pub auth: SystemAccount<'info>,
     pub message_buffer_program: Program<'info, MessageBufferProgram>,
     // Remaining Accounts
     // MessageBuffer PDA

+ 2 - 9
pythnet/message_buffer/programs/mock-cpi-caller/src/instructions/cpi_max_test.rs

@@ -1,13 +1,7 @@
 use {
     crate::{
-        instructions::{
-            UpdatePrice,
-            UpdatePriceParams,
-        },
-        message::{
-            price::DummyPriceMessage,
-            AccumulatorSerializer,
-        },
+        instructions::{UpdatePrice, UpdatePriceParams},
+        message::{price::DummyPriceMessage, AccumulatorSerializer},
     },
     anchor_lang::prelude::*,
 };
@@ -32,6 +26,5 @@ pub fn cpi_max_test<'info>(
     let input_len = inputs.iter().map(|x| x.len()).sum::<usize>();
     msg!("input_len: {}", input_len);
 
-
     UpdatePrice::emit_messages(ctx, inputs)
 }

+ 1 - 5
pythnet/message_buffer/programs/mock-cpi-caller/src/instructions/mod.rs

@@ -1,9 +1,5 @@
 use anchor_lang::solana_program::hash::hashv;
-pub use {
-    add_price::*,
-    cpi_max_test::*,
-    update_price::*,
-};
+pub use {add_price::*, cpi_max_test::*, update_price::*};
 
 mod add_price;
 mod cpi_max_test;

+ 9 - 22
pythnet/message_buffer/programs/mock-cpi-caller/src/instructions/update_price.rs

@@ -1,35 +1,24 @@
 use {
     crate::{
-        instructions::{
-            sighash,
-            ACCUMULATOR_UPDATER_IX_NAME,
-            UPD_PRICE_WRITE,
-        },
+        instructions::{sighash, ACCUMULATOR_UPDATER_IX_NAME, UPD_PRICE_WRITE},
         message::{
-            price::{
-                CompactPriceMessage,
-                FullPriceMessage,
-            },
+            price::{CompactPriceMessage, FullPriceMessage},
             AccumulatorSerializer,
         },
         state::PriceAccount,
     },
-    anchor_lang::{
-        prelude::*,
-        system_program,
-    },
+    anchor_lang::{prelude::*, system_program},
     message_buffer::program::MessageBuffer as MessageBufferProgram,
 };
 
 #[derive(AnchorSerialize, AnchorDeserialize, Clone, Debug, PartialEq, Eq)]
 pub struct UpdatePriceParams {
-    pub price:      u64,
+    pub price: u64,
     pub price_expo: u64,
-    pub ema:        u64,
-    pub ema_expo:   u64,
+    pub ema: u64,
+    pub ema_expo: u64,
 }
 
-
 #[derive(Accounts)]
 pub struct UpdatePrice<'info> {
     #[account(
@@ -41,15 +30,15 @@ pub struct UpdatePrice<'info> {
     ],
     bump,
     )]
-    pub pyth_price_account:     AccountLoader<'info, PriceAccount>,
+    pub pyth_price_account: AccountLoader<'info, PriceAccount>,
     /// CHECK: whitelist
-    pub accumulator_whitelist:  UncheckedAccount<'info>,
+    pub accumulator_whitelist: UncheckedAccount<'info>,
     #[account(
         seeds = [b"upd_price_write".as_ref(), message_buffer_program.key().as_ref()],
         owner = system_program::System::id(),
         bump,
     )]
-    pub auth:                   SystemAccount<'info>,
+    pub auth: SystemAccount<'info>,
     pub message_buffer_program: Program<'info, MessageBufferProgram>,
 }
 
@@ -69,13 +58,11 @@ pub fn update_price<'info>(
 
         inputs.push(price_full_data);
 
-
         let price_compact_data =
             CompactPriceMessage::from(&**pyth_price_acct).accumulator_serialize()?;
         inputs.push(price_compact_data);
     }
 
-
     UpdatePrice::emit_messages(ctx, inputs)
 }
 

+ 3 - 10
pythnet/message_buffer/programs/mock-cpi-caller/src/lib.rs

@@ -1,7 +1,4 @@
-use {
-    anchor_lang::prelude::*,
-    instructions::*,
-};
+use {anchor_lang::prelude::*, instructions::*};
 
 pub mod instructions;
 pub mod message;
@@ -39,19 +36,15 @@ pub mod mock_cpi_caller {
     }
 }
 
-
 #[cfg(test)]
 mod test {
-    use {
-        super::*,
-        anchor_lang::InstructionData,
-    };
+    use {super::*, anchor_lang::InstructionData};
 
     #[test]
     fn ix_discriminator() {
         let a = &(message_buffer::instruction::PutAll {
             base_account_key: anchor_lang::prelude::Pubkey::default(),
-            messages:         vec![],
+            messages: vec![],
         }
         .data()[..8]);
 

+ 2 - 3
pythnet/message_buffer/programs/mock-cpi-caller/src/message.rs

@@ -5,10 +5,10 @@ pub mod price;
 #[derive(Copy, Clone)]
 #[repr(u8)]
 pub enum MessageSchema {
-    Full    = 0,
+    Full = 0,
     Compact = 1,
     Minimal = 2,
-    Dummy   = 3,
+    Dummy = 3,
 }
 
 impl MessageSchema {
@@ -17,7 +17,6 @@ impl MessageSchema {
     }
 }
 
-
 pub fn get_schemas(account_type: PythAccountType) -> Vec<MessageSchema> {
     match account_type {
         PythAccountType::Price => vec![MessageSchema::Full, MessageSchema::Compact],

+ 21 - 30
pythnet/message_buffer/programs/mock-cpi-caller/src/message/price.rs

@@ -1,22 +1,18 @@
 use {
     crate::{
-        message::{
-            AccumulatorSerializer,
-            MessageSchema,
-        },
+        message::{AccumulatorSerializer, MessageSchema},
         state::PriceAccount,
     },
     anchor_lang::prelude::*,
     std::io::Write,
 };
 
-
 #[repr(C)]
 #[derive(Clone, Default, Debug, Eq, PartialEq)]
 pub struct MessageHeader {
-    pub schema:  u8,
+    pub schema: u8,
     pub version: u16,
-    pub size:    u32,
+    pub size: u32,
 }
 
 impl MessageHeader {
@@ -34,13 +30,12 @@ impl MessageHeader {
 #[repr(C)]
 #[derive(Clone, Default, Debug, Eq, PartialEq)]
 pub struct CompactPriceMessage {
-    pub header:     MessageHeader,
-    pub id:         u64,
-    pub price:      u64,
+    pub header: MessageHeader,
+    pub id: u64,
+    pub price: u64,
     pub price_expo: u64,
 }
 
-
 impl CompactPriceMessage {
     // size without header
     pub const SIZE: usize = 24;
@@ -62,24 +57,23 @@ impl AccumulatorSerializer for CompactPriceMessage {
 impl From<&PriceAccount> for CompactPriceMessage {
     fn from(other: &PriceAccount) -> Self {
         Self {
-            header:     MessageHeader::new(MessageSchema::Compact, Self::SIZE as u32),
-            id:         other.id,
-            price:      other.price,
+            header: MessageHeader::new(MessageSchema::Compact, Self::SIZE as u32),
+            id: other.id,
+            price: other.price,
             price_expo: other.price_expo,
         }
     }
 }
 
-
 #[repr(C)]
 #[derive(Clone, Default, Debug, Eq, PartialEq)]
 pub struct FullPriceMessage {
-    pub header:     MessageHeader,
-    pub id:         u64,
-    pub price:      u64,
+    pub header: MessageHeader,
+    pub id: u64,
+    pub price: u64,
     pub price_expo: u64,
-    pub ema:        u64,
-    pub ema_expo:   u64,
+    pub ema: u64,
+    pub ema_expo: u64,
 }
 
 impl FullPriceMessage {
@@ -89,12 +83,12 @@ impl FullPriceMessage {
 impl From<&PriceAccount> for FullPriceMessage {
     fn from(other: &PriceAccount) -> Self {
         Self {
-            header:     MessageHeader::new(MessageSchema::Full, Self::SIZE as u32),
-            id:         other.id,
-            price:      other.price,
+            header: MessageHeader::new(MessageSchema::Full, Self::SIZE as u32),
+            id: other.id,
+            price: other.price,
             price_expo: other.price_expo,
-            ema:        other.ema,
-            ema_expo:   other.ema_expo,
+            ema: other.ema,
+            ema_expo: other.ema_expo,
         }
     }
 }
@@ -114,27 +108,24 @@ impl AccumulatorSerializer for FullPriceMessage {
     }
 }
 
-
 #[repr(C)]
 #[derive(Clone, Debug, Eq, PartialEq)]
 pub struct DummyPriceMessage {
     pub header: MessageHeader,
-    pub data:   Vec<u8>,
+    pub data: Vec<u8>,
 }
 
-
 impl DummyPriceMessage {
     pub const SIZE: usize = 1017;
 
     pub fn new(msg_size: u16) -> Self {
         Self {
             header: MessageHeader::new(MessageSchema::Dummy, msg_size as u32),
-            data:   vec![0u8; msg_size as usize],
+            data: vec![0u8; msg_size as usize],
         }
     }
 }
 
-
 impl AccumulatorSerializer for DummyPriceMessage {
     fn accumulator_serialize(&self) -> Result<Vec<u8>> {
         let mut bytes = vec![];

+ 4 - 4
pythnet/message_buffer/programs/mock-cpi-caller/src/state/mod.rs

@@ -12,10 +12,10 @@ trait PythAccount {
 #[derive(Copy, Clone)]
 #[repr(u32)]
 pub enum PythAccountType {
-    Mapping     = 1,
-    Product     = 2,
-    Price       = 3,
-    Test        = 4,
+    Mapping = 1,
+    Product = 2,
+    Price = 3,
+    Test = 4,
     Permissions = 5,
 }
 impl PythAccountType {

+ 7 - 13
pythnet/message_buffer/programs/mock-cpi-caller/src/state/price.rs

@@ -1,13 +1,7 @@
 use {
     crate::{
-        instructions::{
-            AddPriceParams,
-            UpdatePriceParams,
-        },
-        state::{
-            PythAccount,
-            PythAccountType,
-        },
+        instructions::{AddPriceParams, UpdatePriceParams},
+        state::{PythAccount, PythAccountType},
     },
     anchor_lang::prelude::*,
 };
@@ -15,12 +9,12 @@ use {
 #[account(zero_copy)]
 #[derive(InitSpace)]
 pub struct PriceAccount {
-    pub id:         u64,
-    pub price:      u64,
+    pub id: u64,
+    pub price: u64,
     pub price_expo: u64,
-    pub ema:        u64,
-    pub ema_expo:   u64,
-    pub comp_:      [Pubkey; 32],
+    pub ema: u64,
+    pub ema_expo: u64,
+    pub comp_: [Pubkey; 32],
 }
 
 impl PriceAccount {

Algunos archivos no se mostraron porque demasiados archivos cambiaron en este cambio