Every open wallet with a phrase now shows its NEAR Intents account. Its NEP-649 key is derived from the seed on each look and dropped; only the public side leaves Rust. The account's name is a function of that key, b<base32 of the handle's first 10 bytes>.blackbeard-observer.near, so the sponsor (#81) creates it there, a restored phrase finds it again with nothing stored, and the leading b sorts it onto shard 8, which our nodes serve. The panel says whether the account exists and whether this wallet's key is on it, and shows its NEAR for gas and every token it holds inside Intents (one mt_batch_balance_of over the registry's Intents ids). The logic is wallet_core::near::account_summary, written against the NearRpc port and tested with a fake. The command is a shim, and the app now holds the shard-routed client from #73 and near.toml, which a file in the data directory can replace. Corrected on the way: the asset registry said no post-quantum asset is on Intents. QTC has been, as nep141:qtc.omft.near, since early October. Quantus's native QTC now maps to it, the token-list fixture gains 1Click's QTC entry, and the "unmapped asset" tests use Planck's token instead. The readme no longer says the swap module waits for Quantus's MPC fork. Verified in a dev run with the dev-phrase fixture: the panel showed bffbod6n6ey7jdk4j.blackbeard-observer.near as not created yet. Refs #74 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01NUx7SPonBnB3ofU4mH41WT
This commit is contained in:
@@ -23,9 +23,9 @@ use wallet_data::mnemonic;
|
||||
use wallet_data::substrate::{ChainManager, account_info};
|
||||
use wallet_entities::{
|
||||
AccountBalance, AccountRef, AccountScan, Amount, AssetId, AssetKind, ChainId, ChainProfile,
|
||||
ChainStatus, HighSecurityInfo, HistoryCursor, HistoryPage, OpenWalletInfo, PendingReversible,
|
||||
PreparedTransferInfo, SessionAccountInfo, SessionStatusInfo, TxStage, TxStatusInfo,
|
||||
WormholeSummary,
|
||||
ChainStatus, HighSecurityInfo, HistoryCursor, HistoryPage, NearAccountSummary, OpenWalletInfo,
|
||||
PendingReversible, PreparedTransferInfo, SessionAccountInfo, SessionStatusInfo, TxStage,
|
||||
TxStatusInfo, WormholeSummary,
|
||||
};
|
||||
use wallet_entities::{AppInfo, CreationChallenge, CreationStart, WalletError, WalletSummary};
|
||||
|
||||
@@ -1050,6 +1050,39 @@ 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_data::keys::near::{NEAR_DEFAULT_PATH, NearKey};
|
||||
|
||||
let id = state
|
||||
.session
|
||||
.with_seed(&wallet, |seed| {
|
||||
NearKey::derive(seed, NEAR_DEFAULT_PATH).map(|k| NearIdentity {
|
||||
wallet: wallet.clone(),
|
||||
public_key: k.key_string(),
|
||||
handle_digest: k.handle_digest(),
|
||||
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(),
|
||||
)
|
||||
})?
|
||||
.map_err(|e| WalletError::Internal(e.to_string()))?;
|
||||
account_summary(state.near.as_ref(), &state.near_network, &state.assets, id)
|
||||
.await
|
||||
.map_err(|e| WalletError::Internal(format!("NEAR: {e}")))
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn wormhole_summary(
|
||||
state: State<'_, AppState>,
|
||||
|
||||
@@ -76,6 +76,7 @@ pub fn run() {
|
||||
commands::settings_set,
|
||||
commands::history_page,
|
||||
commands::wormhole_summary,
|
||||
commands::near_account,
|
||||
swap::swap_assets,
|
||||
swap::swap_preview,
|
||||
swap::swap_order_create,
|
||||
|
||||
@@ -10,11 +10,15 @@ use std::time::Duration;
|
||||
use wallet_core::PreparedTransaction;
|
||||
use wallet_core::assets::AssetRegistry;
|
||||
use wallet_core::backup::BackupChallenge;
|
||||
use wallet_core::ports::{FiatRamp, HistoryCache, HistorySource, OrderStore, ShieldedCache};
|
||||
use wallet_core::near::NearNetwork;
|
||||
use wallet_core::ports::{
|
||||
FiatRamp, HistoryCache, HistorySource, NearRpc, OrderStore, ShieldedCache,
|
||||
};
|
||||
use wallet_core::profiles::ProfileRegistry;
|
||||
use wallet_core::session::Session;
|
||||
use wallet_data::history::{ObserverHistory, SqliteHistoryCache};
|
||||
use wallet_data::keystore::FileKeystore;
|
||||
use wallet_data::near::HttpNearRpc;
|
||||
use wallet_data::ramp::StubRamp;
|
||||
use wallet_data::settings::SettingsStore;
|
||||
use wallet_data::substrate::ChainManager;
|
||||
@@ -58,6 +62,9 @@ pub struct AppState {
|
||||
pub assets: AssetRegistry,
|
||||
/// The fiat ramp: a stub until a provider is signed (#44).
|
||||
pub ramp: Arc<dyn FiatRamp>,
|
||||
/// NEAR, under the intents account (#71): RPC routed by shard (#73).
|
||||
pub near: Arc<dyn NearRpc>,
|
||||
pub near_network: NearNetwork,
|
||||
}
|
||||
|
||||
impl AppState {
|
||||
@@ -65,7 +72,7 @@ impl AppState {
|
||||
/// `WALLET_KEYSTORE_DIR` says otherwise (useful for a dev run against a
|
||||
/// throwaway directory, or for pointing at `~/.quantus/wallets`).
|
||||
/// Everything lives under one app-data directory: `<data>/wallets/`,
|
||||
/// `<data>/settings.json`, `<data>/profiles.toml`. `WALLET_DATA_DIR`
|
||||
/// `<data>/settings.json`, `<data>/profiles.toml`, `<data>/near.toml`. `WALLET_DATA_DIR`
|
||||
/// relocates the whole thing (a dev run against a throwaway directory);
|
||||
/// `WALLET_KEYSTORE_DIR` relocates only the wallets (pointing at
|
||||
/// `~/.quantus/wallets` shares them with the CLI in place).
|
||||
@@ -97,6 +104,15 @@ impl AppState {
|
||||
profiles = profiles.with_override(&text)?;
|
||||
tracing::info!(path = %override_path.display(), "applied profile overrides");
|
||||
}
|
||||
// NEAR endpoints and sponsor: shipped, or `<data>/near.toml` in their
|
||||
// place.
|
||||
let near_path = data_dir.join("near.toml");
|
||||
let near_network = if near_path.exists() {
|
||||
tracing::info!(path = %near_path.display(), "NEAR settings from the data directory");
|
||||
NearNetwork::from_toml(&std::fs::read_to_string(&near_path)?)?
|
||||
} else {
|
||||
NearNetwork::shipped()?
|
||||
};
|
||||
let assets = AssetRegistry::shipped().map_err(|e| anyhow::anyhow!("assets.toml: {e}"))?;
|
||||
let cache = Arc::new(
|
||||
SqliteHistoryCache::open(&data_dir.join("history.sqlite"))
|
||||
@@ -118,6 +134,8 @@ impl AppState {
|
||||
swap: Arc::new(OneClick::new(assets.clone())),
|
||||
assets,
|
||||
ramp: Arc::new(StubRamp::new()),
|
||||
near: Arc::new(HttpNearRpc::new(near_network.clone())),
|
||||
near_network,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -181,10 +181,8 @@ mod tests {
|
||||
})
|
||||
.unwrap();
|
||||
assert_eq!((qtc.info.symbol.as_str(), qtc.info.decimals), ("QTC", 12));
|
||||
assert!(
|
||||
qtc.intents.is_none(),
|
||||
"no post-quantum asset is on Intents yet"
|
||||
);
|
||||
// Bridged by the PoA bridge since October 2026 (#71).
|
||||
assert_eq!(qtc.intents.as_deref(), Some("nep141:qtc.omft.near"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -214,13 +212,13 @@ mod tests {
|
||||
#[test]
|
||||
fn an_unmapped_asset_is_refused_by_name() {
|
||||
let r = AssetRegistry::shipped().unwrap();
|
||||
let qtc = AssetId {
|
||||
chain: ChainId("quantus".into()),
|
||||
let plk = AssetId {
|
||||
chain: ChainId("planck".into()),
|
||||
kind: AssetKind::Native,
|
||||
};
|
||||
assert!(matches!(
|
||||
r.intents_id(&qtc),
|
||||
Err(SwapError::UnsupportedPair(ref a)) if a == "quantus/native"
|
||||
r.intents_id(&plk),
|
||||
Err(SwapError::UnsupportedPair(ref a)) if a == "planck/native"
|
||||
));
|
||||
let unknown = AssetId {
|
||||
chain: ChainId("near".into()),
|
||||
|
||||
@@ -8,8 +8,8 @@
|
||||
# wallet only ever passes value through
|
||||
# kind "native", or "nep141" with a contract, or "pallet" with an id
|
||||
# intents the NEAR Intents asset id from GET /v0/tokens, when it has one.
|
||||
# Post-quantum chains have none yet; that is the whole reason the
|
||||
# Quantus leg of a swap is its own child (#42).
|
||||
# QTC has one since early October 2026: the PoA bridge mints it
|
||||
# on NEAR as qtc.omft.near (#71).
|
||||
# ramp a fiat ramp provider's symbol code, when one is chosen (#44)
|
||||
|
||||
# ---- what the wallet holds ---------------------------------------------------
|
||||
@@ -19,6 +19,7 @@ chain = "quantus"
|
||||
kind = "native"
|
||||
symbol = "QTC"
|
||||
decimals = 12
|
||||
intents = "nep141:qtc.omft.near"
|
||||
|
||||
[[asset]]
|
||||
chain = "planck"
|
||||
|
||||
@@ -3,6 +3,10 @@
|
||||
//! adapter in `wallet-data` does the HTTP.
|
||||
|
||||
use serde::Deserialize;
|
||||
use wallet_entities::{Amount, IntentsBalance, NearAccountSummary};
|
||||
|
||||
use crate::assets::AssetRegistry;
|
||||
use crate::ports::{NearError, NearRpc};
|
||||
|
||||
const SHIPPED: &str = include_str!("near.toml");
|
||||
|
||||
@@ -25,6 +29,8 @@ pub struct NearNetwork {
|
||||
/// The shards our nodes track. Any other shard goes to `fallback` only.
|
||||
pub served_shards: Vec<u64>,
|
||||
pub fallback: Vec<String>,
|
||||
/// The account that creates wallets' accounts as its sub-accounts (#81).
|
||||
pub sponsor: String,
|
||||
}
|
||||
|
||||
impl NearNetwork {
|
||||
@@ -69,6 +75,121 @@ impl NearNetwork {
|
||||
}
|
||||
}
|
||||
|
||||
/// The account the sponsor creates for a key: `b<name>.<sponsor>`, where
|
||||
/// `<name>` is the lowercase unpadded base32 of the first 10 bytes of the
|
||||
/// key's handle digest (the SHA3-256 that NEP-645 names an ML-DSA-65 key
|
||||
/// by). Nothing needs storing: a restored phrase re-derives its key and so
|
||||
/// its account. The leading `b` sorts every such account onto the shard
|
||||
/// between `aurora-0` and `earn.kaiching` (8 on mainnet), which our nodes
|
||||
/// serve.
|
||||
pub fn sponsored_account(handle_digest: &[u8; 32], sponsor: &str) -> String {
|
||||
format!("b{}.{sponsor}", base32_lower(&handle_digest[..10]))
|
||||
}
|
||||
|
||||
/// The NEAR Intents verifier contract.
|
||||
pub const INTENTS: &str = "intents.near";
|
||||
|
||||
/// The public side of a wallet's NEAR key, which is all a summary needs.
|
||||
pub struct NearIdentity {
|
||||
pub wallet: String,
|
||||
/// `ml-dsa-65:<base58>`.
|
||||
pub public_key: String,
|
||||
pub handle_digest: [u8; 32],
|
||||
pub derivation_path: String,
|
||||
}
|
||||
|
||||
/// Read the wallet's intents account: whether it exists, whether its key is
|
||||
/// this wallet's, its gas, and every token the asset registry maps to
|
||||
/// 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 = rpc.account(&account_id).await?;
|
||||
let mut summary = NearAccountSummary {
|
||||
wallet: id.wallet,
|
||||
account_id: account_id.clone(),
|
||||
public_key: id.public_key.clone(),
|
||||
derivation_path: id.derivation_path,
|
||||
exists: account.is_some(),
|
||||
key_on_account: false,
|
||||
gas: account.map(|a| a.balance),
|
||||
intents: vec![],
|
||||
};
|
||||
if !summary.exists {
|
||||
return Ok(summary);
|
||||
}
|
||||
summary.key_on_account = rpc
|
||||
.access_key_nonce(&account_id, &id.public_key)
|
||||
.await?
|
||||
.is_some();
|
||||
|
||||
// Every Intents id the registry knows, once each (QTC appears under
|
||||
// both the Quantus chain and NEAR's).
|
||||
let mut tokens: Vec<(String, String, u8)> = vec![];
|
||||
for e in assets.iter() {
|
||||
if let Some(t) = &e.intents
|
||||
&& t.starts_with("nep141:")
|
||||
&& !tokens.iter().any(|(x, ..)| x == t)
|
||||
{
|
||||
tokens.push((t.clone(), e.info.symbol.clone(), e.info.decimals));
|
||||
}
|
||||
}
|
||||
let ids: Vec<&str> = tokens.iter().map(|(t, ..)| t.as_str()).collect();
|
||||
let raw = rpc
|
||||
.view(
|
||||
INTENTS,
|
||||
"mt_batch_balance_of",
|
||||
&serde_json::json!({ "account_id": account_id, "token_ids": ids }),
|
||||
)
|
||||
.await?;
|
||||
let raw: Vec<String> = serde_json::from_value(raw)
|
||||
.map_err(|e| NearError::BadAnswer(format!("mt_batch_balance_of: {e}")))?;
|
||||
if raw.len() != tokens.len() {
|
||||
return Err(NearError::BadAnswer(format!(
|
||||
"mt_batch_balance_of: {} balances for {} tokens",
|
||||
raw.len(),
|
||||
tokens.len()
|
||||
)));
|
||||
}
|
||||
for ((token, symbol, decimals), r) in tokens.into_iter().zip(raw) {
|
||||
let n: u128 = r
|
||||
.parse()
|
||||
.map_err(|_| NearError::BadAnswer(format!("balance {r:?} of {token}")))?;
|
||||
if n > 0 {
|
||||
summary.intents.push(IntentsBalance {
|
||||
token,
|
||||
symbol,
|
||||
amount: Amount::new(n, decimals),
|
||||
});
|
||||
}
|
||||
}
|
||||
Ok(summary)
|
||||
}
|
||||
|
||||
/// RFC 4648 base32, lowercase, no padding. Lowercase letters and `2`-`7`
|
||||
/// are all valid in a NEAR account id.
|
||||
fn base32_lower(bytes: &[u8]) -> String {
|
||||
const ALPHABET: &[u8; 32] = b"abcdefghijklmnopqrstuvwxyz234567";
|
||||
let mut out = String::new();
|
||||
let (mut acc, mut bits) = (0u32, 0u32);
|
||||
for &b in bytes {
|
||||
acc = (acc << 8) | u32::from(b);
|
||||
bits += 8;
|
||||
while bits >= 5 {
|
||||
bits -= 5;
|
||||
out.push(ALPHABET[((acc >> bits) & 31) as usize] as char);
|
||||
}
|
||||
}
|
||||
if bits > 0 {
|
||||
out.push(ALPHABET[((acc << (5 - bits)) & 31) as usize] as char);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The boundary-account shard layout (V1 to V3 all share this shape).
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct ShardLayout {
|
||||
@@ -189,11 +310,149 @@ mod tests {
|
||||
assert!(n.any_endpoints().len() == n.served_shards.len() + n.fallback.len());
|
||||
}
|
||||
|
||||
struct Fake {
|
||||
exists: bool,
|
||||
key: &'static str,
|
||||
balances: Vec<&'static str>,
|
||||
}
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl NearRpc for Fake {
|
||||
async fn account(&self, _: &str) -> Result<Option<crate::ports::NearAccount>, NearError> {
|
||||
Ok(self.exists.then(|| crate::ports::NearAccount {
|
||||
balance: Amount::new(5, 24),
|
||||
locked: Amount::new(0, 24),
|
||||
storage_usage: 1,
|
||||
}))
|
||||
}
|
||||
async fn access_key_nonce(&self, _: &str, key: &str) -> Result<Option<u64>, NearError> {
|
||||
Ok((key == self.key).then_some(7))
|
||||
}
|
||||
async fn view(
|
||||
&self,
|
||||
c: &str,
|
||||
m: &str,
|
||||
args: &serde_json::Value,
|
||||
) -> Result<serde_json::Value, NearError> {
|
||||
assert_eq!((c, m), (INTENTS, "mt_batch_balance_of"));
|
||||
let n = args["token_ids"].as_array().unwrap().len();
|
||||
let mut b = self.balances.clone();
|
||||
b.resize(n, "0");
|
||||
Ok(serde_json::json!(b))
|
||||
}
|
||||
async fn final_block_hash(&self) -> Result<[u8; 32], NearError> {
|
||||
unreachable!()
|
||||
}
|
||||
async fn send(&self, _: &str, _: &[u8]) -> Result<[u8; 32], NearError> {
|
||||
unreachable!()
|
||||
}
|
||||
}
|
||||
|
||||
fn id(key: &str) -> NearIdentity {
|
||||
NearIdentity {
|
||||
wallet: "w".into(),
|
||||
public_key: key.into(),
|
||||
handle_digest: [0; 32],
|
||||
derivation_path: "m/44'/397'/0'".into(),
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn an_account_not_yet_created_says_so_and_reads_nothing_else() {
|
||||
let net = NearNetwork::shipped().unwrap();
|
||||
let s = account_summary(
|
||||
&Fake {
|
||||
exists: false,
|
||||
key: "k",
|
||||
balances: vec![],
|
||||
},
|
||||
&net,
|
||||
&AssetRegistry::shipped().unwrap(),
|
||||
id("k"),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(!s.exists && !s.key_on_account && s.gas.is_none() && s.intents.is_empty());
|
||||
assert_eq!(s.account_id, sponsored_account(&[0; 32], &net.sponsor));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn an_existing_account_lists_its_nonzero_intents_tokens_once_each() {
|
||||
let assets = AssetRegistry::shipped().unwrap();
|
||||
let s = account_summary(
|
||||
&Fake {
|
||||
exists: true,
|
||||
key: "k",
|
||||
balances: vec!["0", "1500000", "0"],
|
||||
},
|
||||
&NearNetwork::shipped().unwrap(),
|
||||
&assets,
|
||||
id("k"),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(s.exists && s.key_on_account);
|
||||
assert_eq!(s.gas, Some(Amount::new(5, 24)));
|
||||
assert_eq!(s.intents.len(), 1);
|
||||
let qtc_ids = assets
|
||||
.iter()
|
||||
.filter(|e| e.intents.as_deref() == Some("nep141:qtc.omft.near"))
|
||||
.count();
|
||||
assert!(qtc_ids >= 1);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn an_account_whose_key_is_not_ours_is_marked() {
|
||||
let s = account_summary(
|
||||
&Fake {
|
||||
exists: true,
|
||||
key: "someone-else",
|
||||
balances: vec![],
|
||||
},
|
||||
&NearNetwork::shipped().unwrap(),
|
||||
&AssetRegistry::shipped().unwrap(),
|
||||
id("k"),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(s.exists && !s.key_on_account);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn base32_matches_rfc4648() {
|
||||
// RFC 4648 §10, lowercased and unpadded.
|
||||
for (input, want) in [
|
||||
("", ""),
|
||||
("f", "my"),
|
||||
("fo", "mzxq"),
|
||||
("foo", "mzxw6"),
|
||||
("foob", "mzxw6yq"),
|
||||
("fooba", "mzxw6ytb"),
|
||||
("foobar", "mzxw6ytboi"),
|
||||
] {
|
||||
assert_eq!(base32_lower(input.as_bytes()), want);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_sponsored_account_is_named_from_its_key_and_lands_on_shard_8() {
|
||||
let n = NearNetwork::shipped().unwrap();
|
||||
let name = sponsored_account(&[0xff; 32], &n.sponsor);
|
||||
assert_eq!(name, "b7777777777777777.blackbeard-observer.near");
|
||||
assert!(name.len() <= 64, "a NEAR account id is at most 64 bytes");
|
||||
for digest in [[0u8; 32], [0xff; 32], [0x5a; 32]] {
|
||||
assert_eq!(
|
||||
mainnet().shard_of(&sponsored_account(&digest, &n.sponsor)),
|
||||
8
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_shard_url_without_its_placeholder_is_refused() {
|
||||
assert!(
|
||||
NearNetwork::from_toml(
|
||||
"shard_url = \"https://x\"\nserved_shards = []\nfallback = [\"https://y\"]"
|
||||
"shard_url = \"https://x\"\nserved_shards = []\nfallback = [\"https://y\"]\nsponsor = \"s.near\""
|
||||
)
|
||||
.is_err()
|
||||
);
|
||||
|
||||
@@ -8,8 +8,14 @@
|
||||
# shard's name. A shard we do not serve, or a name that is down, falls back
|
||||
# to the public RPCs, in order.
|
||||
#
|
||||
# The sponsor creates each wallet's account as a sub-account of its own,
|
||||
# named from the wallet's key (#81), and publishes its terms on
|
||||
# blackbeard.observer. Until protocol 87's PQ implicit accounts, a NEAR
|
||||
# account must be created by an existing one.
|
||||
#
|
||||
# An operator file `<data>/near.toml` of the same shape replaces this one.
|
||||
|
||||
shard_url = "https://s{shard}.near.blackbeard.observer"
|
||||
served_shards = [4, 7, 8, 10, 12, 13]
|
||||
fallback = ["https://rpc.mainnet.fastnear.com", "https://rpc.mainnet.near.org"]
|
||||
sponsor = "blackbeard-observer.near"
|
||||
|
||||
@@ -349,5 +349,12 @@
|
||||
"symbol": "SOL",
|
||||
"contractAddress": "0x0d829a23c3a3760e2fed60ca24d83cee8943f7c61859608ae0726fdb2e4f2784",
|
||||
"coingeckoId": "solana"
|
||||
},
|
||||
{
|
||||
"assetId": "nep141:qtc.omft.near",
|
||||
"decimals": 12,
|
||||
"blockchain": "qtc",
|
||||
"symbol": "QTC",
|
||||
"coingeckoId": "custom:qtc"
|
||||
}
|
||||
]
|
||||
@@ -88,13 +88,18 @@ impl NearKey {
|
||||
/// The handle state keeps and key listings show:
|
||||
/// `ml-dsa-65-hash:<base58 of SHA3-256(tag ‖ public key)>`.
|
||||
pub fn handle(&self) -> String {
|
||||
format!(
|
||||
"ml-dsa-65-hash:{}",
|
||||
bs58::encode(self.handle_digest()).into_string()
|
||||
)
|
||||
}
|
||||
|
||||
/// The handle's 32 bytes, from which the sponsor names the account.
|
||||
pub fn handle_digest(&self) -> [u8; 32] {
|
||||
let mut h = Sha3_256::new();
|
||||
h.update(HANDLE_TAG);
|
||||
h.update(&self.public);
|
||||
format!(
|
||||
"ml-dsa-65-hash:{}",
|
||||
bs58::encode(h.finalize()).into_string()
|
||||
)
|
||||
h.finalize().into()
|
||||
}
|
||||
|
||||
/// Sign under the empty context, as NEAR verifies. Hedged: fresh
|
||||
|
||||
@@ -514,7 +514,7 @@ mod tests {
|
||||
let refused = p
|
||||
.quote_request(
|
||||
&SwapRequest {
|
||||
from: asset("quantus", AssetKind::Native),
|
||||
from: asset("planck", AssetKind::Native),
|
||||
to: usdc_near(),
|
||||
amount_in: Amount::new(1, 12),
|
||||
recipient: "x".into(),
|
||||
@@ -525,7 +525,7 @@ mod tests {
|
||||
)
|
||||
.unwrap_err();
|
||||
assert!(
|
||||
matches!(refused, SwapError::UnsupportedPair(ref a) if a == "quantus/native"),
|
||||
matches!(refused, SwapError::UnsupportedPair(ref a) if a == "planck/native"),
|
||||
"{refused}"
|
||||
);
|
||||
}
|
||||
|
||||
@@ -706,6 +706,42 @@ pub struct WormholeSummary {
|
||||
pub leaf_count: u64,
|
||||
}
|
||||
|
||||
/// The open wallet's NEAR Intents account (blackbeard/wallet #74): the
|
||||
/// NEAR account its phrase's ML-DSA-65 key (NEP-649) controls, named by the
|
||||
/// 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.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
|
||||
#[ts(export)]
|
||||
pub struct NearAccountSummary {
|
||||
pub wallet: String,
|
||||
/// `b<…>.blackbeard-observer.near`, whether or not it exists yet.
|
||||
pub account_id: String,
|
||||
/// `ml-dsa-65:<base58>`: the key that controls it.
|
||||
pub public_key: String,
|
||||
/// The NEP-649 path the key is derived at.
|
||||
pub derivation_path: String,
|
||||
/// Whether the account exists on NEAR.
|
||||
pub exists: bool,
|
||||
/// Whether this wallet's key is one of the account's access keys. False
|
||||
/// for an existing account means it is not this wallet's to use.
|
||||
pub key_on_account: bool,
|
||||
/// Native NEAR, which pays the account's gas. `None` until it exists.
|
||||
pub gas: Option<Amount>,
|
||||
/// What the account holds inside NEAR Intents, by the assets the wallet
|
||||
/// knows; nonzero balances only.
|
||||
pub intents: Vec<IntentsBalance>,
|
||||
}
|
||||
|
||||
/// One token held inside NEAR Intents.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
|
||||
#[ts(export)]
|
||||
pub struct IntentsBalance {
|
||||
/// The Intents token id, `nep141:<contract>`.
|
||||
pub token: String,
|
||||
pub symbol: String,
|
||||
pub amount: Amount,
|
||||
}
|
||||
|
||||
/// Where a swap order is in its life (blackbeard/wallet #39). Terminal
|
||||
/// states are `Success`, `Refunded`, `Failed` and `Expired`.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
|
||||
|
||||
@@ -30,11 +30,17 @@ rather than a rewrite:
|
||||
metadata plus a small per-chain profile (ss58 prefix, decimals, signature
|
||||
enum, transaction extensions, signing-context rule, coin type).
|
||||
- `SwapProvider` is a swap venue. NEAR Intents first.
|
||||
- `NearRpc` is NEAR, the chain under the wallet's intents account, routed to
|
||||
a node that tracks the shard of the account each call is about.
|
||||
- `FiatRamp` builds a provider session through a relay on our infrastructure,
|
||||
which holds the provider secrets, and opens it in the system browser.
|
||||
|
||||
The wallet is **post-quantum only**. Classical chains appear only as transit
|
||||
legs of a swap or ramp; the wallet never derives a secp256k1 or ed25519 key.
|
||||
That includes NEAR: the intents account is a NEAR account whose only key is
|
||||
ML-DSA-65 (NEP-645), derived from the wallet's phrase as NEP-649 specifies.
|
||||
NEAR verifies it under the empty FIPS 204 context, where Quantus requires
|
||||
`QUANTUS_EXTRINSIC`.
|
||||
|
||||
## Why these choices
|
||||
|
||||
@@ -45,10 +51,12 @@ else, so the core is Rust. Tauri is the house desktop convention
|
||||
(`~/git/architecture/generic.md` §4) and the only shell that packages rpm, deb,
|
||||
msi and dmg with a Rust-owned IPC boundary out of the box.
|
||||
|
||||
NEAR's post-quantum work (their MPC fork with threshold ML-DSA-87) is not yet
|
||||
able to sign a Quantus extrinsic, so the swap module is built and tested
|
||||
against chains NEAR Intents already lists, with Quantus as a registry entry
|
||||
that lights up when the bridge does.
|
||||
QTC reaches NEAR as `qtc.omft.near` through a bridge with a deposit address
|
||||
per account, and its liquidity is in Ref pools rather than with 1Click's
|
||||
solvers. So swaps run through an intents account the wallet holds (#71),
|
||||
using only calls `intents.near` authorises by the calling account. Its
|
||||
signed intents (`execute_intents`) accept classical signatures only, and the
|
||||
wallet never makes one. #72 ran the whole route that way on mainnet.
|
||||
|
||||
## Building
|
||||
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
|
||||
import type { Amount } from "./Amount";
|
||||
|
||||
/**
|
||||
* One token held inside NEAR Intents.
|
||||
*/
|
||||
export type IntentsBalance = {
|
||||
/**
|
||||
* The Intents token id, `nep141:<contract>`.
|
||||
*/
|
||||
token: string, symbol: string, amount: Amount, };
|
||||
@@ -0,0 +1,41 @@
|
||||
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
|
||||
import type { Amount } from "./Amount";
|
||||
import type { IntentsBalance } from "./IntentsBalance";
|
||||
|
||||
/**
|
||||
* The open wallet's NEAR Intents account (blackbeard/wallet #74): the
|
||||
* NEAR account its phrase's ML-DSA-65 key (NEP-649) controls, named by the
|
||||
* 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,
|
||||
/**
|
||||
* `b<…>.blackbeard-observer.near`, whether or not it exists yet.
|
||||
*/
|
||||
account_id: string,
|
||||
/**
|
||||
* `ml-dsa-65:<base58>`: the key that controls it.
|
||||
*/
|
||||
public_key: string,
|
||||
/**
|
||||
* The NEP-649 path the key is derived at.
|
||||
*/
|
||||
derivation_path: string,
|
||||
/**
|
||||
* Whether the account exists on NEAR.
|
||||
*/
|
||||
exists: boolean,
|
||||
/**
|
||||
* Whether this wallet's key is one of the account's access keys. False
|
||||
* for an existing account means it is not this wallet's to use.
|
||||
*/
|
||||
key_on_account: boolean,
|
||||
/**
|
||||
* Native NEAR, which pays the account's gas. `None` until it exists.
|
||||
*/
|
||||
gas: Amount | null,
|
||||
/**
|
||||
* What the account holds inside NEAR Intents, by the assets the wallet
|
||||
* knows; nonzero balances only.
|
||||
*/
|
||||
intents: Array<IntentsBalance>, };
|
||||
@@ -22,6 +22,7 @@ import type { SwapAsk } from './generated/SwapAsk'
|
||||
import type { SwapPreview } from './generated/SwapPreview'
|
||||
import type { HistoryPage } from './generated/HistoryPage'
|
||||
import type { WalletSummary } from './generated/WalletSummary'
|
||||
import type { NearAccountSummary } from './generated/NearAccountSummary'
|
||||
import type { WormholeSummary } from './generated/WormholeSummary'
|
||||
import type { WalletError as WalletErrorShape } from './generated/WalletError'
|
||||
|
||||
@@ -221,6 +222,12 @@ 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 })
|
||||
}
|
||||
|
||||
// Swaps, in preview: the assets the provider and the registry agree on, a
|
||||
// dry quote, an order (a wet quote persisted with its deposit address),
|
||||
// and the list. Rust follows open orders and emits `orders:updated`.
|
||||
|
||||
@@ -0,0 +1,100 @@
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import { copyText } from '../api/clipboard'
|
||||
import { nearAccount } 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.
|
||||
*/
|
||||
export function NearIntentsPanel({ wallet }: { wallet: string }) {
|
||||
const account = useQuery({
|
||||
queryKey: ['near-account', wallet],
|
||||
queryFn: () => nearAccount(wallet),
|
||||
staleTime: 30_000,
|
||||
retry: 1,
|
||||
})
|
||||
const a = account.data
|
||||
return (
|
||||
<section className="panel">
|
||||
<div className="panel-head">
|
||||
<h2 className="panel-title">NEAR Intents account · {wallet}</h2>
|
||||
{a && (
|
||||
<span className="muted" style={{ fontSize: 12 }}>
|
||||
{a.exists ? (a.key_on_account ? 'active' : 'not this wallet’s key') : 'not created yet'}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<div className="panel-body">
|
||||
{account.isPending && <p className="muted">Reading NEAR…</p>}
|
||||
{account.isError && <p className="error">{account.error.message}</p>}
|
||||
{a && (
|
||||
<div data-testid="near-account">
|
||||
<div className="field">
|
||||
<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.
|
||||
</span>
|
||||
</div>
|
||||
{!a.exists && (
|
||||
<p className="muted">
|
||||
Swaps run through this account. It is created for you by the wallet’s sponsor,
|
||||
which is not open yet.
|
||||
</p>
|
||||
)}
|
||||
{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.
|
||||
</p>
|
||||
)}
|
||||
{a.exists && (
|
||||
<table className="table review">
|
||||
<tbody>
|
||||
<tr>
|
||||
<th>Gas</th>
|
||||
<td className="numeral">
|
||||
{a.gas ? formatAmount(a.gas) : '—'} NEAR
|
||||
<span className="muted"> pays this account’s transactions</span>
|
||||
</td>
|
||||
</tr>
|
||||
{a.intents.length === 0 && (
|
||||
<tr>
|
||||
<th>Held</th>
|
||||
<td className="muted">Nothing in NEAR Intents yet.</td>
|
||||
</tr>
|
||||
)}
|
||||
{a.intents.map((b) => (
|
||||
<tr key={b.token}>
|
||||
<th>{b.symbol}</th>
|
||||
<td className="numeral">
|
||||
{formatAmount(b.amount)} {b.symbol}
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
)}
|
||||
<div className="row">
|
||||
<button className="button" type="button" onClick={() => copyText(a.account_id)}>
|
||||
Copy account
|
||||
</button>
|
||||
<button
|
||||
className="button"
|
||||
type="button"
|
||||
onClick={() => account.refetch()}
|
||||
disabled={account.isFetching}
|
||||
>
|
||||
{account.isFetching ? 'Reading…' : 'Refresh'}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</section>
|
||||
)
|
||||
}
|
||||
@@ -12,6 +12,7 @@ import { AccountName } from '../components/AccountName'
|
||||
import { ChainCaveat } from '../components/ChainCaveat'
|
||||
import { NetworkOverview } from '../components/NetworkOverview'
|
||||
import { PendingReversibleList } from '../components/PendingReversible'
|
||||
import { NearIntentsPanel } from '../components/NearIntentsPanel'
|
||||
import { WormholePanel } from '../components/WormholePanel'
|
||||
import { schemeLabel } from '../lib/accounts'
|
||||
import { formatAmount } from '../lib/format'
|
||||
@@ -177,6 +178,11 @@ 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} />
|
||||
))}
|
||||
<NetworkOverview />
|
||||
</>
|
||||
)
|
||||
|
||||
Reference in New Issue
Block a user