sui_bridge/
utils.rs

1// Copyright (c) Mysten Labs, Inc.
2// SPDX-License-Identifier: Apache-2.0
3
4use crate::abi::{
5    EthBridgeCommittee, EthBridgeConfig, EthBridgeLimiter, EthBridgeVault, EthSuiBridge,
6};
7use crate::config::{
8    BridgeNodeConfig, EthConfig, MetricsConfig, SuiConfig, WatchdogConfig, default_ed25519_key_pair,
9};
10use crate::crypto::{BridgeAuthorityKeyPair, BridgeAuthorityPublicKeyBytes};
11use crate::server::APPLICATION_JSON;
12use crate::types::{AddTokensOnSuiAction, BridgeAction, BridgeCommittee};
13use alloy::network::EthereumWallet;
14use alloy::primitives::Address as EthAddress;
15use alloy::providers::{ProviderBuilder, RootProvider, WsConnect};
16use alloy::signers::local::PrivateKeySigner;
17use anyhow::anyhow;
18use fastcrypto::ed25519::Ed25519KeyPair;
19use fastcrypto::encoding::{Encoding, Hex};
20use fastcrypto::secp256k1::Secp256k1KeyPair;
21use fastcrypto::traits::{EncodeDecodeBase64, KeyPair};
22use futures::future::join_all;
23use move_core_types::language_storage::StructTag;
24use std::collections::BTreeMap;
25use std::path::PathBuf;
26use std::str::FromStr;
27use std::sync::Arc;
28use sui_config::Config;
29use sui_keys::keypair_file::read_key;
30use sui_sdk::wallet_context::WalletContext;
31use sui_test_transaction_builder::TestTransactionBuilder;
32use sui_types::BRIDGE_PACKAGE_ID;
33use sui_types::base_types::SuiAddress;
34use sui_types::bridge::{
35    BRIDGE_MODULE_NAME, BRIDGE_REGISTER_FOREIGN_TOKEN_FUNCTION_NAME, BridgeChainId,
36};
37use sui_types::committee::StakeUnit;
38use sui_types::crypto::{SuiKeyPair, ToFromBytes, get_key_pair};
39use sui_types::effects::TransactionEffectsAPI;
40use sui_types::programmable_transaction_builder::ProgrammableTransactionBuilder;
41use sui_types::sui_system_state::sui_system_state_summary::SuiSystemStateSummary;
42use sui_types::transaction::{ObjectArg, TransactionData};
43use url::Url;
44
45pub struct EthBridgeContracts {
46    pub bridge: EthSuiBridge::EthSuiBridgeInstance<EthProvider>,
47    pub committee: EthBridgeCommittee::EthBridgeCommitteeInstance<EthProvider>,
48    pub limiter: EthBridgeLimiter::EthBridgeLimiterInstance<EthProvider>,
49    pub vault: EthBridgeVault::EthBridgeVaultInstance<EthProvider>,
50    pub config: EthBridgeConfig::EthBridgeConfigInstance<EthProvider>,
51}
52
53pub type EthProvider = Arc<RootProvider<alloy::network::Ethereum>>;
54pub type EthSignerProvider = Arc<
55    alloy::providers::fillers::FillProvider<
56        alloy::providers::fillers::JoinFill<
57            alloy::providers::fillers::JoinFill<
58                alloy::providers::Identity,
59                alloy::providers::fillers::JoinFill<
60                    alloy::providers::fillers::GasFiller,
61                    alloy::providers::fillers::JoinFill<
62                        alloy::providers::fillers::BlobGasFiller,
63                        alloy::providers::fillers::JoinFill<
64                            alloy::providers::fillers::NonceFiller,
65                            alloy::providers::fillers::ChainIdFiller,
66                        >,
67                    >,
68                >,
69            >,
70            alloy::providers::fillers::WalletFiller<EthereumWallet>,
71        >,
72        EthProvider,
73        alloy::network::Ethereum,
74    >,
75>;
76pub type EthWsProvider = Arc<
77    alloy::providers::fillers::FillProvider<
78        alloy::providers::fillers::JoinFill<
79            alloy::providers::Identity,
80            alloy::providers::fillers::JoinFill<
81                alloy::providers::fillers::GasFiller,
82                alloy::providers::fillers::JoinFill<
83                    alloy::providers::fillers::BlobGasFiller,
84                    alloy::providers::fillers::JoinFill<
85                        alloy::providers::fillers::NonceFiller,
86                        alloy::providers::fillers::ChainIdFiller,
87                    >,
88                >,
89            >,
90        >,
91        alloy::providers::RootProvider<alloy::network::Ethereum>,
92        alloy::network::Ethereum,
93    >,
94>;
95
96pub fn get_eth_provider(url: &str) -> anyhow::Result<EthProvider> {
97    let url = Url::parse(url).map_err(|e| anyhow!("Invalid RPC URL: {}", e))?;
98    let provider = RootProvider::new_http(url);
99    Ok(Arc::new(provider))
100}
101
102pub fn get_eth_signer_provider(
103    url: &str,
104    private_key_hex: &str,
105) -> anyhow::Result<EthSignerProvider> {
106    let signer = PrivateKeySigner::from_str(private_key_hex)
107        .map_err(|e| anyhow!("Invalid private key: {}", e))?;
108    let wallet = EthereumWallet::from(signer);
109    let provider = ProviderBuilder::new()
110        .wallet(wallet)
111        .connect_provider(get_eth_provider(url)?);
112    Ok(Arc::new(provider))
113}
114
115pub async fn get_eth_ws_provider(url: &str) -> anyhow::Result<EthWsProvider> {
116    let url = Url::parse(url).map_err(|e| anyhow!("Invalid WebSocket URL: {}", e))?;
117    let ws = WsConnect::new(url);
118    let provider = ProviderBuilder::new().connect_ws(ws).await?;
119    Ok(Arc::new(provider))
120}
121
122/// Generate Bridge Authority key (Secp256k1KeyPair) and write to a file as base64 encoded `privkey`.
123pub fn generate_bridge_authority_key_and_write_to_file(
124    path: &PathBuf,
125) -> Result<(), anyhow::Error> {
126    let (_, kp): (_, BridgeAuthorityKeyPair) = get_key_pair();
127    let eth_address = BridgeAuthorityPublicKeyBytes::from(&kp.public).to_eth_address();
128    println!(
129        "Corresponding Ethereum address by this ecdsa key: {:?}",
130        eth_address
131    );
132    let sui_address = SuiAddress::from(&kp.public);
133    println!(
134        "Corresponding Sui address by this ecdsa key: {:?}",
135        sui_address
136    );
137    let base64_encoded = kp.encode_base64();
138    std::fs::write(path, base64_encoded)
139        .map_err(|err| anyhow!("Failed to write encoded key to path: {:?}", err))
140}
141
142/// Generate Bridge Client key (Secp256k1KeyPair or Ed25519KeyPair) and write to a file as base64 encoded `flag || privkey`.
143pub fn generate_bridge_client_key_and_write_to_file(
144    path: &PathBuf,
145    use_ecdsa: bool,
146) -> Result<(), anyhow::Error> {
147    let kp = if use_ecdsa {
148        let (_, kp): (_, Secp256k1KeyPair) = get_key_pair();
149        let eth_address = BridgeAuthorityPublicKeyBytes::from(&kp.public).to_eth_address();
150        println!(
151            "Corresponding Ethereum address by this ecdsa key: {:?}",
152            eth_address
153        );
154        SuiKeyPair::from(kp)
155    } else {
156        let (_, kp): (_, Ed25519KeyPair) = get_key_pair();
157        SuiKeyPair::from(kp)
158    };
159    let sui_address = SuiAddress::from(&kp.public());
160    println!("Corresponding Sui address by this key: {:?}", sui_address);
161
162    let contents = kp.encode_base64();
163    std::fs::write(path, contents)
164        .map_err(|err| anyhow!("Failed to write encoded key to path: {:?}", err))
165}
166
167/// Given the address of SuiBridge Proxy, return the addresses of the committee, limiter, vault, and config.
168pub async fn get_eth_contract_addresses(
169    bridge_proxy_address: EthAddress,
170    provider: EthProvider,
171) -> anyhow::Result<(
172    EthAddress,
173    EthAddress,
174    EthAddress,
175    EthAddress,
176    EthAddress,
177    EthAddress,
178    EthAddress,
179    EthAddress,
180)> {
181    let sui_bridge = EthSuiBridge::new(bridge_proxy_address, provider.clone());
182    let committee_address: EthAddress = sui_bridge.committee().call().await?;
183    let committee = EthBridgeCommittee::new(committee_address, provider.clone());
184    let config_address: EthAddress = committee.config().call().await?;
185    let bridge_config = EthBridgeConfig::new(config_address, provider.clone());
186    let limiter_address: EthAddress = sui_bridge.limiter().call().await?;
187    let vault_address: EthAddress = sui_bridge.vault().call().await?;
188    let vault = EthBridgeVault::new(vault_address, provider.clone());
189    let weth_address: EthAddress = vault.wETH().call().await?;
190    let usdt_address: EthAddress = bridge_config.tokenAddressOf(4).call().await?;
191    let wbtc_address: EthAddress = bridge_config.tokenAddressOf(1).call().await?;
192    let lbtc_address: EthAddress = bridge_config.tokenAddressOf(6).call().await?;
193
194    Ok((
195        committee_address,
196        limiter_address,
197        vault_address,
198        config_address,
199        weth_address,
200        usdt_address,
201        wbtc_address,
202        lbtc_address,
203    ))
204}
205
206/// Given the address of SuiBridge Proxy, return the contracts of the committee, limiter, vault, and config.
207pub async fn get_eth_contracts(
208    bridge_proxy_address: EthAddress,
209    provider: EthProvider,
210) -> anyhow::Result<EthBridgeContracts> {
211    let sui_bridge = EthSuiBridge::new(bridge_proxy_address, provider.clone());
212    let committee_address: EthAddress = sui_bridge.committee().call().await?;
213    let limiter_address: EthAddress = sui_bridge.limiter().call().await?;
214    let vault_address: EthAddress = sui_bridge.vault().call().await?;
215    let committee = EthBridgeCommittee::new(committee_address, provider.clone());
216    let config_address: EthAddress = committee.config().call().await?;
217
218    let limiter = EthBridgeLimiter::new(limiter_address, provider.clone());
219    let vault = EthBridgeVault::new(vault_address, provider.clone());
220    let config = EthBridgeConfig::new(config_address, provider.clone());
221    Ok(EthBridgeContracts {
222        bridge: sui_bridge,
223        committee,
224        limiter,
225        vault,
226        config,
227    })
228}
229
230/// Read bridge key from a file and print the corresponding information.
231/// If `is_validator_key` is true, the key must be a Secp256k1 key.
232pub fn examine_key(path: &PathBuf, is_validator_key: bool) -> Result<(), anyhow::Error> {
233    let key = read_key(path, is_validator_key)?;
234    let sui_address = SuiAddress::from(&key.public());
235    let pubkey = match key {
236        SuiKeyPair::Secp256k1(kp) => {
237            println!("Secp256k1 key:");
238            let eth_address = BridgeAuthorityPublicKeyBytes::from(&kp.public).to_eth_address();
239            println!("Corresponding Ethereum address: {:x}", eth_address);
240            kp.public.as_bytes().to_vec()
241        }
242        SuiKeyPair::Ed25519(kp) => {
243            println!("Ed25519 key:");
244            kp.public().as_bytes().to_vec()
245        }
246        SuiKeyPair::Secp256r1(kp) => {
247            println!("Secp256r1 key:");
248            kp.public().as_bytes().to_vec()
249        }
250    };
251    println!("Corresponding Sui address: {:?}", sui_address);
252    println!("Corresponding PublicKey: {:?}", Hex::encode(pubkey));
253    Ok(())
254}
255
256/// Generate Bridge Node Config template and write to a file.
257pub fn generate_bridge_node_config_and_write_to_file(
258    path: &PathBuf,
259    run_client: bool,
260) -> Result<(), anyhow::Error> {
261    let mut config = BridgeNodeConfig {
262        server_listen_port: 9191,
263        metrics_port: 9184,
264        bridge_authority_key_path: PathBuf::from("/path/to/your/bridge_authority_key"),
265        sui: SuiConfig {
266            sui_rpc_url: "your_sui_rpc_url".to_string(),
267            sui_bridge_chain_id: BridgeChainId::SuiTestnet as u8,
268            bridge_client_key_path: None,
269            bridge_client_gas_object: None,
270            sui_bridge_module_last_processed_event_id_override: None,
271            sui_bridge_next_sequence_number_override: None,
272        },
273        eth: EthConfig {
274            eth_rpc_url: "your_eth_rpc_url".to_string(),
275            eth_bridge_proxy_address: "0x0000000000000000000000000000000000000000".to_string(),
276            eth_bridge_chain_id: BridgeChainId::EthSepolia as u8,
277            eth_contracts_start_block_fallback: Some(0),
278            eth_contracts_start_block_override: None,
279        },
280        approved_governance_actions: vec![],
281        run_client,
282        db_path: None,
283        metrics_key_pair: default_ed25519_key_pair(),
284        metrics: Some(MetricsConfig {
285            push_interval_seconds: None, // use default value
286            push_url: "metrics_proxy_url".to_string(),
287        }),
288        watchdog_config: Some(WatchdogConfig {
289            total_supplies: BTreeMap::from_iter(vec![(
290                "eth".to_string(),
291                "0xd0e89b2af5e4910726fbcd8b8dd37bb79b29e5f83f7491bca830e94f7f226d29::eth::ETH"
292                    .to_string(),
293            )]),
294        }),
295    };
296    if run_client {
297        config.sui.bridge_client_key_path = Some(PathBuf::from("/path/to/your/bridge_client_key"));
298        config.db_path = Some(PathBuf::from("/path/to/your/client_db"));
299    }
300    config.save(path)
301}
302
303pub async fn publish_and_register_coins_return_add_coins_on_sui_action(
304    wallet_context: &WalletContext,
305    bridge_arg: ObjectArg,
306    token_packages_dir: Vec<PathBuf>,
307    token_ids: Vec<u8>,
308    token_prices: Vec<u64>,
309    nonce: u64,
310) -> BridgeAction {
311    assert!(token_ids.len() == token_packages_dir.len());
312    assert!(token_prices.len() == token_packages_dir.len());
313    let client = wallet_context.grpc_client().unwrap();
314    let rgp = client.get_reference_gas_price().await.unwrap();
315
316    let senders = wallet_context.get_addresses();
317    // We want each sender to deal with one coin
318    assert!(senders.len() >= token_packages_dir.len());
319
320    // publish coin packages
321    let mut publish_tokens_tasks = vec![];
322
323    for (token_package_dir, sender) in token_packages_dir.iter().zip(senders.clone()) {
324        let gas = wallet_context
325            .get_one_gas_object_owned_by_address(sender)
326            .await
327            .unwrap()
328            .unwrap();
329        let tx = TestTransactionBuilder::new(sender, gas, rgp)
330            .publish(token_package_dir.to_path_buf())
331            .build();
332        let tx = wallet_context.sign_transaction(&tx).await;
333        let api_clone = client.clone();
334        publish_tokens_tasks.push(tokio::spawn(async move {
335            api_clone
336                .execute_transaction_and_wait_for_checkpoint(&tx)
337                .await
338        }));
339    }
340    let publish_coin_responses = join_all(publish_tokens_tasks).await;
341
342    let mut token_type_names = vec![];
343    let mut register_tasks = vec![];
344    for (response, sender) in publish_coin_responses.into_iter().zip(senders.clone()) {
345        let response = response.unwrap().unwrap();
346        assert!(response.effects.status().is_ok());
347        let mut tc = None;
348        let mut type_ = None;
349        let mut uc = None;
350        let mut metadata = None;
351        for o in &response.changed_objects {
352            use sui_rpc::proto::sui::rpc::v2::changed_object::IdOperation;
353            if matches!(o.id_operation(), IdOperation::Created) {
354                let Ok(object_type) = o.object_type().parse::<StructTag>() else {
355                    continue;
356                };
357                if object_type.name.as_str().starts_with("TreasuryCap") {
358                    assert!(tc.is_none() && type_.is_none());
359                    tc = {
360                        let id = o.object_id().parse().unwrap();
361                        let version = o.output_version().into();
362                        let digest = o.output_digest().parse().unwrap();
363                        Some((id, version, digest))
364                    };
365                    type_ = Some(object_type.type_params.first().unwrap().clone());
366                } else if object_type.name.as_str().starts_with("UpgradeCap") {
367                    assert!(uc.is_none());
368                    uc = {
369                        let id = o.object_id().parse().unwrap();
370                        let version = o.output_version().into();
371                        let digest = o.output_digest().parse().unwrap();
372                        Some((id, version, digest))
373                    };
374                } else if object_type.name.as_str().starts_with("CoinMetadata") {
375                    assert!(metadata.is_none());
376                    metadata = {
377                        let id = o.object_id().parse().unwrap();
378                        let version = o.output_version().into();
379                        let digest = o.output_digest().parse().unwrap();
380                        Some((id, version, digest))
381                    };
382                }
383            }
384        }
385        let (tc, type_, uc, metadata) =
386            (tc.unwrap(), type_.unwrap(), uc.unwrap(), metadata.unwrap());
387
388        // register with the bridge
389        let mut builder = ProgrammableTransactionBuilder::new();
390        let bridge_arg = builder.obj(bridge_arg).unwrap();
391        let uc_arg = builder.obj(ObjectArg::ImmOrOwnedObject(uc)).unwrap();
392        let tc_arg = builder.obj(ObjectArg::ImmOrOwnedObject(tc)).unwrap();
393        let metadata_arg = builder.obj(ObjectArg::ImmOrOwnedObject(metadata)).unwrap();
394        builder.programmable_move_call(
395            BRIDGE_PACKAGE_ID,
396            BRIDGE_MODULE_NAME.into(),
397            BRIDGE_REGISTER_FOREIGN_TOKEN_FUNCTION_NAME.into(),
398            vec![type_.clone()],
399            vec![bridge_arg, tc_arg, uc_arg, metadata_arg],
400        );
401        let pt = builder.finish();
402        let gas = wallet_context
403            .get_one_gas_object_owned_by_address(sender)
404            .await
405            .unwrap()
406            .unwrap();
407        let tx = TransactionData::new_programmable(sender, vec![gas], pt, 1_000_000_000, rgp);
408        let signed_tx = wallet_context.sign_transaction(&tx).await;
409        let api_clone = client.clone();
410        register_tasks.push(async move {
411            api_clone
412                .execute_transaction_and_wait_for_checkpoint(&signed_tx)
413                .await
414        });
415        token_type_names.push(type_);
416    }
417    for response in join_all(register_tasks).await {
418        assert!(response.unwrap().effects.status().is_ok());
419    }
420
421    BridgeAction::AddTokensOnSuiAction(AddTokensOnSuiAction {
422        nonce,
423        chain_id: BridgeChainId::SuiCustom,
424        native: false,
425        token_ids,
426        token_type_names,
427        token_prices,
428    })
429}
430
431pub async fn wait_for_server_to_be_up(server_url: String, timeout_sec: u64) -> anyhow::Result<()> {
432    let now = std::time::Instant::now();
433    loop {
434        if let Ok(true) = reqwest::Client::new()
435            .get(server_url.clone())
436            .header(reqwest::header::ACCEPT, APPLICATION_JSON)
437            .send()
438            .await
439            .map(|res| res.status().is_success())
440        {
441            break;
442        }
443        if now.elapsed().as_secs() > timeout_sec {
444            anyhow::bail!("Server is not up and running after {} seconds", timeout_sec);
445        }
446        tokio::time::sleep(tokio::time::Duration::from_millis(100)).await;
447    }
448    Ok(())
449}
450
451/// Return a mappping from validator name to their bridge voting power.
452/// If a validator is not in the Sui committee, we will use its base URL as the name.
453pub async fn get_committee_voting_power_by_name(
454    bridge_committee: &Arc<BridgeCommittee>,
455    system_state: &SuiSystemStateSummary,
456) -> BTreeMap<String, StakeUnit> {
457    let mut sui_committee: BTreeMap<_, _> = system_state
458        .active_validators
459        .iter()
460        .map(|v| (v.sui_address, v.name.clone()))
461        .collect();
462    bridge_committee
463        .members()
464        .iter()
465        .map(|v| {
466            (
467                sui_committee
468                    .remove(&v.1.sui_address)
469                    .unwrap_or(v.1.base_url.clone()),
470                v.1.voting_power,
471            )
472        })
473        .collect()
474}
475
476/// Return a mappping from validator pub keys to their names.
477/// If a validator is not in the Sui committee, we will use its base URL as the name.
478pub async fn get_validator_names_by_pub_keys(
479    bridge_committee: &Arc<BridgeCommittee>,
480    system_state: &SuiSystemStateSummary,
481) -> BTreeMap<BridgeAuthorityPublicKeyBytes, String> {
482    let mut sui_committee: BTreeMap<_, _> = system_state
483        .active_validators
484        .iter()
485        .map(|v| (v.sui_address, v.name.clone()))
486        .collect();
487    bridge_committee
488        .members()
489        .iter()
490        .map(|(name, validator)| {
491            (
492                name.clone(),
493                sui_committee
494                    .remove(&validator.sui_address)
495                    .unwrap_or(validator.base_url.clone()),
496            )
497        })
498        .collect()
499}