createPublicClient
createPublicClient<
transport,chain,accountOrAddress,rpcSchema>(parameters):object
Defined in: src/clients/createPublicClient.ts:45
Creates a Public Client with a given Transport configured for a Chain.
A Public Client is an interface to the “public” Ethereum JSON-RPC API and the Arkiv JSON-RPC API — retrieving block numbers and transactions, reading from contracts, and querying entities — through PublicArkivActions.
Type Parameters
Section titled “Type Parameters”transport
Section titled “transport”transport extends Transport
chain extends Chain | undefined = undefined
accountOrAddress
Section titled “accountOrAddress”accountOrAddress extends `0x${string}` | Account | undefined = undefined
rpcSchema
Section titled “rpcSchema”rpcSchema extends RpcSchema | undefined = ArkivRpcSchema
Parameters
Section titled “Parameters”parameters
Section titled “parameters”Configuration object for the public client (chain, transport, etc.)
Returns
Section titled “Returns”An Arkiv Public Client. PublicArkivClient
count()
Section titled “count()”count: () =>
CountQueryBuilder
Returns a CountQueryBuilder: counts the entities a query matches, without fetching any of them.
It filters exactly as select does — .from(schema), .where(...), .ownedBy(...) and
.createdBy(...) — and .fetch() resolves to a bigint. To show the total next to a page of
rows, use select(...).withCount() instead.
- JSON-RPC Methods:
arkiv_query, with thecountprojection
Returns
Section titled “Returns”Example
Section titled “Example”const total = await client.count().from(Posts).ownedBy(account.address).fetch()const news = await client.count().from(Posts).where(eq("category", "news")).fetch()getBlockTiming()
Section titled “getBlockTiming()”getBlockTiming: () =>
Promise<GetBlockTimingReturnType>
Returns the current block timing.
Returns
Section titled “Returns”Promise<GetBlockTimingReturnType>
The current block timing. GetBlockTimingReturnType
Example
Section titled “Example”import { createPublicClient } from "@arkiv-network/sdk"import { rabdi } from "@arkiv-network/sdk/chains"import { http } from "viem"
const client = createPublicClient({ chain: rabdi({ accessKey: "..." }), transport: http(),})const blockTiming = await client.getBlockTiming()// {// currentBlock: 10n, // block number// currentBlockTime: 1234567890, // block timestamp// blockDuration: 2, // in seconds// }getEntity()
Section titled “getEntity()”getEntity: {(
key):Promise<Row<AllSelected,undefined>>; <S>(key,schema):Promise<Row<{ [K in string | number | symbol]: true },S>>; }
Returns the entity with the given key.
Given a schema, it is read through it: the result is a flat row of every entity field and every column, each typed as the schema declares and checked against it.
- JSON-RPC Methods:
arkiv_getEntity
Call Signature
Section titled “Call Signature”(
key):Promise<Row<AllSelected,undefined>>
Parameters
Section titled “Parameters”`0x${string}`
Returns
Section titled “Returns”Promise<Row<AllSelected, undefined>>
Call Signature
Section titled “Call Signature”<
S>(key,schema):Promise<Row<{ [K in string | number | symbol]: true },S>>
Type Parameters
Section titled “Type Parameters”Parameters
Section titled “Parameters”`0x${string}`
schema
Section titled “schema”S
Returns
Section titled “Returns”Promise<Row<{ [K in string | number | symbol]: true }, S>>
The entity key (hex string)
Optionally, the schema to read the entity through.
Returns
Section titled “Returns”The entity with the given key, with every field populated — a FullEntity, or a FullRow through a schema.
Throws
Section titled “Throws”If the key is not 32 bytes.
Throws
Section titled “Throws”If no live entity has that key — it never existed, or it was deleted or has expired.
Throws
Section titled “Throws”If, given a schema, the entity does not fit it.
Throws
Section titled “Throws”If the schema given was not built with defineSchema.
Example
Section titled “Example”import { createPublicClient } from "@arkiv-network/sdk"import { rabdi } from "@arkiv-network/sdk/chains"import { http } from "viem"
const client = createPublicClient({ chain: rabdi({ accessKey: "..." }), transport: http(),})const entity = await client.getEntity(entityKey)// {// $key: "0x9f2c…",// $owner: "0xabc…",// $expiresAt: 1_297_000n,// $attributes: { category: { type: "str", value: "docs" } },// ...// }
const post = await client.getEntity(entityKey, Posts)// { $key: "0x9f2c…", $owner: "0xabc…", ..., category: { type: "str", value: "docs" }, ... }getEntityNonce()
Section titled “getEntityNonce()”getEntityNonce: (
owner) =>Promise<bigint>
Returns how many entities an account has created — its entity-minting nonce.
Not the account’s transaction nonce: the engine keeps its own counter per creator and mixes it into every key it mints, which is why two identical creates from one account never collide.
Parameters
Section titled “Parameters”`0x${string}`
The account whose nonce to read.
Returns
Section titled “Returns”Promise<bigint>
The nonce the account’s next create will use.
Example
Section titled “Example”import { createPublicClient } from "@arkiv-network/sdk"import { rabdi } from "@arkiv-network/sdk/chains"import { http } from "viem"
const client = createPublicClient({ chain: rabdi({ accessKey: "..." }), transport: http(),})const nonce = await client.getEntityNonce("0xabc…")// 7n — the next entity this account creates is its eighthpredictEntityKeys()
Section titled “predictEntityKeys()”predictEntityKeys: <
TCount,TSalts>(parameters) =>Promise<PredictEntityKeysReturnType<TCount,TSalts>>
Works out the keys an account’s next creates will be given, before sending them.
The engine derives a key from the chain, the registry, the owner, the owner’s nonce and a salt — everything but the nonce is known to the caller, and the nonce is read here. This is what lets a batch reference an entity it is about to mint.
Each key arrives paired with the salt that mints it, because a create defaults to a random salt: a predicted key only holds if the create carries the salt it was predicted with. And the prediction holds only while nothing else from this owner is in flight — for a key you can rely on unconditionally, read it back from the create instead.
A literal count comes back as a fixed-length tuple, so the pairs destructure into names.
Type Parameters
Section titled “Type Parameters”TCount
Section titled “TCount”TCount extends number = number
TSalts
Section titled “TSalts”TSalts extends readonly SaltInput[] | undefined = undefined
Parameters
Section titled “Parameters”parameters
Section titled “parameters”PredictEntityKeysParameters<TCount, TSalts>
Owner, and either a count or the salts. PredictEntityKeysParameters
Returns
Section titled “Returns”Promise<PredictEntityKeysReturnType<TCount, TSalts>>
One { key, salt } pair per create, in batch order.
PredictEntityKeysReturnType
Example
Section titled “Example”A batch whose second entity points at its first.import { defineSchema, key, str } from "@arkiv-network/sdk/schema"
const Nodes = defineSchema("nodes", { name: str(), parent: key().indexed().optional() })
const [parent, child] = await client.predictEntityKeys({ owner: account.address, count: 2 })await wallet.executeBatch({ creates: [ { schema: Nodes, values: { name: "root" }, expiration, salt: parent.salt }, { schema: Nodes, values: { name: "leaf", parent: key(parent.key) }, expiration, salt: child.salt, }, ],})query()
Section titled “query()”query: <
S,K>(query,queryOptions?) =>Promise<QueryReturnType<QueryRow<S>>>
Runs one query and returns one page, with no builder in between.
The selection means what it does in PublicArkivActions.select, and the results are the
same flat rows a query without a schema returns, typed from the selection. Use select() to
read through a schema. This also takes a raw string as an escape hatch for a query built
elsewhere. A raw string
goes to the node exactly as written, with none of the name, type or operator checks the
expression combinators apply.
Type Parameters
Section titled “Type Parameters”S extends SelectArg = "*"
K extends OrderTerm<AttributeRef> = OrderTerm<AttributeRef>
Parameters
Section titled “Parameters”An Expression, or the raw query string.
string | Expression
queryOptions?
Section titled “queryOptions?”QueryOptions<S, K>
Selection, sort, page size, offset and count. QueryOptions
Returns
Section titled “Returns”Promise<QueryReturnType<QueryRow<S>>>
One page of entities. QueryReturnType
Example
Section titled “Example”import { createPublicClient } from "@arkiv-network/sdk"import { rabdi } from "@arkiv-network/sdk/chains"import { and, desc, eq, gte } from "@arkiv-network/sdk/query"import { i32 } from "@arkiv-network/sdk/schema"import { http } from "viem"
const client = createPublicClient({ chain: rabdi({ accessKey: "..." }), transport: http(),})const page = await client.query(and(eq("category", "docs"), gte("level", i32(10))), { select: { $key: true, title: true }, orderBy: desc("level", "i32"), limit: 100,})// { entities: [{ $key: Hex; title: ArkivValue | undefined }], blockNumber: 32223n, count: undefined }
// The raw form, unchecked:await client.query("category = str('docs') AND level >= i32(10)")select()
Section titled “select()”select: {(
selection?):SelectQueryBuilder<"*">; <S>(selection):SelectQueryBuilder<SelectionOf<S>>; }
Returns a SelectQueryBuilder for building and executing queries — the recommended way to read entities. You declare up front which parts of an entity you want returned, so results always contain exactly the data you asked for.
The selection names entity fields and attributes side by side, and each result is a flat row.
Chain .from(schema) to read through a schema: the selection keeps its meaning, but each
attribute comes back typed and checked as the schema declares, and where may only filter on
the schema’s indexed columns.
- JSON-RPC Methods:
arkiv_query
Call Signature
Section titled “Call Signature”(
selection?):SelectQueryBuilder<"*">
Select every field — and every column through a schema, or the $attributes map without
one. Pass nothing or "*". The $attributeSchema is not included: select it by name.
Parameters
Section titled “Parameters”selection?
Section titled “selection?”"*"
Returns
Section titled “Returns”SelectQueryBuilder<"*">
Call Signature
Section titled “Call Signature”<
S>(selection):SelectQueryBuilder<SelectionOf<S>>
Pick the fields to return. Set the ones you want to true (at least one is required); the
result is typed to exactly those fields, so reading anything else is a compile error.
Entity fields start with $: $key, $owner, $creator, $createdAt, $updatedAt,
$expiresAt and $creationFlags. $attributes reads every attribute as a map, and
$attributeSchema their names, types and indexing without the values — a cheap way to find
out what entities hold before fetching values that may be too large for one response. Any
other name is an attribute, read as a field
of its own: untyped without a schema, and through one typed and checked as the column it
must be. An attribute name cannot start with $, so the two never collide.
Pass the selection inline so its fields stay literal true. A selection stored in a let/
const variable widens to boolean, and one typed SelectArg is only known at
runtime: which fields come back is then decided at runtime, so every field of the result is
optional — a PartialRow. Annotate a stored selection as const to keep it narrow.
Type Parameters
Section titled “Type Parameters”S extends SelectArg
Parameters
Section titled “Parameters”selection
Section titled “selection”S & NonEmptySelection<S> & KnownSystemFields<S>
Returns
Section titled “Returns”SelectQueryBuilder<SelectionOf<S>>
Example
Section titled “Example”client.select({ $key: true, title: true }) // { $key: Hex; title: ArkivValue | undefined }client.select({ $key: true, title: true }).from(Posts) // { $key: Hex; title: StrValue }client.select({ $owner: true, $attributes: true }) // { $owner: Hex; $attributes: Attributes }client.select({ $key: true, $attributeSchema: true }) // what do they hold? no valuesWhat to include in the results. Omit it (or pass "*") to select everything,
or pass an object to select specific parts (at least one field is required). Every part is
opt-in, including the $key. The selection is flat — each field maps to a field of the result.
SelectArg
Returns
Section titled “Returns”A SelectQueryBuilder instance for building and executing queries. SelectQueryBuilder
Example
Section titled “Example”import { createPublicClient } from "@arkiv-network/sdk"import { rabdi } from "@arkiv-network/sdk/chains"import { and, eq, gt } from "@arkiv-network/sdk/query"import { dec } from "@arkiv-network/sdk/schema"import { http } from "viem"
const client = createPublicClient({ chain: rabdi({ accessKey: "..." }), transport: http(),})// through a schema — rows typed { $key: Hex; author: AddrValue; title: StrValue }await client .select({ $key: true, author: true, title: true }) .from(Posts) .where(and(eq("category", "docs"), gt("score", dec("4.0")))) .fetch()// every field and columnawait client.select().from(Posts).where(eq("category", "docs")).fetch()
// the same selection without a schema — rows typed// { $key: Hex; author: ArkivValue | undefined; title: ArkivValue | undefined }await client.select({ $key: true, author: true, title: true }).where(eq("category", "docs")).fetch()watchEntityEvents()
Section titled “watchEntityEvents()”watchEntityEvents: (
parameters) => () =>void
Watches entity events, calling the handlers you pass as they arrive.
All five are decoded from logs — onEntityCreated, onEntityPatched, onExpiryExtended,
onOwnershipTransferred, onEntityDeleted — and each carries the block, transaction and log
index it came from, which is the order the operations were applied in. onEvent receives all
of them, whatever their type.
Parameters
Section titled “Parameters”parameters
Section titled “parameters”Handlers and options, all optional. WatchEntityEventsParameters
Returns
Section titled “Returns”A function that stops the watcher.
():
void
Returns
Section titled “Returns”void
Example
Section titled “Example”import { createPublicClient } from "@arkiv-network/sdk"import { rabdi } from "@arkiv-network/sdk/chains"import { http } from "viem"
const client = createPublicClient({ chain: rabdi({ accessKey: "..." }), transport: http(),})const unwatch = client.watchEntityEvents({ onEntityCreated: ({ entityKey, expiresAt }) => console.log(entityKey, "until", expiresAt), onError: (error) => console.error("watchEntityEvents error", error),})unwatch() // stop watchingExample
Section titled “Example”import { createPublicClient } from "@arkiv-network/sdk"import { rabdi } from "@arkiv-network/sdk/chains"import { http } from "viem"
const client = createPublicClient({ chain: rabdi({ accessKey: "..." }), transport: http(),})