feat: QTC into and out of NEAR Intents, block by block
ci / gate (push) Successful in 4m23s
deploy / validate (push) Skipped
deploy / build (push) Successful in 9m6s
deploy / deploy-web (push) Successful in 8s
deploy / deploy-api (push) Successful in 20s

#39 item 4, as replaced: the original check (intents.near's balance against
indexed events) could not see the trades it was for, because a trade moves
QTC inside intents.near and leaves its total alone. What the balance does
move with is deposits and withdrawals, so that is what is recorded.

`intentsflow` reads intents.near's `ft_balance_of` on qtc.omft.near at
every NEAR block from gargravarr, which tracks the token's shard, forward
to its final block and back to the oldest it holds, and records each
change (migration 0015). `view_at` treats only UNKNOWN_BLOCK as a skipped
height: a garbage-collected block is an error, never "nothing changed".
`/v1/chains/{chain}/intents/flows` sums deposits and withdrawals over a
span; the NEAR Intents market page shows it after the bridge.

Verified on the live chain through a tunnel to gargravarr: the scan's
balance at #218,805,000 (36,044.097 QTC) and at #218,811,064 (72,671.542)
match direct reads, and across 1,044 rows every balance less its change
is the previous balance.

Refs #39

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015pkwBsR54NRmZyU4QVhvfj
This commit is contained in:
2026-10-06 18:54:40 +03:00
co-authored by Claude Opus 5.5
parent 0851b244ba
commit 6116954f13
17 changed files with 935 additions and 4 deletions
@@ -0,0 +1,42 @@
{
"db_name": "PostgreSQL",
"query": "\n select near_height, at, balance::text as \"balance!\", delta::text as \"delta!\"\n from intents_flow\n where chain = $1 and asset = $2 and at < $3\n order by near_height desc limit 1\n ",
"describe": {
"columns": [
{
"ordinal": 0,
"name": "near_height",
"type_info": "Int8"
},
{
"ordinal": 1,
"name": "at",
"type_info": "Timestamptz"
},
{
"ordinal": 2,
"name": "balance!",
"type_info": "Text"
},
{
"ordinal": 3,
"name": "delta!",
"type_info": "Text"
}
],
"parameters": {
"Left": [
"Text",
"Text",
"Timestamptz"
]
},
"nullable": [
false,
false,
null,
null
]
},
"hash": "823cc59fea23e31233de6bf243cd40ba65b634c7b01e09238b71b3ddea18425d"
}
@@ -0,0 +1,42 @@
{
"db_name": "PostgreSQL",
"query": "\n select near_height, at, balance::text as \"balance!\", delta::text as \"delta!\"\n from intents_flow\n where chain = $1 and asset = $2 and at >= $3\n order by near_height\n ",
"describe": {
"columns": [
{
"ordinal": 0,
"name": "near_height",
"type_info": "Int8"
},
{
"ordinal": 1,
"name": "at",
"type_info": "Timestamptz"
},
{
"ordinal": 2,
"name": "balance!",
"type_info": "Text"
},
{
"ordinal": 3,
"name": "delta!",
"type_info": "Text"
}
],
"parameters": {
"Left": [
"Text",
"Text",
"Timestamptz"
]
},
"nullable": [
false,
false,
null,
null
]
},
"hash": "aa19fadeadd2ff3f7e24029a8c12541595302b47196575fae24c7561263856e7"
}
@@ -0,0 +1,19 @@
{
"db_name": "PostgreSQL",
"query": "\n insert into intents_flow (chain, asset, near_height, at, balance, delta)\n values ($1, $2, $3, $4, $5::text::numeric, $6::text::numeric)\n on conflict (chain, asset, near_height) do update\n set at = excluded.at, balance = excluded.balance, delta = excluded.delta\n ",
"describe": {
"columns": [],
"parameters": {
"Left": [
"Text",
"Text",
"Int8",
"Timestamptz",
"Text",
"Text"
]
},
"nullable": []
},
"hash": "f32c1bf7d92ff4f804dcf96d3069f095d7fdd6c68617602229965e99c941e246"
}
+1
View File
@@ -124,6 +124,7 @@ pub fn spawn(chain: Arc<ChainRuntime>, store: Store) {
config.clone(),
);
crate::poolscan::spawn(Arc::clone(&chain), store.clone(), config.clone());
crate::intentsflow::spawn(Arc::clone(&chain), store.clone(), config.clone());
tokio::spawn(scan(chain, store, near, config));
}
+232
View File
@@ -0,0 +1,232 @@
//! QTC moving into and out of NEAR Intents, block by block
//! (blackbeard/observer#39, item 4 as replaced on 2026-10-06).
//!
//! intents.near's own balance of the token, read at every NEAR block from a
//! node tracking the token's shard — gargravarr, through `pool_rpc_urls` — and
//! recorded where it changed. Up is a deposit, down a withdrawal. Trades are
//! invisible here by construction: they move balances inside intents.near and
//! leave its total alone.
//!
//! Every call goes to our own node at a named block, so the public endpoint's
//! rate limit never applies and a node behind the tip is no problem: it is
//! read only as far as its own final block, and back no further than the
//! oldest block it holds.
use std::sync::Arc;
use std::time::Duration;
use blackbeard_data::near::NearClient;
use blackbeard_data::store::{IntentsFlow, Store};
use serde_json::json;
use crate::config::IntentsConfig;
use crate::state::ChainRuntime;
/// Heights read per pass. A pass is written whole or not at all.
const BATCH: u64 = 64;
/// Wait at the node's final block.
const TIP_WAIT: Duration = Duration::from_secs(2);
/// Wait after a failure.
const RETRY: Duration = Duration::from_secs(15);
/// How long one NEAR call may take.
const NEAR_TIMEOUT: Duration = Duration::from_secs(20);
/// The cursor's key in `intents_scan`, apart from every other scan's.
fn cursor_key(asset: &str) -> String {
format!("intents-balance:{asset}")
}
/// Start the scan when a node tracking the token's shard is configured.
pub fn spawn(chain: Arc<ChainRuntime>, store: Store, config: IntentsConfig) {
if config.pool_rpc_urls.is_empty() || config.token_contract().is_none() {
return;
}
let near = match NearClient::new(
config.pool_rpc_urls.clone(),
config.pool_rpc_urls.clone(),
config.pool_rpc_urls.clone(),
NEAR_TIMEOUT,
) {
Ok(n) => n,
Err(e) => {
tracing::error!(chain = %chain.id(), error = %e, "intents flow scan not started");
return;
}
};
tokio::spawn(scan(chain, store, near, config));
}
/// intents.near's balance at `height`, or `None` for a height never produced.
async fn balance_at(
near: &NearClient,
token: &str,
holder: &str,
height: u64,
) -> Result<Option<u128>, blackbeard_data::DataError> {
let Some(v) = near
.view_at(
token,
"ft_balance_of",
json!({"account_id": holder}),
height,
)
.await?
else {
return Ok(None);
};
v.as_str()
.and_then(|s| s.parse().ok())
.map(Some)
.ok_or_else(|| blackbeard_data::DataError::Malformed {
method: "ft_balance_of".into(),
message: format!("not a balance: {v}"),
})
}
/// The balance changes across `heights` (ascending), given the balance at the
/// block before the first. Skipped heights change nothing.
async fn read_span(
near: &NearClient,
token: &str,
holder: &str,
mut previous: u128,
heights: &[u64],
) -> Result<Vec<IntentsFlow>, blackbeard_data::DataError> {
let mut out = Vec::new();
for &h in heights {
let Some(balance) = balance_at(near, token, holder, h).await? else {
continue;
};
if balance != previous {
let (_, at) = near.block_at(json!(h)).await?;
out.push(IntentsFlow {
near_height: h,
at,
balance: balance.to_string(),
delta: (balance as i128 - previous as i128).to_string(),
});
previous = balance;
}
}
Ok(out)
}
/// The balance at the last produced block at or before `height`, walking down
/// past skipped heights to `floor`.
async fn balance_on_or_before(
near: &NearClient,
token: &str,
holder: &str,
height: u64,
floor: u64,
) -> Result<Option<u128>, blackbeard_data::DataError> {
let mut h = height;
loop {
if let Some(b) = balance_at(near, token, holder, h).await? {
return Ok(Some(b));
}
if h <= floor {
return Ok(None);
}
h -= 1;
}
}
async fn scan(chain: Arc<ChainRuntime>, store: Store, near: NearClient, config: IntentsConfig) {
let id = chain.id();
let key = cursor_key(&config.asset);
let token = config.token_contract().unwrap_or_default().to_owned();
let holder = config.contract.clone();
tracing::info!(chain = %id, %token, %holder, "following the asset into and out of NEAR Intents");
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, "flow 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, "flow cursor unreadable");
tokio::time::sleep(RETRY).await;
continue;
}
};
// The oldest block is the node's floor: its state before then is gone,
// and the first block above it has no "before" to compare with.
let floor = oldest.max(config.start_height) + 1;
let (low, high) = cursor.unwrap_or((tip, tip.saturating_sub(1)));
let (from, to, descending) = if high < tip {
(high + 1, tip.min(high + BATCH), false)
} else if low > floor {
(low.saturating_sub(BATCH).max(floor), low - 1, true)
} else {
tokio::time::sleep(TIP_WAIT).await;
continue;
};
let heights: Vec<u64> = (from..=to).collect();
let result = async {
let Some(previous) =
balance_on_or_before(&near, &token, &holder, from - 1, floor - 1).await?
else {
return Ok(None);
};
read_span(&near, &token, &holder, previous, &heights)
.await
.map(Some)
}
.await;
match result {
Ok(Some(rows)) => {
if let Err(e) = store.record_intents_flows(&id, &config.asset, &rows).await {
tracing::warn!(chain = %id, error = %e, "flows not recorded");
tokio::time::sleep(RETRY).await;
continue;
}
for r in &rows {
tracing::info!(chain = %id, near_height = r.near_height, delta = %r.delta,
"asset moved into or out of NEAR Intents");
}
let (new_low, new_high) = if descending {
(from, high)
} else {
(low.min(from), to)
};
if let Err(e) = store.set_intents_scan(&id, &key, new_low, new_high).await {
tracing::warn!(chain = %id, error = %e, "flow cursor not saved");
}
}
Ok(None) => {
tracing::warn!(chain = %id, from, "no produced block below the batch to compare with");
tokio::time::sleep(RETRY).await;
}
Err(e) => {
tracing::warn!(chain = %id, from, error = %e, "flow batch unreadable; will retry");
tokio::time::sleep(RETRY).await;
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_cursor_shares_no_key_with_the_other_scans() {
let k = cursor_key("nep141:qtc.omft.near");
assert_ne!(k, "nep141:qtc.omft.near");
assert_ne!(k, "pool-calls:nep141:qtc.omft.near");
}
}
+1
View File
@@ -11,6 +11,7 @@
mod config;
mod ingest;
mod intents;
mod intentsflow;
mod poolscan;
mod refdcl;
mod registry;
+100
View File
@@ -74,6 +74,7 @@ pub fn router(state: AppState, allowed_origins: &[String]) -> Router {
.route("/v1/chains/{chain}/ref/swaps", get(ref_swaps))
.route("/v1/chains/{chain}/ref/series", get(ref_series))
.route("/v1/chains/{chain}/ref/bids", get(ref_bids))
.route("/v1/chains/{chain}/intents/flows", get(intents_flows))
.route("/v1/chains/{chain}/bridge", get(bridge))
.route("/v1/chains/{chain}/nodes", get(nodes))
.route("/v1/chains/{chain}/nodes/{peer}", get(node))
@@ -2485,6 +2486,105 @@ async fn intents_series(
/// mixed with it: a pool swap is usually a solver restocking after an intents
/// fill, so one line over both would count one demand twice. Every pool swap
/// is a fill against the pool, so `taker_trades` equals `trades`.
#[derive(Debug, Deserialize)]
struct FlowsQuery {
/// Hours of history, default a day.
hours: Option<u64>,
}
/// The asset moving into and out of NEAR Intents (blackbeard/observer#39):
/// intents.near's own balance, read at every NEAR block.
async fn intents_flows(
State(state): State<AppState>,
Path(chain): Path<String>,
Query(query): Query<FlowsQuery>,
) -> Result<Json<blackbeard_entities::IntentsFlows>, Failure> {
let runtime = state.chain(&chain).ok_or_else(|| unknown_chain(&chain))?;
let config = runtime
.spec
.intents
.clone()
.ok_or_else(|| no_intents(&chain))?;
let id = runtime.id();
let hours = query.hours.unwrap_or(24).clamp(1, 24 * 30);
let since = chrono::Utc::now() - chrono::Duration::hours(hours as i64);
let rows = state
.store
.intents_flows_since(&id, &config.asset, since)
.await
.map_err(database_unavailable)?;
let before = state
.store
.intents_flow_before(&id, &config.asset, since)
.await
.map_err(database_unavailable)?;
let read = state
.store
.intents_scan(&id, &format!("intents-balance:{}", config.asset))
.await
.map_err(database_unavailable)?;
let meta = state
.store
.near_token(&config.asset)
.await
.map_err(database_unavailable)?;
let (mut deposited, mut withdrawn, mut deposits, mut withdrawals) = (0u128, 0u128, 0u64, 0u64);
for r in &rows {
match r.delta.parse::<i128>() {
Ok(d) if d > 0 => {
deposited += d as u128;
deposits += 1;
}
Ok(d) if d < 0 => {
withdrawn += d.unsigned_abs();
withdrawals += 1;
}
_ => {}
}
}
// The balance then: the last change before the span, or — when the span
// starts before anything was read — the first change's balance less its
// own delta, which is the balance the read started from.
let balance_then = before.map(|b| b.balance).or_else(|| {
rows.first().and_then(|r| {
let (b, d) = (
r.balance.parse::<i128>().ok()?,
r.delta.parse::<i128>().ok()?,
);
Some((b - d).to_string())
})
});
let balance_now = rows
.last()
.map(|r| r.balance.clone())
.or(balance_then.clone());
Ok(Json(blackbeard_entities::IntentsFlows {
chain: id,
asset_symbol: meta.as_ref().map(|m| m.0.clone()),
asset_decimals: meta.map(|m| m.1),
hours,
read_from: read.map(|r| r.0),
read_to: read.map(|r| r.1),
balance_then: balance_then.map(BigUintDec),
balance_now: balance_now.map(BigUintDec),
deposited: BigUintDec(deposited.to_string()),
withdrawn: BigUintDec(withdrawn.to_string()),
deposits,
withdrawals,
changes: rows
.into_iter()
.rev()
.map(|r| blackbeard_entities::IntentsFlowPoint {
near_height: r.near_height,
at: r.at,
balance: BigUintDec(r.balance),
delta: r.delta,
})
.collect(),
}))
}
#[derive(Debug, Deserialize)]
struct BidsQuery {
/// The pool, `token_x|token_y|fee`.
@@ -0,0 +1,23 @@
-- QTC moving into and out of NEAR Intents, block by block.
-- blackbeard/observer#39, item 4 as replaced on 2026-10-06.
--
-- intents.near's own balance of the token, read at every NEAR block from a
-- node tracking the token's shard, and recorded only where it changed. A rise
-- is the token deposited into NEAR Intents, a fall the token withdrawn. Trades
-- never appear here: they move balances between accounts inside intents.near
-- and leave its total untouched, which is why this cannot measure the trades
-- the relay scan misses, only the money arriving and leaving.
--
-- Exact for what it is, and blind to who: a deposit and a withdrawal in the
-- same block net to one row. Amounts are base units.
create table intents_flow (
chain text not null references chain (id) on delete cascade,
asset text not null,
near_height bigint not null,
at timestamptz not null,
-- intents.near's balance after this block.
balance numeric not null,
-- Its change from the block before: positive in, negative out.
delta numeric not null,
primary key (chain, asset, near_height)
);
+41
View File
@@ -488,6 +488,47 @@ impl NearClient {
}
impl NearClient {
/// A view call at one block, on the **live** endpoints: for a node of ours
/// that tracks the contract's shard and holds that block's state.
/// `Ok(None)` for a height that was never produced — NEAR skips heights,
/// and a skipped one has no state to have changed. A height whose state was
/// garbage-collected is an error, not `None`.
pub async fn view_at(
&self,
contract: &str,
method: &str,
args: Value,
height: u64,
) -> Result<Option<Value>, DataError> {
use base64::Engine as _;
let result = match self
.live
.call(
"query",
json!({
"request_type": "call_function",
"block_id": height,
"account_id": contract,
"method_name": method,
"args_base64": base64::engine::general_purpose::STANDARD.encode(args.to_string()),
}),
)
.await
{
Ok(r) => r,
// Only a height never produced. `unknown` also admits a garbage-
// collected block, and here that would read "state pruned away" as
// "nothing happened" and record no change for a block nobody can
// see any more; that stays an error.
Err(DataError::Rpc { ref message, .. }) if message.contains("UNKNOWN_BLOCK") => {
return Ok(None);
}
Err(e) => return Err(e),
};
let bytes: Vec<u8> = serde_json::from_value(result["result"].clone())?;
Ok(Some(serde_json::from_slice(&bytes)?))
}
/// Call a view method on the **live** endpoints rather than the view ones.
///
/// For a contract on the shard the live node tracks — `intents.near`,
+102
View File
@@ -299,6 +299,21 @@ pub struct IntentTrade {
pub legs: serde_json::Value,
}
/// One block where intents.near's balance of the asset changed
/// (blackbeard/observer#39). Amounts are base-unit decimal strings; `delta` is
/// signed.
#[derive(Debug, Clone)]
pub struct IntentsFlow {
/// NEAR block.
pub near_height: u64,
/// Its timestamp.
pub at: DateTime<Utc>,
/// intents.near's balance after it.
pub balance: String,
/// Change from the block before: positive in, negative out.
pub delta: String,
}
/// One read of a Ref DCL pool's state, base units as decimal strings
/// (blackbeard/observer#41).
#[derive(Debug, Clone)]
@@ -3499,6 +3514,93 @@ impl Store {
.collect())
}
/// Record balance changes, idempotently (a re-read writes the same rows).
pub async fn record_intents_flows(
&self,
chain: &ChainId,
asset: &str,
rows: &[IntentsFlow],
) -> Result<(), DataError> {
for r in rows {
sqlx::query!(
r#"
insert into intents_flow (chain, asset, near_height, at, balance, delta)
values ($1, $2, $3, $4, $5::text::numeric, $6::text::numeric)
on conflict (chain, asset, near_height) do update
set at = excluded.at, balance = excluded.balance, delta = excluded.delta
"#,
chain.as_str(),
asset,
r.near_height as i64,
r.at,
r.balance,
r.delta,
)
.execute(&self.pool)
.await?;
}
Ok(())
}
/// Balance changes at or after `since`, oldest first.
pub async fn intents_flows_since(
&self,
chain: &ChainId,
asset: &str,
since: DateTime<Utc>,
) -> Result<Vec<IntentsFlow>, DataError> {
let rows = sqlx::query!(
r#"
select near_height, at, balance::text as "balance!", delta::text as "delta!"
from intents_flow
where chain = $1 and asset = $2 and at >= $3
order by near_height
"#,
chain.as_str(),
asset,
since,
)
.fetch_all(&self.pool)
.await?;
Ok(rows
.into_iter()
.map(|r| IntentsFlow {
near_height: r.near_height.max(0) as u64,
at: r.at,
balance: r.balance,
delta: r.delta,
})
.collect())
}
/// The last balance change before `before`: the balance in force then.
pub async fn intents_flow_before(
&self,
chain: &ChainId,
asset: &str,
before: DateTime<Utc>,
) -> Result<Option<IntentsFlow>, DataError> {
let row = sqlx::query!(
r#"
select near_height, at, balance::text as "balance!", delta::text as "delta!"
from intents_flow
where chain = $1 and asset = $2 and at < $3
order by near_height desc limit 1
"#,
chain.as_str(),
asset,
before,
)
.fetch_optional(&self.pool)
.await?;
Ok(row.map(|r| IntentsFlow {
near_height: r.near_height.max(0) as u64,
at: r.at,
balance: r.balance,
delta: r.delta,
}))
}
/// Every `(contract, pool_id)` a swap of the asset has been recorded in —
/// pools that certainly hold it, known without asking anyone.
pub async fn ref_known_pools(
+56
View File
@@ -554,3 +554,59 @@ pub struct BidSide {
/// Every level change in the span, newest first.
pub changes: Vec<BidChange>,
}
/// One block where intents.near's balance of the asset changed
/// (blackbeard/observer#39).
#[derive(Debug, Clone, Serialize, Deserialize, TS)]
#[ts(export, export_to = "IntentsFlowPoint.ts")]
pub struct IntentsFlowPoint {
/// NEAR block.
#[ts(type = "number")]
pub near_height: u64,
/// Its time.
pub at: DateTime<Utc>,
/// intents.near's balance after it, base units.
pub balance: BigUintDec,
/// The change, base units, signed: positive deposited, negative withdrawn.
pub delta: String,
}
/// The asset moving into and out of NEAR Intents over the last `hours`, read
/// block by block from intents.near's own balance (blackbeard/observer#39).
/// Exact for the money arriving and leaving; blind to who moved it, and a
/// deposit and a withdrawal in one block net to one change.
#[derive(Debug, Clone, Serialize, Deserialize, TS)]
#[ts(export, export_to = "IntentsFlows.ts")]
pub struct IntentsFlows {
/// Which chain's token.
pub chain: ChainId,
/// The asset's symbol on NEAR.
pub asset_symbol: Option<String>,
/// Its decimals on NEAR.
pub asset_decimals: Option<u8>,
/// Hours covered.
#[ts(type = "number")]
pub hours: u64,
/// The NEAR blocks read so far, inclusive: nothing outside them is known.
#[ts(type = "number")]
pub read_from: Option<u64>,
/// Highest NEAR block read.
#[ts(type = "number")]
pub read_to: Option<u64>,
/// The balance at the start of the span, when known.
pub balance_then: Option<BigUintDec>,
/// The balance after the newest change.
pub balance_now: Option<BigUintDec>,
/// Summed rises in the span, base units.
pub deposited: BigUintDec,
/// Summed falls in the span, base units, as a positive amount.
pub withdrawn: BigUintDec,
/// Blocks with a rise.
#[ts(type = "number")]
pub deposits: u64,
/// Blocks with a fall.
#[ts(type = "number")]
pub withdrawals: u64,
/// Every change in the span, newest first.
pub changes: Vec<IntentsFlowPoint>,
}
+4 -4
View File
@@ -42,10 +42,10 @@ pub use chain::{
};
pub use error::{ApiError, EntityError};
pub use intents::{
BidChange, BidLevel, BidSide, BidSidePoint, CounterPrice, IntentsInventory, IntentsListing,
IntentsPrice, IntentsSeries, IntentsSeriesPoint, IntentsSwap, IntentsSwaps, InventoryHolder,
InventoryToken, MarketSummary, Markets, NamedHolder, RefPool, RefPools, RefRung, RefSwap,
RefSwaps,
BidChange, BidLevel, BidSide, BidSidePoint, CounterPrice, IntentsFlowPoint, IntentsFlows,
IntentsInventory, IntentsListing, IntentsPrice, IntentsSeries, IntentsSeriesPoint, IntentsSwap,
IntentsSwaps, InventoryHolder, InventoryToken, MarketSummary, Markets, NamedHolder, RefPool,
RefPools, RefRung, RefSwap, RefSwaps,
};
pub use miner::{
AttributionSource, LeaderboardRow, MinerDetail, MinerId, MinerSeriesPoint, NodeActivity,
+24
View File
@@ -0,0 +1,24 @@
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
import type { BigUintDec } from "./BigUintDec";
/**
* One block where intents.near's balance of the asset changed
* (blackbeard/observer#39).
*/
export type IntentsFlowPoint = {
/**
* NEAR block.
*/
near_height: number,
/**
* Its time.
*/
at: string,
/**
* intents.near's balance after it, base units.
*/
balance: BigUintDec,
/**
* The change, base units, signed: positive deposited, negative withdrawn.
*/
delta: string, };
+64
View File
@@ -0,0 +1,64 @@
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
import type { BigUintDec } from "./BigUintDec";
import type { ChainId } from "./ChainId";
import type { IntentsFlowPoint } from "./IntentsFlowPoint";
/**
* The asset moving into and out of NEAR Intents over the last `hours`, read
* block by block from intents.near's own balance (blackbeard/observer#39).
* Exact for the money arriving and leaving; blind to who moved it, and a
* deposit and a withdrawal in one block net to one change.
*/
export type IntentsFlows = {
/**
* Which chain's token.
*/
chain: ChainId,
/**
* The asset's symbol on NEAR.
*/
asset_symbol: string | null,
/**
* Its decimals on NEAR.
*/
asset_decimals: number | null,
/**
* Hours covered.
*/
hours: number,
/**
* The NEAR blocks read so far, inclusive: nothing outside them is known.
*/
read_from: number,
/**
* Highest NEAR block read.
*/
read_to: number,
/**
* The balance at the start of the span, when known.
*/
balance_then: BigUintDec | null,
/**
* The balance after the newest change.
*/
balance_now: BigUintDec | null,
/**
* Summed rises in the span, base units.
*/
deposited: BigUintDec,
/**
* Summed falls in the span, base units, as a positive amount.
*/
withdrawn: BigUintDec,
/**
* Blocks with a rise.
*/
deposits: number,
/**
* Blocks with a fall.
*/
withdrawals: number,
/**
* Every change in the span, newest first.
*/
changes: Array<IntentsFlowPoint>, };
+10
View File
@@ -7,6 +7,7 @@
*/
import type { BidSide } from './generated/BidSide'
import type { IntentsFlows } from './generated/IntentsFlows'
import type { AccountDetail } from './generated/AccountDetail'
import type { AccountEvent } from './generated/AccountEvent'
import type { AccountRow } from './generated/AccountRow'
@@ -329,6 +330,15 @@ export async function fetchIntentsSeries(
)
}
/** The asset moving into and out of NEAR Intents (blackbeard/observer#39). */
export async function fetchIntentsFlows(
chain: string,
hours: number,
signal?: AbortSignal,
): Promise<IntentsFlows> {
return get<IntentsFlows>(`/chains/${chain}/intents/flows?hours=${hours}`, signal)
}
/** A Ref DCL pool's bid side over the last `hours` (blackbeard/observer#41). */
export async function fetchRefBids(
chain: string,
+171
View File
@@ -0,0 +1,171 @@
/**
* The asset moving into and out of NEAR Intents, block by block
* (blackbeard/observer#39, item 4 as replaced).
*
* intents.near's own balance of the token, read at every NEAR block on a node
* of ours that tracks the token's shard. A rise is the asset deposited, a fall
* the asset withdrawn. Trades never show here — they move balances between
* accounts inside intents.near and leave its total alone — so this is the
* money arriving and leaving, exactly, and nothing about who.
*/
import { useEffect, useState } from 'react'
import type { IntentsFlows } from '../api/generated/IntentsFlows'
import { RequestFailed, fetchIntentsFlows } from '../api/rest'
import { height as fmtHeight, tokens, utc, when } from '../lib/format'
import { Field } from './Field'
const SPANS: [number, string][] = [
[6, '6 h'],
[24, '24 h'],
[24 * 7, '7 d'],
]
const REFRESH_MS = 60_000
/** Changes listed before "older" is needed. */
const SHOWN = 50
export function IntentsFlowPanel({ chain, symbol }: { chain: string; symbol: string }) {
const [hours, setHours] = useState(24)
const [data, setData] = useState<IntentsFlows | null>(null)
const [error, setError] = useState<string | null>(null)
const [all, setAll] = useState(false)
useEffect(() => {
const controller = new AbortController()
const load = () =>
fetchIntentsFlows(chain, hours, controller.signal)
.then((d) => {
setData(d)
setError(null)
})
.catch((e: unknown) => {
if (controller.signal.aborted) return
setError(e instanceof RequestFailed ? e.message : 'Could not reach the observer.')
})
load()
const id = window.setInterval(load, REFRESH_MS)
return () => {
window.clearInterval(id)
controller.abort()
}
}, [chain, hours])
const asset = data?.asset_symbol ?? symbol
const d = data?.asset_decimals ?? 0
const amount = (raw: string | null | undefined) => (raw ? `${tokens(raw, d)} ${asset}` : '—')
const signed = (raw: string) =>
raw.startsWith('-') ? `−${tokens(raw.slice(1), d)}` : `+${tokens(raw, d)}`
const read =
data?.read_from !== null && data?.read_from !== undefined && data.read_to !== null
? `NEAR blocks ${fmtHeight(data.read_from)}–${fmtHeight(data.read_to)}`
: 'nothing read yet'
const net = data && BigInt(data.deposited) - BigInt(data.withdrawn)
const changes = data ? (all ? data.changes : data.changes.slice(0, SHOWN)) : []
return (
<section className="panel" style={{ marginBottom: 26 }}>
<div className="panel-head">
<h2 className="panel-title">Into and out of NEAR Intents</h2>
<span className="eyebrow">{read}</span>
</div>
<div className="pager" style={{ justifyContent: 'flex-start' }}>
{SPANS.map(([h, label]) => (
<button
key={h}
className="segmented panel-button"
aria-pressed={hours === h}
onClick={() => setHours(h)}
>
{label}
</button>
))}
</div>
{error && <p className="empty">{error}</p>}
{!error && !data && <p className="empty">Reading…</p>}
{data && (
<div className="node-grid">
<Field
label="Deposited"
value={amount(data.deposited)}
note={`${data.deposits} block${data.deposits === 1 ? '' : 's'} in the last ${hours} h`}
/>
<Field
label="Withdrawn"
value={amount(data.withdrawn)}
note={`${data.withdrawals} block${data.withdrawals === 1 ? '' : 's'}`}
/>
<Field
label="Net"
value={net === null || net === undefined ? '—' : `${signed(net.toString())} ${asset}`}
note="into NEAR Intents, over the span"
/>
<Field
label="Held now"
value={amount(data.balance_now)}
note={
data.balance_then ? `from ${amount(data.balance_then)}` : 'intents.near’s balance'
}
/>
</div>
)}
{data && data.changes.length > 0 && (
<div className="scroll-x">
<table className="board">
<caption className="visually-hidden">
Each block where intents.near’s {asset} balance changed, newest first
</caption>
<thead>
<tr>
<th scope="col" className="left">
When
</th>
<th scope="col">NEAR block</th>
<th scope="col">Change</th>
<th scope="col">Held after</th>
</tr>
</thead>
<tbody>
{changes.map((c) => (
<tr key={c.near_height}>
<td className="left numeral" title={utc(c.at)}>
{when(c.at)}
</td>
<td className="numeral">{fmtHeight(c.near_height)}</td>
<td className="numeral">
{signed(c.delta)} {asset}
</td>
<td className="numeral">{tokens(c.balance, d)}</td>
</tr>
))}
</tbody>
</table>
</div>
)}
{data && data.changes.length > SHOWN && !all && (
<div className="pager">
<button className="segmented panel-button" onClick={() => setAll(true)}>
All {data.changes.length} →
</button>
</div>
)}
{data && data.changes.length === 0 && (
<p className="empty">No {asset} moved into or out of NEAR Intents in the blocks read.</p>
)}
<p className="panel-note">
intents.near&apos;s own {asset} balance, read at every NEAR block on a node of ours that
tracks the token&apos;s shard. A rise is {asset} deposited into NEAR Intents, a fall {asset}{' '}
withdrawn. This is exact for the money arriving and leaving, and says nothing about who
moved it; a deposit and a withdrawal in the same block net to one change. Trades never
appear: they move {asset} between accounts inside NEAR Intents and leave this total
unchanged. Nothing before the first block read is known.
</p>
</section>
)
}
+3
View File
@@ -21,6 +21,7 @@ import { height as fmtHeight } from '../lib/format'
import { useObserverInstance } from '../lib/observer-context'
import { href } from '../lib/routes'
import { BridgePanel } from './BridgePanel'
import { IntentsFlowPanel } from './IntentsFlowPanel'
import { IntentsPanel } from './IntentsPanel'
import { InventoryPanel } from './InventoryPanel'
import { PriceChart } from './PriceChart'
@@ -159,6 +160,8 @@ function NearIntents({
<BridgePanel chain={chain} decimals={decimals} symbol={symbol} />
<IntentsFlowPanel chain={chain} symbol={symbol} />
<PriceChart chain={chain} symbol={symbol} />
<InventoryPanel chain={chain} symbol={symbol} />