Files
observer/crates/blackbeard-api/src/poolscan.rs
T
grenadeandClaude Opus 5.5 6152ba85c2
ci / gate (push) Successful in 4m5s
deploy / validate (push) Skipped
deploy / build (push) Successful in 9m0s
deploy / deploy-web (push) Successful in 8s
deploy / deploy-api (push) Successful in 19s
fix(api): queue only direct pool calls about the asset, and re-read the rest
The direct-call scan matched any transaction reaching the DCL contract,
which hosts hundreds of pools: 4,881 strangers' swaps queued in the first
hour after launch, from 176 signers, each to be fetched from a
rate-limited public endpoint — enough on its own to keep the market page
starved. A call now counts only when it moves the asset itself or its
arguments name the asset's contract, which every pool id holding it does;
a buy with any token names the pool, a sell is a transfer of the asset.

ref_pending keeps no arguments, so the bad entries cannot be filtered in
place: migration 0016 drops every entry not signed by the relay and the
scan's cursor, and the scan reads the span again from our node.

Refs #39

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015pkwBsR54NRmZyU4QVhvfj
2026-10-06 19:01:29 +03:00

279 lines
11 KiB
Rust

//! Direct calls to the asset's pools, read on the shards the calls are signed on.
//!
//! `intents::scan` finds a pool swap only when the 1Click relay made it, because
//! it reads intents.near's shard and a transaction lands in its *signer's*
//! shard. The pool's whitelisted accounts also call it themselves — to trade, to
//! add or pull liquidity — and those transactions are signed on other shards:
//! `liq.selfevident.near` and `solver-ref-2.near` are on the shard the token
//! contract is on, the pool on another. Our coverage figure measured the gap
//! (#37: 99.75% of buys); this closes it for every signer on a shard a tracked
//! node holds (blackbeard/observer#39).
//!
//! It only finds candidates. Each goes into `ref_pending` and is read whole by
//! `refdcl::fetch`, the same path as the relay's, so a swap is parsed one way
//! whichever road it arrived by and recorded once on its `(tx, receipt, index)`
//! key. A candidate that turns out not to be a swap — a liquidity change, say —
//! yields no swap event and records nothing.
//!
//! Only what the node holds is read: forward from wherever the cursor stands,
//! and back no further than the oldest block the node has. History before the
//! node synced is the coverage figure's to account for, not a public endpoint's
//! to be paced through for days.
use std::collections::BTreeSet;
use std::sync::Arc;
use std::time::Duration;
use blackbeard_core::intents as core;
use blackbeard_data::near::NearClient;
use blackbeard_data::store::Store;
use crate::config::IntentsConfig;
use crate::state::ChainRuntime;
/// NEAR heights read per pass, as for the intents scan.
const BATCH: u64 = 64;
/// Wait at the tip before asking again.
const TIP_WAIT: Duration = Duration::from_secs(1);
/// Wait after a failure — including the node not having synced the shards yet.
const RETRY: Duration = Duration::from_secs(15);
/// How long a NEAR call may take.
const NEAR_TIMEOUT: Duration = Duration::from_secs(20);
/// The cursor's key in `intents_scan`, distinct from the intents scan's own so
/// the two never share a position.
fn cursor_key(asset: &str) -> String {
format!("pool-calls:{asset}")
}
/// Start the scan, if a node is configured for it.
pub fn spawn(chain: Arc<ChainRuntime>, store: Store, config: IntentsConfig) {
if config.pool_rpc_urls.is_empty()
|| config.dcl_contracts.is_empty()
|| config.token_contract().is_none()
{
return;
}
// The node's own endpoints for everything it can answer; the archive is
// never consulted, because nothing below the node's oldest block is read.
let near = match NearClient::new(
config.pool_rpc_urls.clone(),
config.pool_rpc_urls.clone(),
config.view_urls.clone(),
NEAR_TIMEOUT,
) {
Ok(n) => n,
Err(e) => {
tracing::error!(chain = %chain.id(), error = %e, "pool call scan not started");
return;
}
};
tracing::info!(chain = %chain.id(), endpoints = ?config.pool_rpc_urls,
"following direct calls to the asset's pools");
tokio::spawn(scan(chain, store, near, config));
}
/// Whether a transaction calls one of `pools` about the asset: directly, or by
/// sending a token to it with `ft_transfer_call`, which is how a DCL swap is
/// paid for.
///
/// "About the asset" is not optional. A DCL contract hosts hundreds of pools,
/// and matching any call to it queued 4,151 transactions in the first twenty
/// minutes after launch — strangers' swaps in unrelated pools, each to be
/// fetched from a rate-limited public endpoint. A call concerns the asset when
/// it moves the asset itself (the token contract is the receiver) or its
/// arguments name the asset's contract, which every pool id holding it does.
fn calls_pool(
tx: &blackbeard_data::near::ChunkTransaction,
pools: &BTreeSet<String>,
asset_contract: &str,
) -> bool {
let reaches_pool = pools.contains(&tx.receiver_id)
|| tx
.ft_transfer_call_receivers()
.iter()
.any(|r| pools.contains(r));
reaches_pool && (tx.receiver_id == asset_contract || tx.args_mention(asset_contract))
}
async fn scan(chain: Arc<ChainRuntime>, store: Store, near: NearClient, config: IntentsConfig) {
let id = chain.id();
let key = cursor_key(&config.asset);
let pools = crate::refdcl::contracts(&config);
let asset_contract = config.token_contract().unwrap_or_default().to_owned();
loop {
if chain.read().current_runtime().is_none() {
tokio::time::sleep(RETRY).await;
continue;
}
let (tip, oldest) = match near.heights().await {
Ok(h) => h,
Err(e) => {
tracing::debug!(chain = %id, error = %e, "pool call node not answering");
tokio::time::sleep(RETRY).await;
continue;
}
};
let cursor = match store.intents_scan(&id, &key).await {
Ok(c) => c,
Err(e) => {
tracing::warn!(chain = %id, error = %e, "pool call cursor unreadable");
tokio::time::sleep(RETRY).await;
continue;
}
};
let (low, high) = cursor.unwrap_or((tip, tip.saturating_sub(1)));
let floor = oldest.max(config.start_height);
let (heights, descending): (Vec<u64>, bool) = if high < tip {
((high + 1..=tip.min(high + BATCH)).collect(), false)
} else if low > floor {
let from = low.saturating_sub(BATCH).max(floor);
((from..low).rev().collect(), true)
} else {
tokio::time::sleep(TIP_WAIT).await;
continue;
};
let mut layout = None;
for &height in &heights {
match near.shard_layout(height).await {
Ok(l) => {
layout = Some(l);
break;
}
Err(e) if blackbeard_data::near::unknown(&e) => continue,
Err(e) => {
tracing::warn!(chain = %id, error = %e, "pool call shard layout unreadable");
break;
}
}
}
let Some(layout) = layout else {
tokio::time::sleep(RETRY).await;
continue;
};
// The shards a direct call can be signed on that this node holds: the
// pools' and the token's. intents.near's is left to the intents scan.
let shard_of =
|account: &str| core::shard_for(account, &layout.boundary_accounts, &layout.shard_ids);
let relay_shard = shard_of(&config.contract);
let shards: BTreeSet<u64> = pools
.iter()
.map(String::as_str)
.chain(std::iter::once(asset_contract.as_str()))
.filter_map(shard_of)
.filter(|s| Some(*s) != relay_shard)
.collect();
let mut reached = None;
'heights: for &height in &heights {
for &shard in &shards {
let chunk = match near.chunk(height, shard, oldest).await {
Ok(c) => c,
Err(e) => {
tracing::warn!(chain = %id, near_height = height, shard, error = %e,
"pool call chunk unreadable; will retry");
break 'heights;
}
};
let Some(chunk) = chunk else { continue };
for tx in chunk
.transactions
.iter()
.filter(|t| calls_pool(t, &pools, &asset_contract))
{
if let Err(e) = store
.queue_ref_pending(&id, &tx.hash, &tx.signer_id, height, &tx.signer_id)
.await
{
tracing::warn!(chain = %id, tx = %tx.hash, error = %e,
"direct pool call not queued");
break 'heights;
}
tracing::info!(chain = %id, near_height = height, shard, tx = %tx.hash,
signer = %tx.signer_id, "direct pool call queued");
}
}
reached = Some(height);
}
if let Some(reached) = reached {
let (new_low, new_high) = if descending {
(reached, high)
} else {
(low.min(heights[0]), reached)
};
if let Err(e) = store.set_intents_scan(&id, &key, new_low, new_high).await {
tracing::warn!(chain = %id, error = %e, "pool call cursor not saved");
}
} else {
tokio::time::sleep(RETRY).await;
}
}
}
#[cfg(test)]
mod tests {
use super::*;
fn tx(receiver: &str, actions: serde_json::Value) -> blackbeard_data::near::ChunkTransaction {
serde_json::from_value(serde_json::json!({
"hash": "h", "signer_id": "liq.selfevident.near",
"receiver_id": receiver, "actions": actions,
}))
.unwrap()
}
#[test]
fn a_pool_call_concerns_the_asset_or_is_not_one() {
let pools: BTreeSet<String> = ["dclv2.ref-labs.near".to_owned()].into();
let asset = "qtc.omft.near";
let b64 = |v: serde_json::Value| {
use base64::Engine as _;
base64::engine::general_purpose::STANDARD.encode(v.to_string())
};
let call = |receiver: &str, method: &str, args: serde_json::Value| {
tx(
receiver,
serde_json::json!([{"FunctionCall": {"method_name": method, "args": b64(args), "gas": 1, "deposit": "1"}}]),
)
};
// A whitelisted account pulling liquidity from the asset's pool.
let ours = call(
"dclv2.ref-labs.near",
"remove_liquidity",
serde_json::json!({"lpt_id": "17208628f84f5d6ad33f0da3bbbeb27ffcb398eac501a31bd6ad2011e36133a1|qtc.omft.near|2000#1"}),
);
// Selling the asset into the pool: the token is the receiver.
let sold = call(
"qtc.omft.near",
"ft_transfer_call",
serde_json::json!({"receiver_id": "dclv2.ref-labs.near", "amount": "1", "msg": ""}),
);
// A stranger's swap in an unrelated pool on the same contract.
let stranger = call(
"dclv2.ref-labs.near",
"swap",
serde_json::json!({"pool_ids": ["wrap.near|usdt.tether-token.near|100"]}),
);
// A transfer of the asset somewhere other than the pool.
let elsewhere = call(
"qtc.omft.near",
"ft_transfer",
serde_json::json!({"receiver_id": "dclv2.ref-labs.near", "amount": "1"}),
);
assert!(calls_pool(&ours, &pools, asset));
assert!(calls_pool(&sold, &pools, asset));
assert!(!calls_pool(&stranger, &pools, asset));
assert!(!calls_pool(&elsewhere, &pools, asset));
}
#[test]
fn the_cursor_never_shares_the_intents_scan_key() {
assert_ne!(cursor_key("nep141:qtc.omft.near"), "nep141:qtc.omft.near");
}
}