Para desarrolladores / Activos del mundo real

Cómo se forma un precio

Dos métodos de agregación, un solo publicador. La aritmética de abajo es lo que hace un precio robusto frente a un mercado que se porta mal; no es lo que lo hace digno de confianza. Eso es la última sección, y es la que hay que leer antes de liquidar nada sobre estos números.

De dónde viene un precio

Thirteen feeds are aggregated from five public spot venues, each subscribed with that venue's own product id. The other twenty have no venue leg and come from Pyth Network's Hermes service alone.

FuenteQué
Mercados spotCoinbase, Kraken, Bitstamp, Gemini, Bitfinexcada uno suscrito con el identificador de producto propio de ese mercado, tomado del catálogo
Segunda fuentePyth Network, a través de su servicio Hermesla única fuente para los veinte feeds sin pata de mercado, y una comprobación cruzada para los otros trece

Los dos métodos fallan de forma distinta, y un consumidor necesita ambos comportamientos. Un feed respaldado por mercados sobrevive a que un mercado se apague, porque la mediana se toma sobre cinco y cada uno lleva su propia frescura. Un feed de fuente única no puede sobrevivir a que su fuente no esté disponible, y lo dice en lugar de adivinar.

Cuándo cuenta un mercado

Cada mercado se evalúa por separado antes de combinar nada. Las reglas se aplican en este orden, y la primera que falla saca a ese mercado de la mediana para esa evaluación:

ReglaUmbral
Connection statemust be onlinea venue whose socket is down is never fresh, whatever its last quote said
Quote age10 smeasured on a MONOTONIC receive clock, never on the exchange's timestamp or the host's wall clock
Delivery lag5 s either waya timestamp trailing its receipt means the socket is replaying a backlog; one leading it means the venue dates quotes in the future. The whole venue sits out rather than falling through to its last trade
Spread50 bpsthe mid is used when the book is uncrossed and tighter than this
Last trade60 sthe fallback when no usable mid exists, inside its own longer window
La frescura se juzga sobre un reloj monótono

No sobre la marca de tiempo del mercado, y no sobre el reloj de pared del anfitrión. Un mercado con el reloj adelantado o atrasado no puede hacer que su propia cotización parezca fresca, y un anfitrión cuyo reloj da un salto no puede invalidar todos los mercados a la vez. La marca de tiempo del mercado sirve para una sola cosa: el control del retraso de entrega, que la compara contra el momento de recepción en ambos sentidos.

Se prefieren el mejor bid y el mejor ask cuando el libro es reciente, no está cruzado y es más estrecho que el límite de spread. Si no, entra en su lugar la última operación, dentro de su propia ventana más larga. Un mercado cuyo socket está reproduciendo un atraso se retira por completo en vez de caer a su última operación, porque esa operación llega tarde en la misma medida.

La mediana

  1. Evaluate every venue against the rules above and keep the fresh ones.
  2. If fewer than minSources are fresh, publish nothing and report the reason - no_sources when none is fresh, too_few_sources otherwise. Nothing thin is ever published.
  3. Take the median of what survives.
  4. If the spread between the included venues exceeds 200 bps and dropping one would still leave minSources, drop the venue furthest from the median - on a tie the older observation - and take the median again. At most one venue is dropped.
  5. Round half-even to the feed's decimals. The result is an integer, not a float.
  6. Date the aggregate with the NEWEST included quote, capped at the current wall clock so no venue with a fast clock can date a median into the future.

degraded is set when the median rested on exactly minSources venues: still published, one drop-out from silence.

Un feed demasiado fino no publica nada en vez de publicar algo

minSources es propio de cada feed, y vale 3 en todos los feeds respaldados por mercados. Por debajo no hay respuesta alguna: ningún último valor conocido se vuelve a publicar en cadena, la ronda no avanza y updatedAt deja de moverse. El servicio sigue informando de la última respuesta buena como lastKnown para el diagnóstico, y ese campo explícitamente no es un precio con el que operar.

El agregado se fecha con la cotización incluida más reciente, acotada al reloj de pared actual. Las dos mitades importan: un mercado cuya última operación, de sesenta segundos de antigüedad, sustituyó a un libro obsoleto no debe fechar una mediana cuyas demás entradas son de menos de un segundo, y ningún mercado con el reloj adelantado puede empujar una hora de observación hacia el futuro - donde el contrato la omitiría como razón 4.

Comprobación cruzada y sustitución

An exchange-backed feed that also has a Pyth leg is cross-checked against it on every evaluation. Within 100 bps the two are recorded as agreeing; beyond it the feed is marked diverged and the dispersion flag is raised.

When the venues go stale, Pyth may stand in for them - but only if the two agreed recently and are not diverging now. A feed publishing from the stand-in is marked degraded and its source reads pyth rather than exchanges-median, so a consumer can tell. If they are diverged and Pyth is fresh, the feed publishes nothing and reports cross_check_diverged.

Dos campos lo exponen. crossCheckBps es la distancia actual entre los dos métodos, y source dice cuál produjo la ronda que tiene en la mano - 1 para la mediana de los mercados, 2 para la segunda fuente. Un feed cuya source ha cambiado sigue siendo un precio válido, producido de otra manera; si eso importa para su producto, vigile el campo en lugar de inferirlo.

La segunda fuente

Cada actualización de la segunda fuente pasa estos controles antes de poder ser un precio. Una actualización rechazada incrementa un contador por razón, visible feed por feed en las rutas de fuente y de auditoría del servicio:

ControlLímite
Exponentpinned on the first updateany later drift is rejected, so a silent rescaling cannot pass
Slot and publish timemust advancean update that does not move them forward is dropped
Future tolerance5 sa publish time further ahead than this is rejected
Confidence50 bps crypto and index, 30 equity, 10 commodity and fxthe reported confidence interval as a fraction of the price; wider is rejected
EMA band10 % crypto and index, 5 % elsewherea jump away from the exponential moving average needs a SECOND sample within 100 bps of the first before it is used. A lone spike is dropped
Freshness10 s since receipt, 30 s publish lagboth measured at receipt on the monotonic clock

Sin la credencial, veinte de los treinta y tres feeds callan

The upstream needs a credential. Without one it answers unauthorised and every feed with no venue leg stays unpublished - twenty of the thirty-three, which is the whole real-world set plus XMR/USD.

The thirteen exchange-backed feeds continue: they are computed from public venues and need no credential. What they lose is the cross-check and the stand-in, since neither can be established without a Pyth price to compare against. Readiness reports this as a warning rather than a failure, so the service looks healthy while two thirds of the catalog is silent - check the per-feed status, not the service's.

El control del exponente es el discreto y el más importante. La escala de una actualización queda fijada desde la primera autenticada y cualquier deriva posterior se rechaza de plano, porque un reescalado silencioso es un precio errado en una potencia de diez que parece perfectamente bien formado.

Cómo llega a la cadena

  1. The aggregating service holds no signing key at all. It computes prices and serves them on an internal port.
  2. The node's publisher polls that port, authenticates the body with a shared HMAC of the exact bytes, and re-checks every item against on-chain state before signing - mirroring the contract's own skip rules so a bad item costs a counter rather than gas.
  3. The batch is written as ONE system transaction per EVM block, signed by the publisher key, which lives in the node's process and is used by nothing else in it.
  4. The service then reads its own result back off the chain and reports it, which is what the onchain field of every FeedView is.

At most 64 feeds go into one batch by default, and the contract's own maxBatch caps it again. A batch older than 2 s is not published.

La división del trabajo es el punto. Todo lo lento o falible - el sondeo, la autenticación, la lectura del catálogo, la selección, la codificación, la firma y el añadido al registro de escritura anticipada - ocurre fuera de la ruta de sellado, que recibe una transacción terminada y la aplica al coste de cualquier otra transacción. Y como el publicador vuelve a comprobar cada elemento contra el estado en cadena antes de firmar, reproduciendo las propias reglas de omisión del contrato, un agregador que envía algo malo cuesta un contador y no una ronda.

El modelo de confianza

A price is as trustworthy as the operator that produces blocks, and no more. The publisher is the block producer.

  • One party operates the node, holds the publisher key and orders transactions. A price inherits exactly the assumption that already governs ordering.
  • Nothing on chain arbitrates a price. There is no second publisher, no dispute window and no slashing: the contract checks that an item is well formed, positive, not from the future and not older than the feed's last observation, and then writes it.
  • The owner role can add a feed, change a feed's policy, rotate the publisher and adjust the batch and tolerance parameters. Ownership transfer is two-step. Those are the only write paths that are not the publisher's.
  • Splitting the key from the computation limits one failure, not the other: compromising the aggregating service lets an attacker propose prices, and every one is still re-checked and signed by the node. Compromising the node is the end of the argument.
  • If you liquidate on these prices, that is the assumption you are taking, and it is the one to state to your own users.

Nada de lo anterior cambia eso. Las reglas de mercado, la mediana, el rechazo de valores atípicos y la comprobación cruzada hacen un precio robusto frente a una fuente que se porta mal, que es un fallo real y frecuente. No hacen nada frente a la parte que firma. Léalos como controles de calidad, no como un consenso.

La consecuencia práctica para un integrador: estos precios sirven para un producto cuyos usuarios saben quién los produce, y llevan la misma suposición que el ordenamiento de sus propias transacciones - así que si ya acepta esa suposición para usar la cadena siquiera, consumir los feeds no añade ninguna nueva. Si su diseño necesita un precio que ninguna parte por sí sola pueda falsificar, esta capa no lo proporciona y ningún parámetro hace que lo haga.