Для разработчиков / API приложений
API обозревателя
Архив, которым узел намеренно не является. Он держит всю историю, это единственная поверхность в этой цепочке с трассами вызовов, и он доступен только на чтение в самом сильном смысле - каждый POST даёт 405.
Зачем это существует
Узел держит короткое окно истории - примерно две минуты блоков - и запрос за его пределами отвечает null, а не ошибкой. Это намеренный размен: он быстро обслуживает настоящее и отдаёт прошлое тому, что построено для прошлого. Этот сервис и есть то самое. Секвенсер копирует каждый лог в Postgres по ходу дела, а этот API читает этот индекс.
Так что два вопроса получают ответ здесь и больше нигде:
- Всё, что старше окна узла. Транзакция сегодняшнего утра, блок прошлой недели, вся история переводов токена.
- Трассы вызовов. Узел вообще не выставляет пространство имён
debug, поэтомуGET /tx/{hash}- единственное место в этой цепочке, где видно внутренние вызовы транзакции.
Некоторые поля некоторых маршрутов читаются с узла вживую в момент обслуживания запроса - баланс, запись сервиса имён, проба контракта, мини-блоки блока, который индекс ещё не догнал. Когда узел недостижим, они возвращаются нулевыми или отсутствуют, а остальная часть ответа обслуживается из индекса, так что частичный ответ нормален и не поднимает ошибку.
Базовый URL и CORS
| Точка доступа | Value |
|---|---|
| Публично | https://explorer.picklechain.xyz/api/также смонтирован на /api/ сайтами сервиса имён и набора инструментов |
| Ваш собственный стек | http://127.0.0.1:4010собственный порт сервиса; в поставляемом compose-файле он не публикуется за пределы сети контейнеров |
| CORS | список разрешённыхOPTIONS отвечает 204 с разрешёнными GET и OPTIONS; Origin вне списка получает отказ 403 |
Цепочка
Блоки, мини-блоки, транзакции и разделение комиссий.
/stats
GET- Params
- none
- Возвращает
- a flat object of counters
Chain-wide counters: block and transaction totals, wallets, gas used, the cadence figures the node reports, the mini-block head, index lag and the spool's own health.
Также по адресу. GET /
Полезно знать. Recomputed once a second by a background thread and served from a cache for six tenths of a second, so two calls in the same instant give the same answer. It also carries a rate counter this reference does not quote: the site publishes no throughput figure, and the number is local anyway.
/overview
GET- Params
- none
- Возвращает
- {stats, charts, blocks, txs, topAccounts}
The explorer's front page in one call: the cached stats, 48 chart points, the 8 most recent blocks that carried transactions, 12 transactions and the 8 busiest accounts.
Полезно знать. Use this instead of five calls. Its parts are the other routes' defaults and nothing about it is configurable.
/charts
GET- Params
- limit (default 48, clamped to 200)
- Возвращает
- [{number, timestamp, txCount, gasUsed}]
A bare array, oldest first.
Полезно знать. It prefers blocks that carried transactions and falls back to all blocks only when fewer than four match, so the series is not evenly spaced in time and must not be read as one.
/blocks
GET- Params
- limit, offset, active=1
- Возвращает
- [{number, hash, timestamp, gasUsed, txCount, miniCount}]
A bare array, newest first. `active=1` returns only blocks that carried transactions.
Полезно знать. No total is returned, so there is nothing to page against except asking until you get a short answer.
- Params
- limit, offset over the block's transactions
- Возвращает
- one block with its transactions and mini-blocks
The number is parsed permissively: decimal and 0x both work.
Полезно знать. `limit` defaults to 50 here rather than 25, and the mini-blocks fall back to a live read against the node when the index has none for the block. 404 when unknown.
/minis
GET- Params
- limit, offset
- Возвращает
- {total, minis: [...]}
Mini-blocks, newest first. One of the few routes that does return a total.
Полезно знать. Timestamps are `timestamp_us`: MICROSECONDS, not seconds, and a decimal number rather than a hex quantity.
- Params
- limit, offset over the transactions
- Возвращает
- one mini-block
By decimal number or by hash.
Полезно знать. When the index does not have it, the service asks the node - and the answer then ALSO carries `stateDiffHash`, `sequencerSig` and `receipts`, which the indexed answer does not. The shape depends on where it was found.
/txs
GET- Params
- limit, offset
- Возвращает
- a bare array, newest first
Transaction summaries.
Полезно знать. No total.
/tx/{hash}
GET- Params
- none
- Возвращает
- the full transaction
The richest object in the API: input data, the decoded method for known selectors, logs with labelled addresses, CALL TRACES, token transfers and NFT transfers.
Полезно знать. The traces are the reason this route exists. The node exposes no debug namespace at all, so there is nowhere else on this chain to get them. 404 when unknown.
/fees
GET- Params
- none
- Возвращает
- {deployed, router, split, burn, launches, arcadeSkims, deferred, claimed, pendingEthWei, ...}
Everything the fee split has done and everything still waiting, read from the log spool rather than over RPC.
Полезно знать. `{"deployed": false}` and NOTHING ELSE when the fee layer is not in the manifest - that is an ordinary state, not an error, because that layer is deployed by hand. The ether side and the token side are kept as separate figures and never summed.
Счета
Кто совершал транзакции, и всё, что известно об одном адресе.
/accounts
GET- Params
- limit, offset
- Возвращает
- {total, accounts: [...]}
Accounts ordered by how much they have transacted.
Полезно знать. The ordering is by transaction count, not by balance.
- Params
- limit, offset over the transaction lists
- Возвращает
- the largest payload in the service
Balance, nonce, counts, whether it is a contract, its creator and what it created, token and NFT holdings with metadata, the name-service record, and recent transactions and transfers.
Полезно знать. `bytecode` is TRUNCATED to 400 hex characters with an ellipsis appended; `bytecodeSize` is the real length. The whole answer is cached for a few seconds under a key that includes the paging, so two different pages are two different cache entries.
Токены, NFT и имена
Метаданные, объединённые с реестром, и единственный маршрут, который не JSON.
/tokens
GET- Params
- none
- Возвращает
- a list of at most 40 tokens
PKL pinned first, then by transfer count. Each entry merges a live probe of the contract with the operator's registry entry.
Полезно знать. Forty is a hard cap and there is no paging past it. An address that probes as an NFT is skipped even if the registry calls it a token.
/nfts
GET- Params
- none
- Возвращает
- {nfts: [...]}
At most 40 collections, verified ones first, then by how many have been minted.
Полезно знать. The collection list is DISCOVERED from transfer logs rather than registered, so a collection nobody has traded is absent.
- Params
- limit, clamped to 48
- Возвращает
- the collection, its items and its 30 most recent transfers
Collection metadata merged from the chain and the registry.
Полезно знать. Items are fetched one at a time up to the clamp, and off-chain metadata is resolved by a BACKGROUND thread - so the first request for a cold collection returns items whose metadata is still missing, and a second request a moment later returns more. Held for fifteen seconds in a cache of its own.
- Params
- none
- Возвращает
- one item plus `collectionMeta`
One token of a collection.
Полезно знать. The token id must be all digits, or the path does not match this route at all and you get the 404 for an unknown route.
/name/{name}
GET- Params
- none
- Возвращает
- {name, label, available, reserved, owner, resolved, expires, price, twitter, website, description}
A name-service lookup, read live from the registry contract.
Полезно знать. A trailing suffix is stripped, and the label must be 3 to 32 characters. A name outside that range, and any lookup at all when the name service is not configured, is a 404 - which is indistinguishable from a name that does not exist.
- Params
- none
- Возвращает
- raw image bytes
The only non-JSON, non-stream route. The content type is inferred from the stored file's extension.
Полезно знать. 404 as JSON when there is no logo, so a client must check the status before treating the body as an image.
Прямой эфир и два глагола, которые не GET
Поток событий, префлайт и 405.
/live
GET- Params
- none
- Возвращает
- text/event-stream, one stats frame per update
Server-sent events carrying the same object /stats returns, pushed when it changes.
Полезно знать. Bounded to 32 concurrent streams - the 33rd gets 503 - and the server CLOSES every stream after five minutes. A client that does not reconnect simply stops receiving, with no error.
any
OPTIONS- Params
- none
- Возвращает
- 204
The preflight. Allowed methods are GET and OPTIONS, allowed header is Content-Type.
Полезно знать. 403 when an Origin is present and not on the allowlist, rather than a 204 without the allow header.
any
POST- Params
- none
- Возвращает
- 405
This API is read-only and answers 405 to every POST, in JSON and with the CORS headers.
Полезно знать. It had one write route: a token-metadata edit signed by the contract's owner. It is gone, along with the form that called it, because an explorer that takes visitor-supplied identity for an asset is an impersonation surface.
Лимиты, пагинация и кеши
| Лимит | Value |
|---|---|
| Request rate | 300 per minute per client addressthen 429; the window is wall-clock and resets on the minute |
| Client identity | the rightmost trusted X-Forwarded-For entryindexed from the right by the number of trusted proxy hops, because the leftmost entry is whatever the client wrote |
| Request body | 600,000 bytesthere is nothing to POST, but the cap exists |
| List paging | limit <= 100, offset >= 0a non-numeric limit silently becomes the default rather than erroring |
| Live streams | 32 concurrent, 300 seconds each503 above the first, silent close at the second |
| Answer cache | about 3 secondson /address, /tokens, /nfts and the NFT routes; the stats cache is shorter |
Лимит частоты считается по клиентскому адресу, и он общий со страницей самого обозревателя
Триста запросов в минуту - щедро для человека и скудно для обратной заливки. Окно идёт по стенным часам: оно сбрасывается на минуте, а не скользит, поэтому всплеск на переломе минуты может потратить два окна за две секунды, а потом отвечать 429 весь остаток второй минуты. Заголовка retry-after на этом сервисе нет - отступайте сами.
Личность за счётчиком - это переданный клиентский адрес, читаемый с правого конца цепочки, потому что самая левая запись есть то, что написал вызывающий. За прокси, который ничего не добавляет, все вызывающие схлопываются в одно ведро, и весь интернет делит один бюджет.
Пагинация - это limit и offset, ограниченные сверху сотней. Нечисловой limit становится значением по умолчанию, а не ошибкой, а отрицательный становится единицей - так что некорректный запрос получает правдоподобный ответ, а не возражение. Большинство списочных маршрутов не возвращают общего числа; /minis и /accounts - исключения.
/address, /tokens, /nfts и маршруты NFT держатся в недолговечном кеше с ключом из пути и пагинации, а /stats пересчитывается фоновым потоком и отдаётся из кеша ещё более короткого. Два одинаковых запроса в один и тот же миг дают одинаковые ответы, что годится для страницы и не годится для цикла подтверждения. Опрашивайте узел ради квитанции, а не это.
Свежесть и отставание
/stats несёт числа, которые говорят, насколько индекс актуален: indexedBlock против latestBlock, indexLag как разница, и derivedLag для материализованных представлений - балансы токенов и владение NFT строятся отдельными рабочими процессами и могут отставать от транзакций, из которых происходят.
# Is the archive current? Compare the two, do not trust either alone.
curl -s "$EXPLORER_API/stats" | jq '{latestBlock, indexedBlock, indexLag, derivedLag}'
# One transaction, whole, traces included. This is the route with no substitute.
curl -s "$EXPLORER_API/tx/$HASH" | jq '{success, decoded, traces: (.traces|length), tokenTransfers}'
# Page an address's history by offset - and see the note below before relying on it.
curl -s "$EXPLORER_API/address/$ADDR?limit=100&offset=0" | jq '.transactions | length'Пагинация по offset смещается под растущим списком
Каждый список здесь идёт от новых к старым, и новые строки приходят в голову. Страница два, полученная мгновением позже страницы один, поэтому перекрывается с ней - а строки могут быть пропущены целиком, пока вы идёте. Для обратной заливки, которая должна быть полной, листайте по номеру блока вниз или забирайте по одному блоку за раз; offset сделан для интерфейса, а не для импортёра.
Ещё одна асимметрия, которую стоит знать, прежде чем строить любой ключ: эта цепочка нумерует logIndex по транзакции, а не по блоку, поэтому пара (blockNumber, logIndex) не уникальна. Включайте хеш транзакции в любой ключ, который вы строите.