From 4b407de27712795469a38fe7631789eb7c589535 Mon Sep 17 00:00:00 2001 From: rob thijssen Date: Fri, 9 Oct 2026 20:54:37 +0300 Subject: [PATCH] feat(near): one intents account per installation, whichever wallet's QTC moves The operator's call: a person has no use for several intents accounts, so the wallet makes one and routes every swap through it. The sponsor cannot tell one installation from another and does not need to; the wallet simply never offers a second. - Settings record intents_account: the owning wallet, the account id and its public key, none of it secret. settings_set keeps it Rust's to change, as it does the account numbers. - near_intents replaces near_account: - recorded: it is read, with its owning wallet named and marked open or locked. Balances read either way; signing waits for the owner. - not recorded: an open phrase wallet's existing sponsored account with that wallet's key is adopted and recorded. That covers a restore, or a second machine. - otherwise the first phrase wallet's account is described, with the other phrase wallets offered as owner, and creation if the sponsor's terms are acceptable. - near_create_account refuses when an account is recorded or any open wallet's account already exists. - Deposits take QTC from any account; withdrawals pay any open wallet's account. Both use the recorded account, and a withdrawal is signed by the owner's key. - The Accounts page shows one NEAR Intents panel, not one per wallet. Checked in a dev run: with nothing recorded, the dev-phrase wallet's existing bffbod6n6ey7jdk4j.blackbeard-observer.near was found, recorded in settings.json and shown as the one active account, with nothing created. Refs #71, #74, #81 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01NUx7SPonBnB3ofU4mH41WT --- crates/wallet-app/src/commands.rs | 339 +++++++++++++------ crates/wallet-app/src/lib.rs | 2 +- crates/wallet-core/src/near.rs | 13 +- crates/wallet-data/src/settings.rs | 5 + crates/wallet-entities/src/lib.rs | 22 ++ ui/src/api/generated/IntentsAccountRecord.ts | 15 + ui/src/api/generated/NearAccountSummary.ts | 14 +- ui/src/api/generated/Settings.ts | 9 +- ui/src/api/wallet.ts | 20 +- ui/src/components/NearIntentsPanel.tsx | 180 ++++++---- ui/src/routes/Accounts.tsx | 6 +- 11 files changed, 429 insertions(+), 196 deletions(-) create mode 100644 ui/src/api/generated/IntentsAccountRecord.ts diff --git a/crates/wallet-app/src/commands.rs b/crates/wallet-app/src/commands.rs index 8281a0e..aee927c 100644 --- a/crates/wallet-app/src/commands.rs +++ b/crates/wallet-app/src/commands.rs @@ -955,6 +955,8 @@ pub fn settings_set( // the webview's cached copy must not erase one added since. if let Ok(stored) = state.settings.load() { settings.wallet_accounts = stored.wallet_accounts; + // So is the intents account (near_intents, near_create_account). + settings.intents_account = stored.intents_account; } if state.profiles.get(&settings.network).is_none() { return Err(WalletError::InvalidInput(format!( @@ -1052,76 +1054,201 @@ const HISTORY_CACHE_PAGE: usize = 50; /// the zk-tree scanned for leaves paying it (resumed from the cache), each /// unspent one checked against `UsedNullifiers`. The secret is derived from /// the session's seed for the call and dropped with it. -/// The open wallet's NEAR Intents account (#74): derived from its phrase -/// (NEP-649), named by the sponsor from the key (#81), read from NEAR. The -/// key is derived again here and dropped; only its public side leaves. -#[tauri::command] -pub async fn near_account( - state: State<'_, AppState>, - wallet: String, -) -> Result { - use wallet_core::near::{NearIdentity, account_summary}; - use wallet_near::{NEAR_DEFAULT_PATH, NearKey}; - - let id = state - .session - .with_seed(&wallet, |seed| { - NearKey::derive(seed.as_bytes(), NEAR_DEFAULT_PATH).map(|k| NearIdentity { - wallet: wallet.clone(), +/// A wallet's NEAR identity, derived from its phrase: the key's public +/// side and the account the sponsor makes for it. `None` for a wallet +/// opened without its phrase. +fn near_identity_of( + state: &AppState, + wallet: &str, +) -> Result, WalletError> { + use wallet_near::{NEAR_DEFAULT_PATH, NearKey, sponsored_account}; + match state.session.with_seed(wallet, |seed| { + NearKey::derive(seed.as_bytes(), NEAR_DEFAULT_PATH).map(|k| { + wallet_core::near::NearIdentity { + wallet: wallet.to_owned(), public_key: k.key_string(), - handle_digest: k.handle_digest(), + account_id: sponsored_account(&k.handle_digest(), &state.near_network.sponsor), derivation_path: NEAR_DEFAULT_PATH.into(), - }) + } }) - .map_err(session_error)? - .ok_or_else(|| { - WalletError::Refused( - "this wallet was opened without its seed; only a wallet with a phrase has an intents account".into(), - ) - })? + }) { + Ok(Some(Ok(id))) => Ok(Some(id)), + Ok(Some(Err(e))) => Err(WalletError::Internal(e.to_string())), + Ok(None) => Ok(None), + Err(e) => Err(session_error(e)), + } +} + +/// Open wallets that carry a phrase, in the order they were opened. +fn phrase_wallets(state: &AppState) -> Vec { + state + .session + .status(std::time::Instant::now()) + .map(|s| { + s.wallets + .iter() + .filter(|w| w.has_seed) + .map(|w| w.summary.name.clone()) + .collect() + }) + .unwrap_or_default() +} + +fn record_intents_account( + state: &AppState, + id: &wallet_core::near::NearIdentity, +) -> Result<(), WalletError> { + let mut s = state + .settings + .load() .map_err(|e| WalletError::Internal(e.to_string()))?; - let mut summary = account_summary(state.near.as_ref(), &state.near_network, &state.assets, id) - .await - .map_err(|e| WalletError::Internal(format!("NEAR: {e}")))?; - if !summary.exists { - match state.near_sponsor.terms().await { - Ok(t) => match wallet_core::near::usable_terms(&t, &state.near_network.sponsor) { - Ok(_) => summary.can_create = true, - Err(why) => summary.sponsor_note = Some(why), - }, - Err(e) => summary.sponsor_note = Some(format!("the sponsor cannot be reached: {e}")), + s.intents_account = Some(wallet_entities::IntentsAccountRecord { + wallet: id.wallet.clone(), + account_id: id.account_id.clone(), + public_key: id.public_key.clone(), + }); + state + .settings + .save(&s) + .map_err(|e| WalletError::Internal(e.to_string())) +} + +/// The installation's one NEAR Intents account (#74, #81). Every swap +/// routes through it, whichever wallet's QTC goes in or out. +/// +/// - Recorded: read it, and say whether its owning wallet is open to sign. +/// Its balances read without the wallet: they need only the account id. +/// - Not recorded: if an open phrase wallet's sponsored account already +/// exists with that wallet's key (a restore, another machine), adopt and +/// record it. Otherwise describe the account the first open phrase wallet +/// would get, list the wallets that could own it, and say whether the +/// sponsor will create it. The wallet never makes a second one. +#[tauri::command] +pub async fn near_intents(state: State<'_, AppState>) -> Result { + use wallet_core::near::{NearIdentity, account_summary}; + let near_err = |e: wallet_core::ports::NearError| WalletError::Internal(format!("NEAR: {e}")); + let open = phrase_wallets(&state); + let recorded = state + .settings + .load() + .map_err(|e| WalletError::Internal(e.to_string()))? + .intents_account; + + if let Some(rec) = recorded { + let id = NearIdentity { + wallet: rec.wallet.clone(), + public_key: rec.public_key.clone(), + account_id: rec.account_id.clone(), + derivation_path: wallet_near::NEAR_DEFAULT_PATH.into(), + }; + let mut summary = account_summary(state.near.as_ref(), &state.assets, id) + .await + .map_err(near_err)?; + summary.owner_open = open.contains(&rec.wallet); + return Ok(summary); + } + + if open.is_empty() { + return Err(WalletError::Refused( + "open a wallet that carries a phrase: its phrase controls the intents account".into(), + )); + } + // A restore or another machine: an account one of these phrases already has. + let mut ids = vec![]; + for w in &open { + if let Some(id) = near_identity_of(&state, w)? { + ids.push(id); } } + for id in &ids { + if state + .near + .account(&id.account_id) + .await + .map_err(near_err)? + .is_some() + && state + .near + .access_key_nonce(&id.account_id, &id.public_key) + .await + .map_err(near_err)? + .is_some() + { + record_intents_account(&state, id)?; + tracing::info!(account = %id.account_id, wallet = %id.wallet, "found the intents account"); + let mut summary = account_summary(state.near.as_ref(), &state.assets, id_clone(id)) + .await + .map_err(near_err)?; + summary.owner_open = true; + return Ok(summary); + } + } + // None yet: describe the first wallet's, and offer creation. + let first = ids + .into_iter() + .next() + .ok_or_else(|| WalletError::Internal("no phrase wallet could derive a key".into()))?; + let mut summary = account_summary(state.near.as_ref(), &state.assets, first) + .await + .map_err(near_err)?; + summary.owner_open = true; + summary.candidates = open; + match state.near_sponsor.terms().await { + Ok(t) => match wallet_core::near::usable_terms(&t, &state.near_network.sponsor) { + Ok(_) => summary.can_create = true, + Err(why) => summary.sponsor_note = Some(why), + }, + Err(e) => summary.sponsor_note = Some(format!("the sponsor cannot be reached: {e}")), + } Ok(summary) } -/// The open wallet's NEAR account name and key, derived from its phrase. -fn near_identity(state: &AppState, wallet: &str) -> Result<(String, String), WalletError> { - use wallet_near::{NEAR_DEFAULT_PATH, NearKey, sponsored_account}; - state - .session - .with_seed(wallet, |seed| { - NearKey::derive(seed.as_bytes(), NEAR_DEFAULT_PATH).map(|k| { - ( - sponsored_account(&k.handle_digest(), &state.near_network.sponsor), - k.key_string(), - ) - }) - }) - .map_err(session_error)? - .ok_or_else(|| WalletError::Refused("this wallet has no phrase, so no NEAR key".into()))? - .map_err(|e| WalletError::Internal(e.to_string())) +fn id_clone(id: &wallet_core::near::NearIdentity) -> wallet_core::near::NearIdentity { + wallet_core::near::NearIdentity { + wallet: id.wallet.clone(), + public_key: id.public_key.clone(), + account_id: id.account_id.clone(), + derivation_path: id.derivation_path.clone(), + } } -/// Where to send QTC from Quantus to land in the open wallet's intents -/// account (#75): the account's permanent bridge deposit address, checked -/// as a Quantus address. +/// The recorded intents account, and its owning wallet's identity if that +/// wallet is open: what signing needs. +fn intents_owner(state: &AppState) -> Result { + let rec = state + .settings + .load() + .map_err(|e| WalletError::Internal(e.to_string()))? + .intents_account + .ok_or_else(|| WalletError::Refused("there is no intents account yet".into()))?; + let id = near_identity_of(state, &rec.wallet) + .map_err(|_| { + WalletError::Refused(format!("open {} to use the intents account", rec.wallet)) + })? + .ok_or_else(|| { + WalletError::Refused(format!("{} was opened without its phrase", rec.wallet)) + })?; + if id.account_id != rec.account_id { + return Err(WalletError::Internal(format!( + "{}'s key names {}, not the recorded {}", + rec.wallet, id.account_id, rec.account_id + ))); + } + Ok(id) +} + +/// Where to send QTC from Quantus to land in the intents account (#75): +/// its permanent bridge deposit address, checked as a Quantus address. Any +/// of the person's Quantus accounts can pay it. #[tauri::command] -pub async fn near_qtc_deposit_address( - state: State<'_, AppState>, - wallet: String, -) -> Result { - let (account, _) = near_identity(&state, &wallet)?; +pub async fn near_qtc_deposit_address(state: State<'_, AppState>) -> Result { + let account = state + .settings + .load() + .map_err(|e| WalletError::Internal(e.to_string()))? + .intents_account + .ok_or_else(|| WalletError::Refused("there is no intents account yet".into()))? + .account_id; state .qtc_bridge .deposit_address(&account) @@ -1130,13 +1257,12 @@ pub async fn near_qtc_deposit_address( } /// QTC out of the intents account and back to a Quantus address (#75): an -/// `ft_withdraw` with the bridge's memo, signed here as a delegate action -/// and relayed by the sponsor, which pays the gas. Returns the sponsor's -/// transaction hash. The bridge keeps 0.002 QTC. +/// `ft_withdraw` with the bridge's memo, signed by the owning wallet's key +/// as a delegate action and relayed by the sponsor, which pays the gas. +/// Returns the sponsor's transaction hash. The bridge keeps 0.002 QTC. #[tauri::command] pub async fn near_withdraw_qtc( state: State<'_, AppState>, - wallet: String, amount: String, to: String, ) -> Result { @@ -1156,7 +1282,7 @@ pub async fn near_withdraw_qtc( } } let call = qtc_withdraw_call(to.trim(), raw).map_err(WalletError::InvalidInput)?; - let (account, key) = near_identity(&state, &wallet)?; + let owner = intents_owner(&state)?; let near = |e: wallet_core::ports::NearError| WalletError::Internal(format!("NEAR: {e}")); let held = state @@ -1164,7 +1290,7 @@ pub async fn near_withdraw_qtc( .view( INTENTS, "mt_batch_balance_of", - &serde_json::json!({ "account_id": account, "token_ids": [format!("nep141:{QTC_TOKEN}")] }), + &serde_json::json!({ "account_id": owner.account_id, "token_ids": [format!("nep141:{QTC_TOKEN}")] }), ) .await .map_err(near)?; @@ -1179,20 +1305,23 @@ pub async fn near_withdraw_qtc( usable_terms(&terms, &state.near_network.sponsor).map_err(WalletError::Refused)?; let nonce = state .near - .access_key_nonce(&account, &key) + .access_key_nonce(&owner.account_id, &owner.public_key) .await .map_err(near)? .ok_or_else(|| { - WalletError::Refused(format!("{account} does not carry this wallet's key")) + WalletError::Refused(format!( + "{} does not carry {}'s key", + owner.account_id, owner.wallet + )) })?; let (_, height) = state.near.final_block().await.map_err(near)?; let signed = state .session - .with_seed(&wallet, |seed| { + .with_seed(&owner.wallet, |seed| { let k = NearKey::derive(seed.as_bytes(), NEAR_DEFAULT_PATH)?; DelegateAction { - sender_id: account.clone(), + sender_id: owner.account_id.clone(), receiver_id: INTENTS.into(), actions: vec![call], nonce: nonce + 1, @@ -1203,7 +1332,7 @@ pub async fn near_withdraw_qtc( .sign(&k) }) .map_err(session_error)? - .ok_or_else(|| WalletError::Refused("this wallet has no phrase".into()))? + .ok_or_else(|| WalletError::Refused(format!("{} has no phrase", owner.wallet)))? .map_err(|e| WalletError::Internal(e.to_string()))?; let hash = state .near_sponsor @@ -1211,51 +1340,65 @@ pub async fn near_withdraw_qtc( .await .map_err(|e| WalletError::Internal(format!("sponsor: {e}")))?; let hash = bs58::encode(hash).into_string(); - tracing::info!(%account, tx = %hash, "QTC withdrawal relayed"); + tracing::info!(account = %owner.account_id, tx = %hash, "QTC withdrawal relayed"); Ok(hash) } -/// Ask the sponsor to create the open wallet's NEAR Intents account (#81), -/// then read it back. The sponsor names the account from the key; a name -/// other than the one the wallet derived is refused rather than used. +/// Ask the sponsor to create the installation's intents account (#81), +/// controlled by `wallet`'s phrase, then read it back. Refused when one is +/// already recorded, or when any open wallet's account already exists: the +/// wallet makes one, and only one. The sponsor names the account from the +/// key; a name other than the one derived here is refused. #[tauri::command] pub async fn near_create_account( state: State<'_, AppState>, wallet: String, ) -> Result { - use wallet_near::{NEAR_DEFAULT_PATH, NearKey, sponsored_account}; - - let (public_key, expected) = state - .session - .with_seed(&wallet, |seed| { - NearKey::derive(seed.as_bytes(), NEAR_DEFAULT_PATH).map(|k| { - ( - k.key_string(), - sponsored_account(&k.handle_digest(), &state.near_network.sponsor), - ) - }) - }) - .map_err(session_error)? - .ok_or_else(|| WalletError::Refused("this wallet has no phrase, so no NEAR key".into()))? - .map_err(|e| WalletError::Internal(e.to_string()))?; - let terms = state - .near_sponsor - .terms() - .await - .map_err(|e| WalletError::Internal(format!("sponsor: {e}")))?; + let near = |e: wallet_core::ports::NearError| WalletError::Internal(format!("NEAR: {e}")); + if let Some(rec) = state + .settings + .load() + .map_err(|e| WalletError::Internal(e.to_string()))? + .intents_account + { + return Err(WalletError::Refused(format!( + "this wallet already uses {}; it makes only one", + rec.account_id + ))); + } + for w in phrase_wallets(&state) { + if let Some(id) = near_identity_of(&state, &w)? + && state + .near + .account(&id.account_id) + .await + .map_err(near)? + .is_some() + { + return Err(WalletError::Refused(format!( + "{w} already has {}; refresh to use it", + id.account_id + ))); + } + } + let id = near_identity_of(&state, &wallet)? + .ok_or_else(|| WalletError::Refused(format!("{wallet} has no phrase, so no NEAR key")))?; + let terms = state.near_sponsor.terms().await.map_err(near)?; wallet_core::near::usable_terms(&terms, &state.near_network.sponsor) .map_err(WalletError::Refused)?; let made = state .near_sponsor - .create_account(&public_key) + .create_account(&id.public_key) .await .map_err(|e| WalletError::Internal(format!("sponsor: {e}")))?; - if made != expected { + if made != id.account_id { return Err(WalletError::Internal(format!( - "the sponsor made {made}, but this wallet's key names {expected}" + "the sponsor made {made}, but {wallet}'s key names {}", + id.account_id ))); } - tracing::info!(account = %made, "NEAR account created by the sponsor"); + record_intents_account(&state, &id)?; + tracing::info!(account = %made, %wallet, "intents account created by the sponsor"); // The sponsor answers once its transaction is in a final block; the // account itself is made by a receipt a block or two later. Read it // back only once it is there, or the panel says "not created yet" over @@ -1266,7 +1409,7 @@ pub async fn near_create_account( } tokio::time::sleep(std::time::Duration::from_millis(1500)).await; } - near_account(state, wallet).await + near_intents(state).await } #[tauri::command] diff --git a/crates/wallet-app/src/lib.rs b/crates/wallet-app/src/lib.rs index 788f782..69fded1 100644 --- a/crates/wallet-app/src/lib.rs +++ b/crates/wallet-app/src/lib.rs @@ -76,7 +76,7 @@ pub fn run() { commands::settings_set, commands::history_page, commands::wormhole_summary, - commands::near_account, + commands::near_intents, commands::near_create_account, commands::near_qtc_deposit_address, commands::near_withdraw_qtc, diff --git a/crates/wallet-core/src/near.rs b/crates/wallet-core/src/near.rs index f542af1..e859bde 100644 --- a/crates/wallet-core/src/near.rs +++ b/crates/wallet-core/src/near.rs @@ -157,7 +157,8 @@ pub struct NearIdentity { pub wallet: String, /// `ml-dsa-65:`. pub public_key: String, - pub handle_digest: [u8; 32], + /// The sponsored account of that key ([`sponsored_account`]). + pub account_id: String, pub derivation_path: String, } @@ -166,14 +167,15 @@ pub struct NearIdentity { /// Intents that it holds. One view call covers the tokens. pub async fn account_summary( rpc: &dyn NearRpc, - net: &NearNetwork, assets: &AssetRegistry, id: NearIdentity, ) -> Result { - let account_id = sponsored_account(&id.handle_digest, &net.sponsor); + let account_id = id.account_id.clone(); let account = rpc.account(&account_id).await?; let mut summary = NearAccountSummary { wallet: id.wallet, + owner_open: false, + candidates: vec![], account_id: account_id.clone(), public_key: id.public_key.clone(), derivation_path: id.derivation_path, @@ -397,7 +399,7 @@ mod tests { NearIdentity { wallet: "w".into(), public_key: key.into(), - handle_digest: [0; 32], + account_id: sponsored_account(&[0; 32], "blackbeard-observer.near"), derivation_path: "m/44'/397'/0'".into(), } } @@ -411,7 +413,6 @@ mod tests { key: "k", balances: vec![], }, - &net, &AssetRegistry::shipped().unwrap(), id("k"), ) @@ -430,7 +431,6 @@ mod tests { key: "k", balances: vec!["0", "1500000", "0"], }, - &NearNetwork::shipped().unwrap(), &assets, id("k"), ) @@ -454,7 +454,6 @@ mod tests { key: "someone-else", balances: vec![], }, - &NearNetwork::shipped().unwrap(), &AssetRegistry::shipped().unwrap(), id("k"), ) diff --git a/crates/wallet-data/src/settings.rs b/crates/wallet-data/src/settings.rs index 6eddc98..bd3a115 100644 --- a/crates/wallet-data/src/settings.rs +++ b/crates/wallet-data/src/settings.rs @@ -85,6 +85,11 @@ mod tests { account_names: [("qz1".to_string(), "savings".to_string())].into(), preview_swaps: true, wallet_accounts: [("w".to_string(), vec![1, 2])].into(), + intents_account: Some(wallet_entities::IntentsAccountRecord { + wallet: "w".into(), + account_id: "bx.blackbeard-observer.near".into(), + public_key: "ml-dsa-65:x".into(), + }), }; store.save(&changed).unwrap(); assert_eq!(store.load().unwrap(), changed); diff --git a/crates/wallet-entities/src/lib.rs b/crates/wallet-entities/src/lib.rs index ce43d1d..30f0072 100644 --- a/crates/wallet-entities/src/lib.rs +++ b/crates/wallet-entities/src/lib.rs @@ -473,6 +473,22 @@ pub struct Settings { /// every unlock. Kept here because the keystore file is quantus-cli's /// and holds one keypair. pub wallet_accounts: BTreeMap>, + /// The installation's one NEAR Intents account (#74, #81): every swap + /// routes through it, whichever wallet's QTC goes in or out. Recorded + /// when it is created or first found; not secret. + pub intents_account: Option, +} + +/// Which intents account this installation uses, and which wallet's +/// phrase controls it. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)] +#[ts(export)] +pub struct IntentsAccountRecord { + /// The wallet whose phrase derives the account's key. + pub wallet: String, + pub account_id: String, + /// `ml-dsa-65:`. + pub public_key: String, } impl Default for Settings { @@ -484,6 +500,7 @@ impl Default for Settings { account_names: BTreeMap::new(), preview_swaps: false, wallet_accounts: BTreeMap::new(), + intents_account: None, } } } @@ -713,7 +730,12 @@ pub struct WormholeSummary { #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)] #[ts(export)] pub struct NearAccountSummary { + /// The wallet whose phrase controls the account (or would, once made). pub wallet: String, + /// Whether that wallet is open with its phrase, so the account can sign. + pub owner_open: bool, + /// Open wallets with a phrase that could own it, when none does yet. + pub candidates: Vec, /// `b<…>.blackbeard-observer.near`, whether or not it exists yet. pub account_id: String, /// `ml-dsa-65:`: the key that controls it. diff --git a/ui/src/api/generated/IntentsAccountRecord.ts b/ui/src/api/generated/IntentsAccountRecord.ts new file mode 100644 index 0000000..76bfe34 --- /dev/null +++ b/ui/src/api/generated/IntentsAccountRecord.ts @@ -0,0 +1,15 @@ +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. + +/** + * Which intents account this installation uses, and which wallet's + * phrase controls it. + */ +export type IntentsAccountRecord = { +/** + * The wallet whose phrase derives the account's key. + */ +wallet: string, account_id: string, +/** + * `ml-dsa-65:`. + */ +public_key: string, }; diff --git a/ui/src/api/generated/NearAccountSummary.ts b/ui/src/api/generated/NearAccountSummary.ts index c7b9889..8dec1a9 100644 --- a/ui/src/api/generated/NearAccountSummary.ts +++ b/ui/src/api/generated/NearAccountSummary.ts @@ -8,7 +8,19 @@ import type { IntentsBalance } from "./IntentsBalance"; * sponsor from that key (#81), and what it holds. No secret: the key is * public, and the account is derived again from the phrase on every look. */ -export type NearAccountSummary = { wallet: string, +export type NearAccountSummary = { +/** + * The wallet whose phrase controls the account (or would, once made). + */ +wallet: string, +/** + * Whether that wallet is open with its phrase, so the account can sign. + */ +owner_open: boolean, +/** + * Open wallets with a phrase that could own it, when none does yet. + */ +candidates: Array, /** * `b<…>.blackbeard-observer.near`, whether or not it exists yet. */ diff --git a/ui/src/api/generated/Settings.ts b/ui/src/api/generated/Settings.ts index 288043b..f7fd91a 100644 --- a/ui/src/api/generated/Settings.ts +++ b/ui/src/api/generated/Settings.ts @@ -1,5 +1,6 @@ // This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. import type { ChainId } from "./ChainId"; +import type { IntentsAccountRecord } from "./IntentsAccountRecord"; /** * Persisted preferences. Nothing here is secret. @@ -34,4 +35,10 @@ preview_swaps: boolean, * every unlock. Kept here because the keystore file is quantus-cli's * and holds one keypair. */ -wallet_accounts: { [key in string]?: Array }, }; +wallet_accounts: { [key in string]?: Array }, +/** + * The installation's one NEAR Intents account (#74, #81): every swap + * routes through it, whichever wallet's QTC goes in or out. Recorded + * when it is created or first found; not secret. + */ +intents_account: IntentsAccountRecord | null, }; diff --git a/ui/src/api/wallet.ts b/ui/src/api/wallet.ts index 2e6bfae..91c5c38 100644 --- a/ui/src/api/wallet.ts +++ b/ui/src/api/wallet.ts @@ -222,24 +222,26 @@ export function wormholeSummary(chain: ChainId, wallet: string): Promise('wormhole_summary', { chain, wallet }) } -// The wallet's NEAR Intents account: derived from its phrase, named by the -// sponsor from its key, read from NEAR. Only public fields come back. -export function nearAccount(wallet: string): Promise { - return command('near_account', { wallet }) +// The installation's one NEAR Intents account: controlled by one wallet's +// phrase, named by the sponsor from its key, read from NEAR. Every swap +// routes through it. Only public fields come back. +export function nearIntents(): Promise { + return command('near_intents') } // QTC between Quantus and the intents account, over the PoA bridge. The // deposit address is permanent per account; a withdrawal is signed in Rust // and relayed by the sponsor, and returns its NEAR transaction hash. -export function nearQtcDepositAddress(wallet: string): Promise { - return command('near_qtc_deposit_address', { wallet }) +export function nearQtcDepositAddress(): Promise { + return command('near_qtc_deposit_address') } -export function nearWithdrawQtc(wallet: string, amount: string, to: string): Promise { - return command('near_withdraw_qtc', { wallet, amount, to }) +export function nearWithdrawQtc(amount: string, to: string): Promise { + return command('near_withdraw_qtc', { amount, to }) } -// Ask the sponsor to create that account. Returns it, read back. +// Ask the sponsor to create it, controlled by `wallet`'s phrase. The wallet +// makes one, and only one. Returns it, read back. export function nearCreateAccount(wallet: string): Promise { return command('near_create_account', { wallet }) } diff --git a/ui/src/components/NearIntentsPanel.tsx b/ui/src/components/NearIntentsPanel.tsx index 214dbcd..38be556 100644 --- a/ui/src/components/NearIntentsPanel.tsx +++ b/ui/src/components/NearIntentsPanel.tsx @@ -4,40 +4,48 @@ import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query' import { copyText } from '../api/clipboard' import { useSession } from '../api/hooks' import { - nearAccount, nearCreateAccount, + nearIntents, nearQtcDepositAddress, nearWithdrawQtc, } from '../api/wallet' import { formatAmount } from '../lib/format' /** - * The wallet's NEAR Intents account: the NEAR account its phrase's - * ML-DSA-65 key controls, which the swap routes run through. Named by the - * sponsor from the key, so it is known before it exists; everything here - * is read and decided on the Rust side. + * The installation's NEAR Intents account: one NEAR account, controlled by + * one wallet's post-quantum key, that every swap routes through whichever + * wallet's QTC goes in or out. Named by the sponsor from the key, so it is + * known before it exists; everything here is read and decided on the Rust + * side. */ -export function NearIntentsPanel({ wallet }: { wallet: string }) { +export function NearIntentsPanel() { + const qc = useQueryClient() const account = useQuery({ - queryKey: ['near-account', wallet], - queryFn: () => nearAccount(wallet), + queryKey: ['near-intents'], + queryFn: nearIntents, staleTime: 30_000, retry: 1, }) - const qc = useQueryClient() + const [owner, setOwner] = useState('') const create = useMutation({ - mutationFn: () => nearCreateAccount(wallet), - onSuccess: (made) => qc.setQueryData(['near-account', wallet], made), + mutationFn: (wallet: string) => nearCreateAccount(wallet), + onSuccess: (made) => qc.setQueryData(['near-intents'], made), }) const a = account.data const active = !!a?.exists && a.key_on_account return (
-

NEAR Intents account · {wallet}

+

NEAR Intents account

{a && ( - {a.exists ? (a.key_on_account ? 'active' : 'not this wallet’s key') : 'not created yet'} + {a.exists + ? a.key_on_account + ? a.owner_open + ? `active · ${a.wallet}` + : `${a.wallet} is locked` + : 'not this wallet’s key' + : 'not created yet'} )}
@@ -50,25 +58,42 @@ export function NearIntentsPanel({ wallet }: { wallet: string }) {
{a.account_id}
- Controlled only by this wallet’s post-quantum key (ML-DSA-65, derived from its - phrase at {a.derivation_path}). The same phrase finds it again anywhere. + Every swap runs through this one account. It is controlled only by {a.wallet}’s + post-quantum key (ML-DSA-65, derived from its phrase at {a.derivation_path}); the + same phrase finds it again anywhere. {!a.exists && (

- Swaps run through this account. The wallet’s sponsor creates it for you and pays - its NEAR fees, so you never need NEAR yourself. + The wallet’s sponsor creates it and pays its NEAR fees, so you never need NEAR. It + is made once: choose the wallet whose phrase will control it.

{a.can_create ? ( - +
+ {a.candidates.length > 1 && ( + + )} + +
) : (

{a.sponsor_note ?? 'The sponsor cannot create it now.'}

)} @@ -77,7 +102,7 @@ export function NearIntentsPanel({ wallet }: { wallet: string }) { )} {a.exists && !a.key_on_account && (

- This account exists but this wallet’s key is not on it, so the wallet cannot use it. + This account exists but {a.wallet}’s key is not on it, so the wallet cannot use it.

)} {a.exists && ( @@ -100,7 +125,10 @@ export function NearIntentsPanel({ wallet }: { wallet: string }) { )} - {active && account.refetch()} />} + {active && !a.owner_open && ( +

Unlock {a.wallet} to move anything in or out of it.

+ )} + {active && account.refetch()} />}
)} -
{ - e.preventDefault() - withdraw.mutate() - }} - > - setAmount(e.target.value)} - inputMode="decimal" - aria-label="QTC to withdraw" - /> - - -
- - The bridge keeps 0.002 QTC of each withdrawal; at least 0.01 QTC. The wallet’s sponsor pays - the NEAR fee. - + {canSign && ( + <> +
{ + e.preventDefault() + withdraw.mutate() + }} + > + setAmount(e.target.value)} + inputMode="decimal" + aria-label="QTC to withdraw" + /> + + +
+ + The bridge keeps 0.002 QTC of each withdrawal; at least 0.01 QTC. The wallet’s sponsor + pays the NEAR fee. + + + )} {withdraw.isError &&

{withdraw.error.message}

} {withdraw.data && (

diff --git a/ui/src/routes/Accounts.tsx b/ui/src/routes/Accounts.tsx index 54c2cec..c13c406 100644 --- a/ui/src/routes/Accounts.tsx +++ b/ui/src/routes/Accounts.tsx @@ -178,11 +178,7 @@ export function Accounts() { wallet={w.wallet.name} /> ))} - {session.data?.wallets - .filter((w) => w.has_seed) - .map((w) => ( - - ))} + {session.data?.wallets.some((w) => w.has_seed) && } )