feat(near): one intents account per installation, whichever wallet's QTC moves
ci / gate (push) Canceled after 25s

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 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NUx7SPonBnB3ofU4mH41WT
This commit is contained in:
2026-10-09 20:54:37 +03:00
co-authored by Claude Opus 5.5
parent 5d5baf1c21
commit 4b407de277
11 changed files with 429 additions and 196 deletions
+241 -98
View File
@@ -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<NearAccountSummary, WalletError> {
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<Option<wallet_core::near::NearIdentity>, 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<String> {
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<NearAccountSummary, WalletError> {
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<wallet_core::near::NearIdentity, WalletError> {
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<String, WalletError> {
let (account, _) = near_identity(&state, &wallet)?;
pub async fn near_qtc_deposit_address(state: State<'_, AppState>) -> Result<String, WalletError> {
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<String, WalletError> {
@@ -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<NearAccountSummary, WalletError> {
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]
+1 -1
View File
@@ -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,
+6 -7
View File
@@ -157,7 +157,8 @@ pub struct NearIdentity {
pub wallet: String,
/// `ml-dsa-65:<base58>`.
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<NearAccountSummary, NearError> {
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"),
)
+5
View File
@@ -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);
+22
View File
@@ -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<String, Vec<u32>>,
/// 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<IntentsAccountRecord>,
}
/// 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:<base58>`.
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<String>,
/// `b<…>.blackbeard-observer.near`, whether or not it exists yet.
pub account_id: String,
/// `ml-dsa-65:<base58>`: the key that controls it.
@@ -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:<base58>`.
*/
public_key: string, };
+13 -1
View File
@@ -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<string>,
/**
* `b<…>.blackbeard-observer.near`, whether or not it exists yet.
*/
+8 -1
View File
@@ -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<number> }, };
wallet_accounts: { [key in string]?: Array<number> },
/**
* 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, };
+11 -9
View File
@@ -222,24 +222,26 @@ export function wormholeSummary(chain: ChainId, wallet: string): Promise<Wormhol
return command<WormholeSummary>('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<NearAccountSummary> {
return command<NearAccountSummary>('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<NearAccountSummary> {
return command<NearAccountSummary>('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<string> {
return command<string>('near_qtc_deposit_address', { wallet })
export function nearQtcDepositAddress(): Promise<string> {
return command<string>('near_qtc_deposit_address')
}
export function nearWithdrawQtc(wallet: string, amount: string, to: string): Promise<string> {
return command<string>('near_withdraw_qtc', { wallet, amount, to })
export function nearWithdrawQtc(amount: string, to: string): Promise<string> {
return command<string>('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<NearAccountSummary> {
return command<NearAccountSummary>('near_create_account', { wallet })
}
+106 -74
View File
@@ -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 (
<section className="panel">
<div className="panel-head">
<h2 className="panel-title">NEAR Intents account · {wallet}</h2>
<h2 className="panel-title">NEAR Intents account</h2>
{a && (
<span className="muted" style={{ fontSize: 12 }}>
{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'}
</span>
)}
</div>
@@ -50,25 +58,42 @@ export function NearIntentsPanel({ wallet }: { wallet: string }) {
<label>Account</label>
<div className="mono address">{a.account_id}</div>
<span className="muted" style={{ fontSize: 12 }}>
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.
</span>
</div>
{!a.exists && (
<div className="field">
<p className="muted">
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.
</p>
{a.can_create ? (
<button
className="button"
type="button"
onClick={() => create.mutate()}
disabled={create.isPending}
>
{create.isPending ? 'Creating…' : 'Create account'}
</button>
<div className="row">
{a.candidates.length > 1 && (
<select
className="input"
value={owner || a.wallet}
onChange={(e) => setOwner(e.target.value)}
aria-label="Controlled by"
>
{a.candidates.map((w) => (
<option key={w} value={w}>
{w}
</option>
))}
</select>
)}
<button
className="button"
type="button"
onClick={() => create.mutate(owner || a.wallet)}
disabled={create.isPending}
>
{create.isPending ? 'Creating…' : 'Create account'}
</button>
</div>
) : (
<p className="error">{a.sponsor_note ?? 'The sponsor cannot create it now.'}</p>
)}
@@ -77,7 +102,7 @@ export function NearIntentsPanel({ wallet }: { wallet: string }) {
)}
{a.exists && !a.key_on_account && (
<p className="error">
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.
</p>
)}
{a.exists && (
@@ -100,7 +125,10 @@ export function NearIntentsPanel({ wallet }: { wallet: string }) {
</tbody>
</table>
)}
{active && <QtcBridgeLegs wallet={wallet} onMoved={() => account.refetch()} />}
{active && !a.owner_open && (
<p className="muted">Unlock {a.wallet} to move anything in or out of it.</p>
)}
{active && <QtcBridgeLegs canSign={a.owner_open} onMoved={() => account.refetch()} />}
<div className="row">
<button className="button" type="button" onClick={() => copyText(a.account_id)}>
Copy account
@@ -123,28 +151,28 @@ export function NearIntentsPanel({ wallet }: { wallet: string }) {
/**
* QTC in and out of the intents account over the PoA bridge (#75). In: the
* account's permanent Quantus deposit address, paid with an ordinary send.
* Out: a withdrawal to one of this wallet's Quantus accounts, relayed by
* the sponsor; the bridge keeps 0.002 QTC.
* account's permanent Quantus deposit address, paid with an ordinary send
* from any of your accounts. Out: a withdrawal to any of your open
* accounts, relayed by the sponsor; the bridge keeps 0.002 QTC.
*/
function QtcBridgeLegs({ wallet, onMoved }: { wallet: string; onMoved: () => void }) {
function QtcBridgeLegs({ canSign, onMoved }: { canSign: boolean; onMoved: () => void }) {
const navigate = useNavigate()
const session = useSession()
const mine =
session.data?.wallets
.find((w) => w.wallet.name === wallet)
?.accounts.filter((x) => x.current_scheme) ?? []
session.data?.wallets.flatMap((w) =>
w.accounts.filter((x) => x.current_scheme).map((x) => ({ ...x, walletName: w.wallet.name })),
) ?? []
const [showDeposit, setShowDeposit] = useState(false)
const deposit = useQuery({
queryKey: ['qtc-deposit-address', wallet],
queryFn: () => nearQtcDepositAddress(wallet),
queryKey: ['qtc-deposit-address'],
queryFn: nearQtcDepositAddress,
enabled: showDeposit,
staleTime: Infinity,
})
const [amount, setAmount] = useState('')
const [to, setTo] = useState('')
const withdraw = useMutation({
mutationFn: () => nearWithdrawQtc(wallet, amount, to || mine[0]?.address || ''),
mutationFn: () => nearWithdrawQtc(amount, to || mine[0]?.address || ''),
onSuccess: () => {
setAmount('')
// The bridge pays out on Quantus within about a minute; the balance
@@ -167,8 +195,8 @@ function QtcBridgeLegs({ wallet, onMoved }: { wallet: string; onMoved: () => voi
<>
<div className="mono address">{deposit.data}</div>
<span className="muted" style={{ fontSize: 12 }}>
This account’s own deposit address on Quantus; it does not change. QTC sent here
arrives in NEAR Intents a few minutes later. At least 0.01 QTC.
The account’s own deposit address on Quantus; it does not change. QTC sent here from
any of your accounts arrives in NEAR Intents a few minutes later. At least 0.01 QTC.
</span>
<div className="row">
<button
@@ -186,41 +214,45 @@ function QtcBridgeLegs({ wallet, onMoved }: { wallet: string; onMoved: () => voi
)}
</div>
)}
<form
className="row"
onSubmit={(e) => {
e.preventDefault()
withdraw.mutate()
}}
>
<input
className="input numeral"
placeholder="QTC to withdraw"
value={amount}
onChange={(e) => setAmount(e.target.value)}
inputMode="decimal"
aria-label="QTC to withdraw"
/>
<select
className="input"
value={to || mine[0]?.address || ''}
onChange={(e) => setTo(e.target.value)}
aria-label="Withdraw to"
>
{mine.map((x) => (
<option key={x.address} value={x.address}>
Account {(x.account ?? 0) + 1} · {x.address.slice(0, 10)}…
</option>
))}
</select>
<button className="button" type="submit" disabled={!amount || withdraw.isPending}>
{withdraw.isPending ? 'Withdrawing…' : 'Withdraw to Quantus'}
</button>
</form>
<span className="muted" style={{ fontSize: 12 }}>
The bridge keeps 0.002 QTC of each withdrawal; at least 0.01 QTC. The wallet’s sponsor pays
the NEAR fee.
</span>
{canSign && (
<>
<form
className="row"
onSubmit={(e) => {
e.preventDefault()
withdraw.mutate()
}}
>
<input
className="input numeral"
placeholder="QTC to withdraw"
value={amount}
onChange={(e) => setAmount(e.target.value)}
inputMode="decimal"
aria-label="QTC to withdraw"
/>
<select
className="input"
value={to || mine[0]?.address || ''}
onChange={(e) => setTo(e.target.value)}
aria-label="Withdraw to"
>
{mine.map((x) => (
<option key={x.address} value={x.address}>
{x.walletName} · account {(x.account ?? 0) + 1} · {x.address.slice(0, 10)}…
</option>
))}
</select>
<button className="button" type="submit" disabled={!amount || withdraw.isPending}>
{withdraw.isPending ? 'Withdrawing…' : 'Withdraw to Quantus'}
</button>
</form>
<span className="muted" style={{ fontSize: 12 }}>
The bridge keeps 0.002 QTC of each withdrawal; at least 0.01 QTC. The wallet’s sponsor
pays the NEAR fee.
</span>
</>
)}
{withdraw.isError && <p className="error">{withdraw.error.message}</p>}
{withdraw.data && (
<p className="muted">
+1 -5
View File
@@ -178,11 +178,7 @@ export function Accounts() {
wallet={w.wallet.name}
/>
))}
{session.data?.wallets
.filter((w) => w.has_seed)
.map((w) => (
<NearIntentsPanel key={`near-${w.wallet.name}`} wallet={w.wallet.name} />
))}
{session.data?.wallets.some((w) => w.has_seed) && <NearIntentsPanel />}
<NetworkOverview />
</>
)