Skip to content
This repository was archived by the owner on Jun 1, 2026. It is now read-only.
11 changes: 11 additions & 0 deletions crates/primitives/src/job_configuration.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
use serde::{Deserialize, Serialize};
use typeshare::typeshare;

#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
#[typeshare(swift = "Sendable")]
#[serde(rename_all = "camelCase")]
pub struct JobConfiguration {
pub initial_interval_ms: u32,
pub max_interval_ms: u32,
pub step_factor: f32,
}
2 changes: 2 additions & 0 deletions crates/primitives/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,8 @@ pub mod time;
pub use self::time::unix_timestamp;
pub mod transaction_state;
pub use self::transaction_state::TransactionState;
pub mod job_configuration;
pub use self::job_configuration::JobConfiguration;
pub mod username_status;
pub use self::username_status::UsernameStatus;
pub mod recent_activity_type;
Expand Down
3 changes: 2 additions & 1 deletion crates/primitives/src/swap/approval.rs
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,7 @@ pub struct SwapProviderData {
#[serde(rename_all = "camelCase")]
pub enum SwapStatus {
Pending,
InTransit,
Completed,
Failed,
}
Expand All @@ -109,7 +110,7 @@ impl SwapStatus {
match self {
SwapStatus::Completed => Some(TransactionState::Confirmed),
SwapStatus::Failed => Some(TransactionState::Failed),
SwapStatus::Pending => None,
SwapStatus::Pending | SwapStatus::InTransit => None,
}
}
}
3 changes: 2 additions & 1 deletion crates/primitives/src/transaction_update.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use crate::transaction_metadata_types::TransactionPerpetualMetadata;
use crate::transaction_metadata_types::{TransactionPerpetualMetadata, TransactionSwapMetadata};
use crate::transaction_state::TransactionState;
use num_bigint::BigInt;
use serde::{Deserialize, Serialize};
Expand Down Expand Up @@ -30,6 +30,7 @@ pub enum TransactionChange {
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub enum TransactionMetadata {
Perpetual(TransactionPerpetualMetadata),
Swap(TransactionSwapMetadata),
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
Expand Down
103 changes: 103 additions & 0 deletions gemstone/src/gateway/chain_factory.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
use super::{GatewayError, GemPreferences, PreferencesWrapper};
use crate::alien::{AlienProvider, new_alien_client};
use crate::network::JsonRpcClient;
use chain_traits::ChainTraits;
use gem_algorand::rpc::AlgorandClientIndexer;
use gem_algorand::rpc::client::AlgorandClient;
use gem_aptos::rpc::client::AptosClient;
use gem_bitcoin::rpc::client::BitcoinClient;
use gem_cardano::rpc::client::CardanoClient;
use gem_cosmos::rpc::client::CosmosClient;
use gem_evm::rpc::EthereumClient;
use gem_hypercore::rpc::client::HyperCoreClient;
use gem_near::rpc::client::NearClient;
use gem_polkadot::rpc::client::PolkadotClient;
use gem_solana::rpc::client::SolanaClient;
use gem_stellar::rpc::client::StellarClient;
use gem_sui::rpc::client::SuiClient;
use gem_ton::rpc::client::TonClient;
use gem_tron::rpc::{client::TronClient, trongrid::client::TronGridClient};
use gem_xrp::rpc::client::XRPClient;
use primitives::{BitcoinChain, Chain, EVMChain, chain_cosmos::CosmosChain};
use std::sync::Arc;

pub struct ChainClientFactory {
alien: Arc<dyn AlienProvider>,
preferences: Arc<dyn GemPreferences>,
secure_preferences: Arc<dyn GemPreferences>,
}

impl ChainClientFactory {
pub fn new(alien: Arc<dyn AlienProvider>, preferences: Arc<dyn GemPreferences>, secure_preferences: Arc<dyn GemPreferences>) -> Self {
Self {
alien,
preferences,
secure_preferences,
}
}

pub async fn create(&self, chain: Chain) -> Result<Arc<dyn ChainTraits>, GatewayError> {
let url = self.alien.get_endpoint(chain).map_err(|e| GatewayError::PlatformError { msg: e.to_string() })?;
self.create_with_url(chain, url).await
}

pub async fn create_with_url(&self, chain: Chain, url: String) -> Result<Arc<dyn ChainTraits>, GatewayError> {
let alien_client = new_alien_client(url, self.alien.clone());
match chain {
Chain::HyperCore => {
let preferences = Arc::new(PreferencesWrapper {
preferences: self.preferences.clone(),
});
let secure_preferences = Arc::new(PreferencesWrapper {
preferences: self.secure_preferences.clone(),
});
Ok(Arc::new(HyperCoreClient::new_with_preferences(alien_client, preferences, secure_preferences)))
}
Chain::Bitcoin | Chain::BitcoinCash | Chain::Litecoin | Chain::Doge | Chain::Zcash => {
Ok(Arc::new(BitcoinClient::new(alien_client, BitcoinChain::from_chain(chain).unwrap())))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

Using unwrap() here is risky. If a new chain is added to the match arm but is not supported by BitcoinChain::from_chain, the application will panic at runtime. It's safer to handle the potential error by returning a GatewayError::PlatformError.

Suggested change
Ok(Arc::new(BitcoinClient::new(alien_client, BitcoinChain::from_chain(chain).unwrap())))
Ok(Arc::new(BitcoinClient::new(alien_client, BitcoinChain::from_chain(chain).ok_or(GatewayError::PlatformError { msg: format!("Unsupported bitcoin chain: {:?}", chain) })?)))

}
Chain::Cardano => Ok(Arc::new(CardanoClient::new(alien_client))),
Chain::Stellar => Ok(Arc::new(StellarClient::new(alien_client))),
Chain::Sui => Ok(Arc::new(SuiClient::new(JsonRpcClient::new(alien_client.clone())))),
Chain::Xrp => Ok(Arc::new(XRPClient::new(JsonRpcClient::new(alien_client.clone())))),
Chain::Algorand => Ok(Arc::new(AlgorandClient::new(alien_client.clone(), AlgorandClientIndexer::new(alien_client.clone())))),
Chain::Near => Ok(Arc::new(NearClient::new(JsonRpcClient::new(alien_client.clone())))),
Chain::Aptos => Ok(Arc::new(AptosClient::new(alien_client))),
Chain::Cosmos | Chain::Osmosis | Chain::Celestia | Chain::Thorchain | Chain::Injective | Chain::Sei | Chain::Noble => {
Ok(Arc::new(CosmosClient::new(CosmosChain::from_chain(chain).unwrap(), alien_client)))
}
Chain::Ton => Ok(Arc::new(TonClient::new(alien_client))),
Chain::Tron => Ok(Arc::new(TronClient::new(alien_client.clone(), TronGridClient::new(alien_client.clone(), String::new())))),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

The TronGridClient is initialized with an empty string for the API key. This will likely lead to rate limiting or authentication errors when interacting with TronGrid. Consider making the API key configurable via preferences or environment variables.

Chain::Polkadot => Ok(Arc::new(PolkadotClient::new(alien_client))),
Chain::Solana => Ok(Arc::new(SolanaClient::new(JsonRpcClient::new(alien_client.clone())))),
Chain::Ethereum
| Chain::Arbitrum
| Chain::SmartChain
| Chain::Polygon
| Chain::Optimism
| Chain::Base
| Chain::AvalancheC
| Chain::OpBNB
| Chain::Fantom
| Chain::Gnosis
| Chain::Manta
| Chain::Blast
| Chain::ZkSync
| Chain::Linea
| Chain::Mantle
| Chain::Celo
| Chain::World
| Chain::Sonic
| Chain::SeiEvm
| Chain::Abstract
| Chain::Berachain
| Chain::Ink
| Chain::Unichain
| Chain::Hyperliquid
| Chain::Plasma
| Chain::Monad
| Chain::XLayer
| Chain::Stable => Ok(Arc::new(EthereumClient::new(JsonRpcClient::new(alien_client), EVMChain::from_chain(chain).unwrap()))),
}
}
}
10 changes: 10 additions & 0 deletions gemstone/src/gateway/error.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use crate::alien::AlienError;
use crate::transaction_state::TransactionStatusError;
use gem_jsonrpc::types::{ERROR_CLIENT_ERROR, JsonRpcError};
use std::{error::Error, fmt::Display};

Expand Down Expand Up @@ -29,6 +30,15 @@ impl From<uniffi::UnexpectedUniFFICallbackError> for GatewayError {
}
}

impl From<TransactionStatusError> for GatewayError {
fn from(err: TransactionStatusError) -> Self {
match err {
TransactionStatusError::NetworkError(msg) => Self::NetworkError { msg },
TransactionStatusError::PlatformError(msg) => Self::PlatformError { msg },
}
}
}

pub(crate) fn map_network_error(error: Box<dyn Error + Send + Sync>) -> GatewayError {
if let Some(jsonrpc_error) = error.downcast_ref::<JsonRpcError>()
&& jsonrpc_error.code == ERROR_CLIENT_ERROR
Expand Down
124 changes: 21 additions & 103 deletions gemstone/src/gateway/mod.rs
Original file line number Diff line number Diff line change
@@ -1,39 +1,26 @@
mod chain_factory;
mod error;
mod preferences;

pub use chain_factory::ChainClientFactory;
pub use error::GatewayError;
use error::map_network_error;
#[cfg(test)]
pub use preferences::EmptyPreferences;
pub use preferences::GemPreferences;
use preferences::PreferencesWrapper;
pub(crate) use preferences::PreferencesWrapper;

use crate::alien::{AlienProvider, AlienProviderWrapper, new_alien_client};
use crate::alien::{AlienProvider, AlienProviderWrapper};
use crate::api_client::GemApiClient;
use crate::models::*;
use crate::network::JsonRpcClient;
use crate::transaction_state::StatusProvider;
use chain_traits::ChainTraits;
use gem_algorand::rpc::AlgorandClientIndexer;
use gem_algorand::rpc::client::AlgorandClient;
use gem_aptos::rpc::client::AptosClient;
use gem_bitcoin::rpc::client::BitcoinClient;
use gem_cardano::rpc::client::CardanoClient;
use gem_cosmos::rpc::client::CosmosClient;
use gem_evm::rpc::EthereumClient;
use gem_hypercore::rpc::client::HyperCoreClient;
use gem_near::rpc::client::NearClient;
use gem_polkadot::rpc::client::PolkadotClient;
use gem_solana::rpc::client::SolanaClient;
use gem_stellar::rpc::client::StellarClient;
use gem_sui::rpc::client::SuiClient;
use gem_ton::rpc::client::TonClient;
use gem_tron::rpc::{client::TronClient, trongrid::client::TronGridClient};
use gem_xrp::rpc::client::XRPClient;
use swapper::swapper::GemSwapper as Swapper;
use std::future::Future;
use std::sync::Arc;
use yielder::Yielder;

use primitives::{AssetId, BitcoinChain, Chain, ChartPeriod, EVMChain, ScanAddressTarget, ScanTransactionPayload, TransactionPreloadInput, chain_cosmos::CosmosChain};
use primitives::{AssetId, Chain, ChartPeriod, ScanAddressTarget, ScanTransactionPayload, TransactionPreloadInput};

#[uniffi::export(with_foreign)]
#[async_trait::async_trait]
Expand All @@ -44,21 +31,15 @@ pub trait GemGatewayEstimateFee: Send + Sync {

#[derive(uniffi::Object)]
pub struct GemGateway {
pub provider: Arc<dyn AlienProvider>,
pub preferences: Arc<dyn GemPreferences>,
pub secure_preferences: Arc<dyn GemPreferences>,
pub api_client: GemApiClient,
chain_factory: Arc<ChainClientFactory>,
yielder: Yielder,
status_provider: StatusProvider,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

can we move status provider out of this?

}

impl std::fmt::Debug for GemGateway {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("GemGateway")
.field("provider", &"<AlienProvider>")
.field("preferences", &"<GemPreferences>")
.field("secure_preferences", &"<GemPreferences>")
.field("api_client", &self.api_client)
.finish()
f.debug_struct("GemGateway").field("api_client", &self.api_client).finish()
}
}

Expand All @@ -68,74 +49,9 @@ impl GemGateway {
F: FnOnce(Arc<dyn ChainTraits>) -> Fut,
Fut: Future<Output = Result<T, Box<dyn std::error::Error + Send + Sync>>>,
{
let provider = self.provider(chain).await?;
let provider = self.chain_factory.create(chain).await?;
call(provider).await.map_err(|e| GatewayError::NetworkError { msg: e.to_string() })
}

pub async fn provider(&self, chain: Chain) -> Result<Arc<dyn ChainTraits>, GatewayError> {
let url = self.provider.get_endpoint(chain).unwrap();
self.provider_with_url(chain, url).await
}

pub async fn provider_with_url(&self, chain: Chain, url: String) -> Result<Arc<dyn ChainTraits>, GatewayError> {
let alien_client = new_alien_client(url.clone(), self.provider.clone());
match chain {
Chain::HyperCore => {
let preferences = Arc::new(PreferencesWrapper {
preferences: self.preferences.clone(),
});
let secure_preferences = Arc::new(PreferencesWrapper {
preferences: self.secure_preferences.clone(),
});
Ok(Arc::new(HyperCoreClient::new_with_preferences(alien_client, preferences, secure_preferences)))
}
Chain::Bitcoin | Chain::BitcoinCash | Chain::Litecoin | Chain::Doge | Chain::Zcash => {
Ok(Arc::new(BitcoinClient::new(alien_client, BitcoinChain::from_chain(chain).unwrap())))
}
Chain::Cardano => Ok(Arc::new(CardanoClient::new(alien_client))),
Chain::Stellar => Ok(Arc::new(StellarClient::new(alien_client))),
Chain::Sui => Ok(Arc::new(SuiClient::new(JsonRpcClient::new(alien_client.clone())))),
Chain::Xrp => Ok(Arc::new(XRPClient::new(JsonRpcClient::new(alien_client.clone())))),
Chain::Algorand => Ok(Arc::new(AlgorandClient::new(alien_client.clone(), AlgorandClientIndexer::new(alien_client.clone())))),
Chain::Near => Ok(Arc::new(NearClient::new(JsonRpcClient::new(alien_client.clone())))),
Chain::Aptos => Ok(Arc::new(AptosClient::new(alien_client))),
Chain::Cosmos | Chain::Osmosis | Chain::Celestia | Chain::Thorchain | Chain::Injective | Chain::Sei | Chain::Noble => {
Ok(Arc::new(CosmosClient::new(CosmosChain::from_chain(chain).unwrap(), alien_client)))
}
Chain::Ton => Ok(Arc::new(TonClient::new(alien_client))),
Chain::Tron => Ok(Arc::new(TronClient::new(alien_client.clone(), TronGridClient::new(alien_client.clone(), String::new())))),
Chain::Polkadot => Ok(Arc::new(PolkadotClient::new(alien_client))),
Chain::Solana => Ok(Arc::new(SolanaClient::new(JsonRpcClient::new(alien_client.clone())))),
Chain::Ethereum
| Chain::Arbitrum
| Chain::SmartChain
| Chain::Polygon
| Chain::Optimism
| Chain::Base
| Chain::AvalancheC
| Chain::OpBNB
| Chain::Fantom
| Chain::Gnosis
| Chain::Manta
| Chain::Blast
| Chain::ZkSync
| Chain::Linea
| Chain::Mantle
| Chain::Celo
| Chain::World
| Chain::Sonic
| Chain::SeiEvm
| Chain::Abstract
| Chain::Berachain
| Chain::Ink
| Chain::Unichain
| Chain::Hyperliquid
| Chain::Plasma
| Chain::Monad
| Chain::XLayer
| Chain::Stable => Ok(Arc::new(EthereumClient::new(JsonRpcClient::new(alien_client), EVMChain::from_chain(chain).unwrap()))),
}
}
}

#[async_trait::async_trait]
Expand All @@ -154,13 +70,16 @@ impl GemGateway {
#[uniffi::constructor]
pub fn new(provider: Arc<dyn AlienProvider>, preferences: Arc<dyn GemPreferences>, secure_preferences: Arc<dyn GemPreferences>, api_url: String) -> Self {
let api_client = GemApiClient::new(api_url, provider.clone());
let yielder = Yielder::new(Arc::new(AlienProviderWrapper::new(provider.clone())));
let chain_factory = Arc::new(ChainClientFactory::new(provider.clone(), preferences, secure_preferences));
let alien_wrapper = Arc::new(AlienProviderWrapper::new(provider));
let yielder = Yielder::new(alien_wrapper.clone());
let swapper = Swapper::new(alien_wrapper);
let status_provider = StatusProvider::new(chain_factory.clone(), swapper);
Self {
provider,
preferences,
secure_preferences,
api_client,
chain_factory,
yielder,
status_provider,
}
}

Expand Down Expand Up @@ -191,8 +110,7 @@ impl GemGateway {
}

pub async fn get_transaction_status(&self, chain: Chain, request: GemTransactionStateRequest) -> Result<GemTransactionUpdate, GatewayError> {
self.with_provider(chain, |provider| async move { provider.get_transaction_status(request.into()).await })
.await
Ok(self.status_provider.get(chain, request).await?)
}

pub async fn get_chain_id(&self, chain: Chain) -> Result<String, GatewayError> {
Expand Down Expand Up @@ -301,7 +219,7 @@ impl GemGateway {
}

pub async fn get_is_token_address(&self, chain: Chain, token_id: String) -> Result<bool, GatewayError> {
Ok(self.provider(chain).await?.get_is_token_address(&token_id))
Ok(self.chain_factory.create(chain).await?.get_is_token_address(&token_id))
}

pub async fn get_balance_earn(&self, chain: Chain, address: String, token_ids: Vec<String>) -> Result<Vec<GemAssetBalance>, GatewayError> {
Expand All @@ -325,7 +243,7 @@ impl GemGateway {

pub async fn get_node_status(&self, chain: Chain, url: &str) -> Result<GemNodeStatus, GatewayError> {
let start_time = std::time::Instant::now();
let provider = self.provider_with_url(chain, url.to_string()).await?;
let provider = self.chain_factory.create_with_url(chain, url.to_string()).await?;

let (chain_id, latest_block_number) = futures::try_join!(provider.get_chain_id(), provider.get_block_latest_number()).map_err(map_network_error)?;

Expand Down
1 change: 1 addition & 0 deletions gemstone/src/gem_swapper/remote_types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -167,6 +167,7 @@ pub struct SwapperQuoteAsset {
#[uniffi::remote(Enum)]
pub enum SwapperSwapStatus {
Pending,
InTransit,
Completed,
Failed,
}
Expand Down
1 change: 1 addition & 0 deletions gemstone/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ pub mod perpetual;
pub mod price_alert_formatter;
pub mod signer;
pub mod siwe;
pub mod transaction_state;
pub mod wallet_connect;

use alien::AlienError;
Expand Down
Loading
Loading