@arkiv-network/sdk 0.6.8-dev.4 → 0.6.8-dev.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/chains/index.d.ts +25 -25
- package/dist/{entity-CHiZ2Qu1.d.ts → entity-B6g_EPm1.d.cts} +11 -1
- package/dist/entity-B6g_EPm1.d.cts.map +1 -0
- package/dist/{entity-BSU5-vyY.d.cts → entity-qoLMAuuk.d.ts} +11 -1
- package/dist/entity-qoLMAuuk.d.ts.map +1 -0
- package/dist/{index-ByaanQGD.d.ts → index-DdspxNAA.d.ts} +23 -2
- package/dist/index-DdspxNAA.d.ts.map +1 -0
- package/dist/{index-CS6sxVJC.d.cts → index-Ds9dwqb5.d.cts} +23 -2
- package/dist/index-Ds9dwqb5.d.cts.map +1 -0
- package/dist/index.cjs +1 -1
- package/dist/index.d.cts +2 -3
- package/dist/index.d.cts.map +1 -1
- package/dist/index.d.ts +2 -3
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/query/index.cjs +1 -1
- package/dist/query/index.d.cts +2 -2
- package/dist/query/index.d.ts +2 -2
- package/dist/query/index.js +1 -1
- package/dist/{queryBuilder-C3XSUYpn.js → queryBuilder-D2uwP9jI.js} +9 -1
- package/dist/queryBuilder-D2uwP9jI.js.map +1 -0
- package/dist/{queryBuilder-K0ZkQGnx.cjs → queryBuilder-UW2MCaX4.cjs} +8 -0
- package/dist/types/index.d.cts +1 -1
- package/dist/types/index.d.ts +1 -1
- package/package.json +1 -1
- package/src/actions/public/query.ts +10 -0
- package/src/clients/decorators/arkivPublic.ts +0 -1
- package/src/query/queryBuilder.ts +21 -0
- package/dist/entity-BSU5-vyY.d.cts.map +0 -1
- package/dist/entity-CHiZ2Qu1.d.ts.map +0 -1
- package/dist/index-ByaanQGD.d.ts.map +0 -1
- package/dist/index-CS6sxVJC.d.cts.map +0 -1
- package/dist/queryBuilder-C3XSUYpn.js.map +0 -1
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["logger","bytes: Uint8Array","rpcQueryOptions: RpcQueryOptions","query","logger","logger","zlib: typeof import(\"zlib\") | null","brotli: BrotliWasmType | null","logger","logger","logger","logger","logger","logger","createdEntities: Hex[]","updatedEntities: Hex[]","deletedEntities: Hex[]","extendedEntities: Hex[]","ownershipChanges: Hex[]","chains"],"sources":["../src/actions/public/getBlockTiming.ts","../src/actions/public/getEntity.ts","../src/actions/public/getEntityCount.ts","../src/actions/public/query.ts","../src/actions/public/subscribeEntityEvents.ts","../src/clients/decorators/arkivPublic.ts","../src/clients/createPublicClient.ts","../src/utils/compression.ts","../src/utils/validation.ts","../src/utils/arkivTransactions.ts","../src/actions/wallet/changeOwnership.ts","../src/actions/wallet/createEntity.ts","../src/actions/wallet/deleteEntity.ts","../src/actions/wallet/extendEntity.ts","../src/actions/wallet/mutateEntities.ts","../src/actions/wallet/updateEntity.ts","../src/clients/decorators/arkivWallet.ts","../src/clients/createWalletClient.ts","../src/utils/chains.ts"],"sourcesContent":["import type { ArkivClient } from \"../../clients/baseClient\"\nimport { getLogger } from \"../../utils/logger\"\n\nconst logger = getLogger(\"actions:public:get-block-timing\")\n\nexport type GetBlockTimingReturnType = {\n currentBlock: bigint\n currentBlockTime: number\n blockDuration: number\n}\n\nexport async function getBlockTiming(client: ArkivClient) {\n const blockTiming = await client.request({\n method: \"arkiv_getBlockTiming\",\n params: [],\n })\n logger(\"Block timing %o\", blockTiming)\n return {\n currentBlock: BigInt(blockTiming.current_block),\n currentBlockTime: blockTiming.current_block_time,\n blockDuration: blockTiming.duration,\n }\n}\n","import { bytesToHex, type Hex, hexToBytes } from \"viem\"\nimport type { ArkivClient } from \"../../clients/baseClient\"\nimport { NoEntityFoundError } from \"../../errors\"\nimport { entityFromRpcResult } from \"../../utils/entities\"\n\nexport async function getEntity(client: ArkivClient, key: Hex) {\n // Normalize the key into bytes\n let bytes: Uint8Array\n try {\n bytes = hexToBytes(key)\n } catch {\n throw new Error(`Invalid key format: ${key}. Key must be a valid hex string.`)\n }\n\n if (bytes.length !== 32) {\n throw new Error(\n `Invalid key length: ${bytes.length} bytes. Key must be 32 bytes (64 hex characters) long.`,\n )\n }\n\n const hexKey = bytesToHex(bytes)\n\n const result = await client.request({\n method: \"arkiv_query\",\n params: [\n `$key = ${hexKey}`,\n {\n includeData: {\n key: true,\n attributes: true,\n payload: true,\n contentType: true,\n expiration: true,\n owner: true,\n creator: true,\n createdAtBlock: true,\n lastModifiedAtBlock: true,\n transactionIndexInBlock: true,\n operationIndexInTransaction: true,\n },\n },\n ],\n })\n\n if (!result.data.length) {\n throw new NoEntityFoundError()\n }\n\n return await entityFromRpcResult(result.data[0])\n}\n","import type { ArkivClient } from \"../../clients/baseClient\"\n\nexport async function getEntityCount(client: ArkivClient) {\n const count = await client.request({\n method: \"arkiv_getEntityCount\",\n params: [],\n })\n\n return count\n}\n","import { numberToHex } from \"viem\"\nimport type { ArkivClient } from \"../../clients/baseClient\"\nimport type { Entity } from \"../../types/entity\"\nimport type { RpcQueryOptions } from \"../../types/rpcSchema\"\nimport { entityFromRpcResult } from \"../../utils/entities\"\n\nexport type QueryOptionsIncludeData = {\n attributes?: boolean\n payload?: boolean\n metadata?: boolean\n}\nexport type QueryOptionsOrderBy = {\n name: string\n type: \"string\" | \"numeric\"\n desc: \"asc\" | \"desc\"\n}\n\nexport type QueryOptions = {\n includeData?: QueryOptionsIncludeData\n atBlock?: bigint\n orderBy?: QueryOptionsOrderBy[]\n resultsPerPage?: number | undefined\n cursor?: string | undefined\n}\n\nexport type QueryReturnType = {\n entities: Entity[]\n cursor: string | undefined\n blockNumber: bigint | undefined\n}\n\nexport async function query(client: ArkivClient, query: string, queryOptions?: QueryOptions) {\n const rpcQueryOptions: RpcQueryOptions = {\n includeData: {\n key: true,\n payload: queryOptions?.includeData?.payload ?? true,\n attributes: queryOptions?.includeData?.attributes ?? false,\n contentType: queryOptions?.includeData?.metadata ?? false,\n expiration: queryOptions?.includeData?.metadata ?? false,\n owner: queryOptions?.includeData?.metadata ?? false,\n creator: queryOptions?.includeData?.metadata ?? false,\n createdAtBlock: queryOptions?.includeData?.metadata ?? false,\n lastModifiedAtBlock: queryOptions?.includeData?.metadata ?? false,\n transactionIndexInBlock: queryOptions?.includeData?.metadata ?? false,\n operationIndexInTransaction: queryOptions?.includeData?.metadata ?? false,\n },\n ...(queryOptions?.atBlock !== undefined && { atBlock: numberToHex(queryOptions.atBlock) }),\n ...(queryOptions?.orderBy && {\n orderBy: queryOptions?.orderBy.map((order) => ({\n name: order.name,\n type: order.type,\n desc: order.desc === \"desc\",\n })),\n }),\n ...(queryOptions?.resultsPerPage !== undefined && {\n resultsPerPage: numberToHex(queryOptions.resultsPerPage),\n }),\n ...(queryOptions?.cursor !== undefined && { cursor: queryOptions?.cursor }),\n }\n\n const result = await client.request({\n method: \"arkiv_query\",\n params: [query, rpcQueryOptions],\n })\n\n const entities = await Promise.all(result.data.map((entity) => entityFromRpcResult(entity)))\n\n return {\n entities,\n cursor: result.cursor,\n blockNumber: BigInt(result.blockNumber),\n }\n}\n","import { decodeEventLog, type Hex, parseAbi, toHex } from \"viem\"\nimport type { ArkivClient } from \"../../clients/baseClient\"\nimport type { PublicArkivClient } from \"../../clients/createPublicClient\"\nimport type {\n OnEntityCreatedEvent,\n OnEntityDeletedEvent,\n OnEntityExpiredEvent,\n OnEntityExpiresInExtendedEvent,\n OnEntityOwnerChangedEvent,\n OnEntityUpdatedEvent,\n} from \"../../types/events\"\nimport { getLogger } from \"../../utils/logger\"\n\nconst logger = getLogger(\"actions:public:subscribe-entity-events\")\n\nexport const arkivABI = parseAbi([\n \"event ArkivEntityCreated(uint256 indexed entityKey, address indexed ownerAddress, uint256 expirationBlock, uint256 cost)\",\n \"event ArkivEntityUpdated(uint256 indexed entityKey, address indexed ownerAddress, uint256 oldExpirationBlock, uint256 newExpirationBlock, uint256 cost)\",\n \"event ArkivEntityExpired(uint256 indexed entityKey, address indexed ownerAddress)\",\n \"event ArkivEntityDeleted(uint256 indexed entityKey, address indexed ownerAddress)\",\n \"event ArkivEntityBTLExtended(uint256 indexed entityKey, address indexed ownerAddress, uint256 oldExpirationBlock, uint256 newExpirationBlock, uint256 cost)\",\n \"event ArkivEntityOwnerChanged(uint256 indexed entityKey, address indexed oldOwnerAddress, address indexed newOwnerAddress)\",\n])\n\nexport async function subscribeEntityEvents(\n client: ArkivClient,\n {\n onError,\n onEntityCreated,\n onEntityUpdated,\n onEntityDeleted,\n onEntityExpired,\n onEntityExpiresInExtended,\n onEntityOwnerChanged,\n }: {\n onError: ((error: Error) => void) | undefined\n onEntityCreated?: ((event: OnEntityCreatedEvent) => void) | undefined\n onEntityUpdated?: ((event: OnEntityUpdatedEvent) => void) | undefined\n onEntityDeleted?: ((event: OnEntityDeletedEvent) => void) | undefined\n onEntityExpired?: ((event: OnEntityExpiredEvent) => void) | undefined\n onEntityExpiresInExtended?: ((event: OnEntityExpiresInExtendedEvent) => void) | undefined\n onEntityOwnerChanged?: ((event: OnEntityOwnerChangedEvent) => void) | undefined\n },\n pollingInterval?: number,\n fromBlock?: bigint,\n): Promise<() => void> {\n const unsubscribe = (client as PublicArkivClient).watchEvent({\n pollingInterval: pollingInterval ?? 1000,\n fromBlock,\n events: arkivABI,\n onLogs: (logs) => {\n logger(\"logs from subscribeEntityEvents %o\", logs)\n for (const log of logs) {\n const event = decodeEventLog({\n abi: arkivABI,\n topics: log.topics as [Hex, ...Hex[]] | [],\n data: log.data,\n })\n logger(\"event from subscribeEntityEvents %o\", event)\n switch (event.eventName) {\n case \"ArkivEntityCreated\":\n onEntityCreated?.({\n entityKey: toHex(event.args.entityKey, { size: 32 }),\n owner: event.args.ownerAddress,\n expirationBlock: Number(event.args.expirationBlock),\n cost: event.args.cost,\n })\n break\n case \"ArkivEntityUpdated\":\n onEntityUpdated?.({\n entityKey: toHex(event.args.entityKey, { size: 32 }),\n owner: event.args.ownerAddress,\n oldExpirationBlock: Number(event.args.oldExpirationBlock),\n newExpirationBlock: Number(event.args.newExpirationBlock),\n cost: event.args.cost,\n })\n break\n case \"ArkivEntityDeleted\":\n onEntityDeleted?.({\n entityKey: toHex(event.args.entityKey, { size: 32 }),\n owner: event.args.ownerAddress,\n })\n break\n case \"ArkivEntityBTLExtended\":\n onEntityExpiresInExtended?.({\n entityKey: toHex(event.args.entityKey, { size: 32 }),\n owner: event.args.ownerAddress,\n oldExpirationBlock: Number(event.args.oldExpirationBlock),\n newExpirationBlock: Number(event.args.newExpirationBlock),\n cost: event.args.cost,\n })\n break\n case \"ArkivEntityExpired\":\n onEntityExpired?.({\n entityKey: toHex(event.args.entityKey, { size: 32 }),\n owner: event.args.ownerAddress,\n })\n break\n case \"ArkivEntityOwnerChanged\":\n onEntityOwnerChanged?.({\n entityKey: toHex(event.args.entityKey, { size: 32 }),\n oldOwner: event.args.oldOwnerAddress,\n newOwner: event.args.newOwnerAddress,\n })\n break\n default:\n console.warn(\"unknown event from subscribeEntityEvents\", event)\n break\n }\n }\n },\n onError: (error) => {\n console.error(\"error from subscribeEntityEvents\", error)\n onError?.(error)\n },\n })\n\n return unsubscribe\n}\n","import type { Account, Chain, Client, Hex, PublicActions, Transport } from \"viem\"\nimport { getBlockTiming } from \"../../actions/public/getBlockTiming\"\nimport { getEntity } from \"../../actions/public/getEntity\"\nimport { getEntityCount } from \"../../actions/public/getEntityCount\"\nimport { type QueryOptions, type QueryReturnType, query } from \"../../actions/public/query\"\nimport { subscribeEntityEvents } from \"../../actions/public/subscribeEntityEvents\"\nimport { QueryBuilder, SelectQueryBuilder } from \"../../query/queryBuilder\"\nimport type { EntitySelection, FullEntity, ProjectedEntity, SelectArg } from \"../../query/selection\"\nimport type { Entity } from \"../../types/entity\"\nimport type {\n OnEntityCreatedEvent,\n OnEntityDeletedEvent,\n OnEntityExpiredEvent,\n OnEntityExpiresInExtendedEvent,\n OnEntityUpdatedEvent,\n} from \"../../types/events\"\n\nexport type PublicArkivActions<\n transport extends Transport = Transport,\n chain extends Chain | undefined = Chain | undefined,\n account extends Account | undefined = Account | undefined,\n> = Pick<\n PublicActions<transport, chain, account>,\n | \"getBalance\"\n | \"getBlock\"\n | \"getBlockNumber\"\n | \"getChainId\"\n | \"getLogs\"\n | \"getTransaction\"\n | \"getTransactionCount\"\n | \"getTransactionReceipt\"\n | \"waitForTransactionReceipt\"\n | \"watchEvent\"\n> & {\n /**\n * Returns the entity with the given key.\n *\n * - Docs: https://docs.arkiv.network/ts-sdk/actions/public/getEntity\n *\n * @param key - The entity key (hex string)\n * @returns The entity with the given key. {@link Entity}\n *\n * @example\n * import { createPublicClient, http } from 'arkiv'\n * import { braga } from 'arkiv/chains'\n *\n * const client = createPublicClient({\n * chain: braga,\n * transport: http(),\n * })\n * const entity = await client.getEntity(\"0x123\")\n * // {\n * // key: \"0x123\",\n * // value: \"0x123\",\n * // }\n */\n getEntity: (key: Hex) => Promise<Entity>\n\n /**\n * Returns a SelectQueryBuilder for building and executing queries — the recommended way to\n * read entities. You declare up front which parts of an entity you want returned, so results\n * always contain exactly the data you asked for.\n *\n * - Docs: https://docs.arkiv.network/ts-sdk/actions/public/query\n *\n * @param selection - What to include in the results. Omit it (or pass `\"*\"`) to select everything,\n * or pass an object to select specific parts (at least one field is required). Every part is\n * opt-in, including the `key`. The selection is flat — each field maps to an entity field.\n * {@link SelectArg}\n * @returns A SelectQueryBuilder instance for building and executing queries. {@link SelectQueryBuilder}\n *\n * @example\n * import { createPublicClient, http } from 'arkiv'\n * import { braga } from 'arkiv/chains'\n * import { eq } from 'arkiv/query'\n *\n * const client = createPublicClient({\n * chain: braga,\n * transport: http(),\n * })\n * // select everything\n * await client.select().where(eq(\"category\", \"docs\")).fetch()\n * await client.select(\"*\").where(eq(\"category\", \"docs\")).fetch()\n * // only the key\n * await client.select({ key: true }).where(eq(\"category\", \"docs\")).fetch()\n * // select specific fields — result typed { owner: Hex; attributes: Attribute[] }\n * await client.select({ owner: true, attributes: true }).fetch()\n * // a single field — result typed { owner: Hex }\n * await client.select({ owner: true }).fetch()\n */\n select: {\n /** Select every field. Pass nothing or `\"*\"`; the returned entities contain all fields. */\n (selection?: \"*\"): SelectQueryBuilder<FullEntity>\n /**\n * Pick the entity fields to return. Set the ones you want to `true` (at least one is required);\n * the result is typed to exactly those fields, so reading anything else is a compile error.\n *\n * Available fields: `key`, `owner`, `creator`, `contentType`, `payload`, `attributes`,\n * `expiresAtBlock`, `createdAtBlock`, `lastModifiedAtBlock`, `transactionIndexInBlock`,\n * `operationIndexInTransaction`.\n *\n * Pass the selection inline so its fields stay literal `true`. A selection stored in a `let`/\n * `const` variable widens to `boolean` and the result type can no longer be narrowed — annotate\n * it `as const` (e.g. `const sel = { owner: true } as const`) in that case.\n *\n * @example\n * client.select({ owner: true, attributes: true }) // entities typed { owner, attributes }\n * client.select({ key: true, payload: true }) // includes payload → toText()/toJson() too\n */\n <const S extends EntitySelection>(selection: S): SelectQueryBuilder<ProjectedEntity<S>>\n /**\n * Dynamic selection: accepts a value typed {@link SelectArg} (e.g. built at runtime). The\n * result cannot be narrowed in this case, so the entities are typed as the full entity.\n */\n (selection: SelectArg): SelectQueryBuilder<FullEntity>\n }\n\n /**\n * Returns a QueryBuilder instance for building and executing queries.\n * The QueryBuilder object follows the Builder pattern, allowing you to chain methods to build a query and then execute it.\n *\n * - Docs: https://docs.arkiv.network/ts-sdk/actions/public/query\n *\n * @deprecated Use {@link select} instead. `buildQuery()` returns only the entity `key` unless\n * you remember to opt in to data with `withAttributes()`/`withMetadata()`/`withPayload()`, which\n * is an easy mistake. `select()` makes the selection explicit. This method remains for backwards\n * compatibility and will be removed in a future release.\n *\n * @returns A QueryBuilder instance for building and executing queries. {@link QueryBuilder}\n *\n * @example\n * import { createPublicClient, http } from 'arkiv'\n * import { braga } from 'arkiv/chains'\n *\n * const client = createPublicClient({\n * chain: braga,\n * transport: http(),\n * })\n * const query = client.buildQuery()\n * const entities = await query.where(\"key\", \"=\", \"value\").ownedBy(\"0x123\").fetch()\n *\n */\n buildQuery: () => QueryBuilder\n\n /**\n * Returns a QueryResult instance for fetching the results of a raw query.\n * If no query options are provided, all payload is included, but no metadata (like owner, expiredAt, etc.) and attributes.\n * @param query - The raw query string\n * @param queryOptions - The optional query options - {@link QueryOptions}\n * @returns A QueryReturnType instance - {@link QueryReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'arkiv'\n * import { braga } from 'arkiv/chains'\n *\n * const client = createPublicClient({\n * chain: braga,\n * transport: http(),\n * })\n * const queryResult = client.query('key = value && $owner = 0x123')\n * // queryResult = { entities: [{ key: \"0x123\", value: \"0x123\" }], cursor: undefined, blockNumber: undefined }\n * const queryResultWithOptions = client.query('key = value && $owner = 0x123', {\n * includeData: {\n * attributes: false,\n * payload: true,\n * metadata: true,\n * },\n * orderBy: [{ name: \"key\", type: \"string\", desc: \"asc\" }],\n * resultsPerPage: 10,\n * cursor: undefined,\n * atBlock: undefined,\n * })\n * // queryResultWithOptions = { entities: [{ key: \"0x123\", value: \"0x123\" }], cursor: \"...\", blockNumber: 32223n }\n */\n query: (query: string, queryOptions?: QueryOptions) => Promise<QueryReturnType>\n\n /**\n * Returns the number of entities in the DBChain.\n * @returns The number of entities in the DBChain\n *\n * @example\n * import { createPublicClient, http } from 'arkiv'\n * import { braga } from 'arkiv/chains'\n *\n * const client = createPublicClient({\n * chain: braga,\n * transport: http(),\n * })\n * const entityCount = await client.getEntityCount()\n * // entityCount = 0\n */\n getEntityCount: () => Promise<number>\n\n /**\n * Returns the current block timing.\n * @returns The current block timing. {@link GetBlockTimingReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'arkiv'\n * import { braga } from 'arkiv/chains'\n *\n * const client = createPublicClient({\n * chain: braga,\n * transport: http(),\n * })\n * const blockTiming = await client.getBlockTiming()\n * // {\n * // currentBlock: 10n, // block number\n * // currentBlockTime: 1234567890, // block timestamp\n * // blockDuration: 2, // in seconds\n * // }\n */\n getBlockTiming: () => Promise<{\n currentBlock: bigint\n currentBlockTime: number\n blockDuration: number\n }>\n\n /**\n * Subscribes to entity events.\n * Takes an object with event handlers: {onError, onEntityCreated, onEntityUpdated, onEntityDeleted, onEntityExpiresInExtended}\n * @param pollingInterval - The polling interval in milliseconds\n * @param fromBlock - The block number to start from\n * @returns A function to unsubscribe from the events\n *\n * @example\n * import { createPublicClient, http } from 'arkiv'\n * import { braga } from 'arkiv/chains'\n *\n * const client = createPublicClient({\n * chain: braga,\n * transport: http(),\n * })\n * const unsubscribe = await client.subscribeEntityEvents({\n * onError: (error) => console.error(\"subscribeEntityEvents error\", error),\n * })\n * unsubscribe() // unsubscribe from the events\n */\n subscribeEntityEvents: (\n {\n onError,\n onEntityCreated,\n onEntityUpdated,\n onEntityDeleted,\n onEntityExpiresInExtended,\n }: {\n onError?: (error: Error) => void\n onEntityCreated?: (event: OnEntityCreatedEvent) => void\n onEntityUpdated?: (event: OnEntityUpdatedEvent) => void\n onEntityDeleted?: (event: OnEntityDeletedEvent) => void\n onEntityExpired?: (event: OnEntityExpiredEvent) => void\n onEntityExpiresInExtended?: (event: OnEntityExpiresInExtendedEvent) => void\n },\n pollingInterval?: number,\n fromBlock?: bigint,\n ) => Promise<() => void>\n}\n\nexport function publicArkivActions<\n transport extends Transport = Transport,\n chain extends Chain | undefined = Chain | undefined,\n account extends Account | undefined = Account | undefined,\n>(client: Client<transport, chain, account>) {\n return {\n getEntity: (key: Hex) => getEntity(client, key),\n query: (rawQuery: string, queryOptions?: QueryOptions) => query(client, rawQuery, queryOptions),\n buildQuery: () => new QueryBuilder(client),\n select: (selection?: SelectArg) => new SelectQueryBuilder(client, selection),\n getBlockTiming: () => getBlockTiming(client),\n getEntityCount: () => getEntityCount(client),\n subscribeEntityEvents: (\n {\n onError,\n onEntityCreated,\n onEntityUpdated,\n onEntityDeleted,\n onEntityExpired,\n onEntityExpiresInExtended,\n }: {\n onError?: (error: Error) => void\n onEntityCreated?: (event: OnEntityCreatedEvent) => void\n onEntityUpdated?: (event: OnEntityUpdatedEvent) => void\n onEntityDeleted?: (event: OnEntityDeletedEvent) => void\n onEntityExpired?: (event: OnEntityExpiredEvent) => void\n onEntityExpiresInExtended?: (event: OnEntityExpiresInExtendedEvent) => void\n },\n pollingInterval?: number,\n fromBlock?: bigint,\n ) =>\n subscribeEntityEvents(\n client,\n {\n onError,\n onEntityCreated,\n onEntityUpdated,\n onEntityDeleted,\n onEntityExpired,\n onEntityExpiresInExtended,\n },\n pollingInterval,\n fromBlock,\n ),\n }\n}\n","import type {\n Account,\n Address,\n Chain,\n Client,\n ParseAccount,\n Prettify,\n PublicClientConfig,\n RpcSchema,\n Transport,\n} from \"viem\"\nimport { createClient, publicActions } from \"viem\"\nimport type { ArkivRpcSchema } from \"../types/rpcSchema\"\nimport { type PublicArkivActions, publicArkivActions } from \"./decorators/arkivPublic\"\n\nexport type PublicArkivClient<\n transport extends Transport = Transport,\n chain extends Chain | undefined = Chain | undefined,\n accountOrAddress extends Account | undefined = undefined,\n rpcSchema extends RpcSchema | undefined = ArkivRpcSchema,\n> = Prettify<\n Client<transport, chain, accountOrAddress, rpcSchema, PublicArkivActions<transport, chain>>\n>\n\n/**\n * Creates a Public Client with a given [Transport](https://viem.sh/docs/clients/intro) configured for a [Chain](https://viem.sh/docs/clients/chains).\n *\n * - Docs: https://docs.arkiv.network/ts-sdk/clients/public\n *\n * A Public Client is an interface to \"public\" [Ethereum JSON-RPC API](https://ethereum.org/en/developers/docs/apis/json-rpc/), [Arkiv JSON-RPC API](https://docs.arkiv.network/json-rpc/), and [Braga JSON-RPC API](https://braga.holesky.arkiv.network/rpc) methods such as retrieving block numbers, transactions, reading from smart contracts, etc through [Public Actions](/docs/actions/public/introduction).\n *\n * @param parameters - Configuration object for the public client (chain, transport, etc.)\n * @returns A Arkiv Public Client. {@link PublicArkivClient}\n *\n * @example\n * import { createPublicClient, http } from 'arkiv'\n * import { braga } from 'arkiv/chains'\n *\n * const client = createPublicClient({\n * chain: braga,\n * transport: http(),\n * })\n */\nexport function createPublicClient<\n transport extends Transport,\n chain extends Chain | undefined = undefined,\n accountOrAddress extends Account | Address | undefined = undefined,\n rpcSchema extends RpcSchema | undefined = ArkivRpcSchema,\n>(\n parameters: PublicClientConfig<transport, chain, accountOrAddress, rpcSchema>,\n): PublicArkivClient<transport, chain, ParseAccount<accountOrAddress>, rpcSchema> {\n const { key = \"public\", name = \"Public Client\" } = parameters\n const client = createClient({\n ...parameters,\n key,\n name,\n })\n\n return client.extend(publicActions).extend(publicArkivActions) as unknown as PublicArkivClient<\n transport,\n chain,\n ParseAccount<accountOrAddress>,\n rpcSchema\n >\n}\n","// src/utils/compression.ts\n\nimport type { BrotliWasmType } from \"brotli-wasm\"\nimport { getLogger } from \"./logger\"\n\nconst logger = getLogger(\"utils:compression\")\n\n// Detect if we're in Node.js environment\nconst isNode = typeof process !== \"undefined\" && process.versions?.node != null\n\nlet zlib: typeof import(\"zlib\") | null = null\nlet brotli: BrotliWasmType | null = null\n\n// Lazy load zlib (Node.js only)\nasync function getZlib(): Promise<typeof import(\"zlib\") | null> {\n if (!isNode) return null\n\n if (!zlib) {\n try {\n zlib = await import(\"zlib\")\n } catch (error) {\n console.error(\"Error importing zlib\", error)\n return null\n }\n }\n return zlib\n}\n\n// Lazy load brotli-wasm (browser/fallback)\nasync function getBrotli(): Promise<BrotliWasmType | null> {\n if (brotli) return brotli\n\n try {\n const brotliModule = await import(\"brotli-wasm\")\n brotli = (brotliModule.default ? await brotliModule.default : brotliModule) as BrotliWasmType\n } catch (error) {\n console.error(\"Error importing brotli-wasm\", error)\n return null\n }\n\n return brotli\n}\n\nexport async function compress(data: Uint8Array): Promise<Uint8Array> {\n logger(\"Compressing data size %d\", data.length)\n\n // Try Node.js zlib first (if available)\n if (isNode) {\n const zlibModule = await getZlib()\n if (zlibModule) {\n try {\n // zlib.brotliCompress expects Buffer, returns Buffer\n const buffer = Buffer.from(data)\n const compressed = zlibModule.brotliCompressSync(buffer)\n const result = new Uint8Array(compressed)\n logger(\"Brotli compressed with zlib size %d\", result.length)\n return result\n } catch (error) {\n console.warn(\"zlib compression failed, falling back to brotli-wasm\", error)\n }\n }\n }\n\n // Fallback to brotli-wasm (browser or if zlib fails)\n const brotliInstance = await getBrotli()\n if (!brotliInstance) {\n console.warn(\"Brotli instance not found, not compressing data\")\n return data\n }\n\n const brotliCompressed = brotliInstance.compress(data)\n logger(\"Brotli compressed with wasm size %d\", brotliCompressed.length)\n return brotliCompressed\n}\n\nexport async function decompress(data: Uint8Array): Promise<Uint8Array> {\n // Try Node.js zlib first (if available)\n if (isNode) {\n const zlibModule = await getZlib()\n if (zlibModule) {\n try {\n // zlib.brotliDecompress expects Buffer, returns Buffer\n const buffer = Buffer.from(data)\n const decompressed = zlibModule.brotliDecompressSync(buffer)\n const result = new Uint8Array(decompressed)\n logger(\"Brotli decompressed with zlib size %d\", result.length)\n return result\n } catch (error) {\n console.warn(\"zlib decompression failed, falling back to brotli-wasm\", error)\n }\n }\n }\n\n // Fallback to brotli-wasm (browser or if zlib fails)\n const brotliInstance = await getBrotli()\n if (!brotliInstance) {\n console.warn(\"Brotli instance not found, not decompressing data\")\n return data\n }\n\n return brotliInstance.decompress(data)\n}\n","import { BLOCK_TIME } from \"../consts\"\nimport { InvalidAttributeError, InvalidExpirationError } from \"../errors\"\nimport type { Attribute } from \"../types\"\n\n/**\n * Expiration on Arkiv is measured in blocks (1 block =\n * 2 seconds), so the value must be a positive integer that is\n * a multiple of the block time.\n *\n * @param expiresIn - The expiration in seconds.\n * @throws {InvalidExpirationError} If the value is not a positive integer that\n * is a multiple of the block time.\n */\nexport function validateExpiresIn(expiresIn: number): void {\n if (!Number.isInteger(expiresIn) || expiresIn <= 0 || expiresIn % BLOCK_TIME !== 0) {\n throw new InvalidExpirationError(expiresIn)\n }\n}\n\n/**\n * Validates a single attribute. Arkiv supports string and number attribute\n * values, but numeric values must be integers.\n *\n * @param attribute - The attribute to validate.\n * @throws {InvalidAttributeError} If the attribute has a non-integer numeric\n * value.\n */\nexport function validateAttribute(attribute: Attribute): void {\n if (typeof attribute.value === \"number\" && !Number.isInteger(attribute.value)) {\n throw new InvalidAttributeError(attribute.key, attribute.value)\n }\n}\n","import { type Hex, hexToString, TransactionExecutionError, toBytes, toHex, toRlp } from \"viem\"\nimport type { ChangeOwnershipParameters } from \"../actions/wallet/changeOwnership\"\nimport type { CreateEntityParameters } from \"../actions/wallet/createEntity\"\nimport type { DeleteEntityParameters } from \"../actions/wallet/deleteEntity\"\nimport type { ExtendEntityParameters } from \"../actions/wallet/extendEntity\"\nimport type { UpdateEntityParameters } from \"../actions/wallet/updateEntity\"\nimport type { ArkivClient } from \"../clients/baseClient\"\nimport type { WalletArkivClient } from \"../clients/createWalletClient\"\nimport { ARKIV_ADDRESS, BLOCK_TIME } from \"../consts\"\nimport { EntityMutationError } from \"../errors\"\nimport type { TxParams } from \"../types\"\nimport { compress } from \"./compression\"\nimport { getLogger } from \"./logger\"\nimport { validateAttribute, validateExpiresIn } from \"./validation\"\n\nconst logger = getLogger(\"utils:arkiv-transactions\")\n\nexport function opsToTxData({\n creates,\n updates,\n deletes,\n extensions,\n ownershipChanges,\n}: {\n creates?: CreateEntityParameters[]\n updates?: UpdateEntityParameters[]\n deletes?: DeleteEntityParameters[]\n extensions?: ExtendEntityParameters[]\n ownershipChanges?: ChangeOwnershipParameters[]\n}) {\n function formatAttributes<T extends string | number | bigint | boolean>(attribute: {\n key: string\n value: T\n }): [Hex, Hex] {\n return [\n toHex(attribute.key),\n toHex(typeof attribute.value === \"number\" && attribute.value === 0 ? \"\" : attribute.value),\n ]\n }\n\n const payload = [\n //creates\n (creates ?? []).map((item) => {\n validateExpiresIn(item.expiresIn)\n item.attributes.forEach(validateAttribute)\n return [\n toHex(item.expiresIn / BLOCK_TIME),\n toHex(item.contentType),\n toHex(item.payload),\n item.attributes\n .filter((attribute) => typeof attribute.value === \"string\")\n .map(formatAttributes),\n item.attributes\n .filter((attribute) => typeof attribute.value === \"number\")\n .map(formatAttributes),\n ]\n }),\n //updates\n (updates ?? []).map((item) => {\n validateExpiresIn(item.expiresIn)\n item.attributes.forEach(validateAttribute)\n return [\n item.entityKey,\n toHex(item.contentType),\n toHex(item.expiresIn / BLOCK_TIME),\n toHex(item.payload),\n item.attributes\n .filter((attribute) => typeof attribute.value === \"string\")\n .map(formatAttributes),\n item.attributes\n .filter((attribute) => typeof attribute.value === \"number\")\n .map(formatAttributes),\n ]\n }),\n //deletes\n (deletes ?? []).map((item) => item.entityKey),\n //extends\n (extensions ?? []).map((item) => {\n validateExpiresIn(item.expiresIn)\n return [item.entityKey, toHex(item.expiresIn / BLOCK_TIME)]\n }),\n //ownershipChanges TODO\n (ownershipChanges ?? []).map((item) => [item.entityKey, item.newOwner]),\n ]\n\n logger(\"txData to send as RLP %o length %d\", payload, payload.length)\n\n return toRlp(payload)\n}\n\nexport async function sendArkivTransaction(client: ArkivClient, data: Hex, txParams?: TxParams) {\n if (!client.account) throw new Error(\"Account required\")\n const walletClient = client as WalletArkivClient\n\n logger(\"Sending transaction %o\", {\n account: client.account,\n chain: client.chain,\n to: ARKIV_ADDRESS,\n value: 0n,\n data,\n ...txParams,\n })\n\n try {\n const compressed = await compress(toBytes(data))\n const txHash = await walletClient.sendTransaction({\n account: client.account,\n chain: client.chain,\n to: ARKIV_ADDRESS,\n value: 0n,\n data: toHex(compressed),\n ...txParams,\n })\n\n const receipt = await walletClient.waitForTransactionReceipt({ hash: txHash })\n logger(\"Tx receipt %o\", receipt)\n if (receipt.status === \"reverted\") {\n try {\n const callResult = await walletClient.call({\n account: client.account,\n to: ARKIV_ADDRESS,\n value: 0n,\n data: toHex(compressed),\n ...txParams,\n })\n throw new EntityMutationError(\n `Transaction ${receipt.transactionHash} reverted. Please make sure the data for entities doesn't contain invalid characters or invalid data types.\n Reason: ${callResult.data ? hexToString(callResult.data) : \"No reason provided by backend.\"}`,\n )\n } catch (err) {\n const error = err as { cause?: { details?: string } }\n const reason = error.cause?.details ?? \"No reason provided by backend.\"\n logger(\n \"Error while calling to get more details about reverted transaction. Reason: %s\",\n reason,\n )\n throw new EntityMutationError(\n `Transaction ${receipt.transactionHash} reverted. Reason: ${reason}`,\n )\n }\n }\n\n return receipt\n } catch (error) {\n let message = \"Transaction failed\"\n if (error instanceof TransactionExecutionError) {\n message += `: ${error.details}`\n } else if (error instanceof EntityMutationError) {\n throw error\n }\n\n logger(\"%s Detailed error stack: %o\", message, error)\n throw new EntityMutationError(message)\n }\n}\n","import type { Hex } from \"viem\"\nimport type { ArkivClient } from \"../../clients/baseClient\"\nimport type { TxParams } from \"../../types\"\nimport { opsToTxData, sendArkivTransaction } from \"../../utils/arkivTransactions\"\nimport { getLogger } from \"../../utils/logger\"\n\nconst logger = getLogger(\"actions:wallet:change-ownership\")\n\n/**\n * Parameters for the deleteEntity function.\n * - entityKey: The key of the entity to delete.\n */\nexport type ChangeOwnershipParameters = {\n entityKey: Hex\n newOwner: Hex\n}\n\n/**\n * Return type for the deleteEntity function.\n * - entityKey: The key of the entity.\n * - txHash: The transaction hash.\n */\nexport type ChangeOwnershipReturnType = {\n entityKey: Hex\n txHash: string\n}\n\nexport async function changeOwnership(\n client: ArkivClient,\n data: ChangeOwnershipParameters,\n txParams?: TxParams,\n): Promise<ChangeOwnershipReturnType> {\n logger(\"changeOwnership %o\", data)\n const txData = opsToTxData({ ownershipChanges: [data] })\n const receipt = await sendArkivTransaction(client, txData, txParams)\n\n logger(\"Receipt from changeOwnership %o\", receipt)\n\n return {\n txHash: receipt.transactionHash,\n entityKey: data.entityKey,\n }\n}\n","import type { Hash, Hex } from \"viem\"\nimport type { ArkivClient } from \"../../clients/baseClient\"\nimport type { Attribute, MimeType, TxParams } from \"../../types\"\nimport { opsToTxData, sendArkivTransaction } from \"../../utils/arkivTransactions\"\nimport { getLogger } from \"../../utils/logger\"\n\nconst logger = getLogger(\"actions:wallet:create-entity\")\n\n/**\n * Parameters for the createEntity function.\n * - payload: The payload of the entity.\n * - attributes: The attributes of the entity. Attribute values may be strings\n * or numbers, but numeric values **must be integers**. To store a non-integer,\n * scale it to an integer (e.g. `1.5` -> `1500`) to preserve numeric ordering,\n * or pass it as a string (e.g. `\"1.5\"`). A non-integer numeric value throws an\n * {@link InvalidAttributeError}.\n * - contentType: The content type of the entity.\n * - expiresIn: How long until the entity expires, in seconds. Because Arkiv\n * measures expiration in blocks (1 block = 2 seconds), this **must be a\n * positive integer and a multiple of the block time (2 seconds)**\n * Invalid values throw an {@link InvalidExpirationError}.\n */\nexport type CreateEntityParameters = {\n payload: Uint8Array\n /** Entity attributes. Numeric values must be integers (scale non-integers, e.g. `1.5` -> `1500`, or use a string). Throws {@link InvalidAttributeError} otherwise. */\n attributes: Attribute[]\n contentType: MimeType | string\n /** Seconds until expiry. Must be a positive integer and a multiple of the 2s block time.\n * Throws {@link InvalidExpirationError} otherwise. */\n expiresIn: number\n}\n\n/**\n * Return type for the createEntity function.\n * - entityKey: The key of the entity.\n * - txHash: The transaction hash.\n */\nexport type CreateEntityReturnType = {\n entityKey: Hex\n txHash: Hash\n}\n\nexport async function createEntity(\n client: ArkivClient,\n data: CreateEntityParameters,\n txParams?: TxParams,\n): Promise<CreateEntityReturnType> {\n logger(\"createEntity %o\", data)\n const txData = opsToTxData({ creates: [data] })\n const receipt = await sendArkivTransaction(client, txData, txParams)\n\n logger(\"Receipt from createEntity %o\", receipt)\n\n return {\n txHash: receipt.transactionHash as Hash,\n entityKey: receipt.logs[0].topics[1] as Hex,\n }\n}\n","import type { Hash, Hex } from \"viem\"\nimport type { ArkivClient } from \"../../clients/baseClient\"\nimport type { TxParams } from \"../../types\"\nimport { opsToTxData, sendArkivTransaction } from \"../../utils/arkivTransactions\"\nimport { getLogger } from \"../../utils/logger\"\n\nconst logger = getLogger(\"actions:wallet:delete-entity\")\n\n/**\n * Parameters for the deleteEntity function.\n * - entityKey: The key of the entity to delete.\n */\nexport type DeleteEntityParameters = {\n entityKey: Hex\n}\n\n/**\n * Return type for the deleteEntity function.\n * - entityKey: The key of the entity.\n * - txHash: The transaction hash.\n */\nexport type DeleteEntityReturnType = {\n entityKey: Hex\n txHash: Hash\n}\n\nexport async function deleteEntity(\n client: ArkivClient,\n data: DeleteEntityParameters,\n txParams?: TxParams,\n): Promise<DeleteEntityReturnType> {\n logger(\"deleteEntity %o\", data)\n const txData = opsToTxData({ deletes: [data] })\n const receipt = await sendArkivTransaction(client, txData, txParams)\n\n logger(\"Receipt from deleteEntity %o\", receipt)\n\n return {\n txHash: receipt.transactionHash as Hash,\n entityKey: data.entityKey,\n }\n}\n","import type { Hash, Hex } from \"viem\"\nimport type { ArkivClient } from \"../../clients/baseClient\"\nimport type { TxParams } from \"../../types\"\nimport { opsToTxData, sendArkivTransaction } from \"../../utils/arkivTransactions\"\nimport { getLogger } from \"../../utils/logger\"\n\nconst logger = getLogger(\"actions:wallet:extend-entity\")\n\n/**\n * Parameters for the extendEntity function.\n * - entityKey: The key of the entity to extend.\n * - expiresIn: How long to extend the entity by, in seconds. Because Arkiv\n * measures expiration in blocks (1 block = 2 seconds), this **must be a\n * positive integer and a multiple of the block time (2 seconds)**.\n * Invalid values throw an {@link InvalidExpirationError}.\n */\nexport type ExtendEntityParameters = {\n entityKey: Hex\n /** Seconds to extend by. Must be a positive integer and a multiple of the 2s block time.\n * Throws {@link InvalidExpirationError} otherwise. */\n expiresIn: number\n}\n\n/**\n * Return type for the extendEntity function.\n * - entityKey: The key of the entity.\n * - txHash: The transaction hash.\n */\nexport type ExtendEntityReturnType = {\n entityKey: Hex\n txHash: Hash\n}\n\nexport async function extendEntity(\n client: ArkivClient,\n data: ExtendEntityParameters,\n txParams?: TxParams,\n): Promise<ExtendEntityReturnType> {\n logger(\"extendEntity %o\", data)\n const txData = opsToTxData({ extensions: [data] })\n const receipt = await sendArkivTransaction(client, txData, txParams)\n\n logger(\"Receipt from extendEntity %o\", receipt)\n\n return {\n txHash: receipt.transactionHash as Hash,\n entityKey: receipt.logs[0].topics[1] as Hex,\n }\n}\n","import type { Hash, Hex, TransactionReceipt } from \"viem\"\nimport type { ArkivClient } from \"../../clients/baseClient\"\nimport type { TxParams } from \"../../types\"\nimport { opsToTxData, sendArkivTransaction } from \"../../utils/arkivTransactions\"\nimport { getLogger } from \"../../utils/logger\"\nimport type { ChangeOwnershipParameters } from \"./changeOwnership\"\n\nconst logger = getLogger(\"actions:wallet:mutate-entities\")\n\nimport type { CreateEntityParameters } from \"./createEntity\"\nimport type { DeleteEntityParameters } from \"./deleteEntity\"\nimport type { ExtendEntityParameters } from \"./extendEntity\"\nimport type { UpdateEntityParameters } from \"./updateEntity\"\n\n/**\n * Parameters for the mutateEntities function.\n * - creates: The creates to perform.\n * - updates: The updates to perform.\n * - deletes: The deletes to perform.\n * - extensions: The extensions to perform.\n */\nexport type MutateEntitiesParameters = {\n creates?: CreateEntityParameters[]\n updates?: UpdateEntityParameters[]\n deletes?: DeleteEntityParameters[]\n extensions?: ExtendEntityParameters[]\n ownershipChanges?: ChangeOwnershipParameters[]\n}\n\nfunction parseReceipt(receipt: TransactionReceipt, params: MutateEntitiesParameters) {\n const createdEntities: Hex[] = []\n const updatedEntities: Hex[] = []\n const deletedEntities: Hex[] = []\n const extendedEntities: Hex[] = []\n const ownershipChanges: Hex[] = []\n\n const totalCreates = params.creates?.length ?? 0\n const totalUpdates = params.updates?.length ?? 0\n const totalDeletes = params.deletes?.length ?? 0\n const totalExtensions = params.extensions?.length ?? 0\n\n // iterate over all logs and parse the event\n // logs go in the following order: creates, deleted, updates, extends, ownership changes\n for (let index = 0; index < receipt.logs.length; index++) {\n const log = receipt.logs[index]\n\n if (index < totalCreates) {\n createdEntities.push(log.topics[1] as Hex)\n } else if (index < totalCreates + totalDeletes) {\n deletedEntities.push(log.topics[1] as Hex)\n } else if (index < totalCreates + totalUpdates + totalDeletes) {\n updatedEntities.push(log.topics[1] as Hex)\n } else if (index < totalCreates + totalUpdates + totalDeletes + totalExtensions) {\n extendedEntities.push(log.topics[1] as Hex)\n } else {\n ownershipChanges.push(log.topics[1] as Hex)\n }\n }\n\n return { createdEntities, updatedEntities, deletedEntities, extendedEntities, ownershipChanges }\n}\n\n/**\n * Return type for the mutateEntities function.\n * - txHash: The transaction hash.\n * - createdEntities: The keys of the created entities.\n * - updatedEntities: The keys of the updated entities.\n * - deletedEntities: The keys of the deleted entities.\n * - extendedEntities: The keys of the extended entities.\n * - ownershipChanges: The keys of the ownership changes.\n */\nexport type MutateEntitiesReturnType = {\n txHash: Hash\n createdEntities: Hex[]\n updatedEntities: Hex[]\n deletedEntities: Hex[]\n extendedEntities: Hex[]\n ownershipChanges: Hex[]\n}\nexport async function mutateEntities(\n client: ArkivClient,\n data: MutateEntitiesParameters,\n txParams?: TxParams,\n): Promise<MutateEntitiesReturnType> {\n if (!data.creates && !data.updates && !data.deletes && !data.extensions) {\n throw new Error(\"No operations to perform\")\n }\n\n const txData = opsToTxData({\n creates: data.creates ?? [],\n updates: data.updates ?? [],\n deletes: data.deletes ?? [],\n extensions: data.extensions ?? [],\n ownershipChanges: data.ownershipChanges ?? [],\n })\n\n const receipt = await sendArkivTransaction(client, txData, txParams)\n\n logger(\"Receipt from mutateEntities %o\", receipt)\n\n const { createdEntities, updatedEntities, deletedEntities, extendedEntities, ownershipChanges } =\n parseReceipt(receipt, data)\n return {\n txHash: receipt.transactionHash as Hash,\n createdEntities,\n updatedEntities,\n deletedEntities,\n extendedEntities,\n ownershipChanges,\n }\n}\n","import type { Hash, Hex } from \"viem\"\nimport type { ArkivClient } from \"../../clients/baseClient\"\nimport type { Attribute, MimeType, TxParams } from \"../../types\"\nimport { opsToTxData, sendArkivTransaction } from \"../../utils/arkivTransactions\"\nimport { getLogger } from \"../../utils/logger\"\n\nconst logger = getLogger(\"actions:wallet:update-entity\")\n\n/**\n * Parameters for the updateEntity function.\n * - entityKey: The key of the entity to update.\n * - payload: The payload of the entity.\n * - attributes: The attributes of the entity. Attribute values may be strings\n * or numbers, but numeric values **must be integers**. To store a non-integer,\n * scale it to an integer (e.g. `1.5` -> `1500`) to preserve numeric ordering,\n * or pass it as a string (e.g. `\"1.5\"`). A non-integer numeric value throws an\n * {@link InvalidAttributeError}.\n * - contentType: The content type of the entity.\n * - expiresIn: How long until the entity expires, in seconds. Because Arkiv\n * measures expiration in blocks (1 block = 2 seconds), this **must be a\n * positive integer and a multiple of the block time (2 seconds)**.\n * Invalid values throw an {@link InvalidExpirationError}.\n */\nexport type UpdateEntityParameters = {\n entityKey: Hex\n payload: Uint8Array\n /** Entity attributes. Numeric values must be integers (scale non-integers, e.g. `1.5` -> `1500`, or use a string). Throws {@link InvalidAttributeError} otherwise. */\n attributes: Attribute[]\n contentType: MimeType | string\n /** Seconds until expiry. Must be a positive integer and a multiple of the 2s block time.\n * Throws {@link InvalidExpirationError} otherwise. */\n expiresIn: number\n}\n\n/**\n * Return type for the updateEntity function.\n * - entityKey: The key of the entity.\n * - txHash: The transaction hash.\n */\nexport type UpdateEntityReturnType = {\n entityKey: Hex\n txHash: Hash\n}\n\nexport async function updateEntity(\n client: ArkivClient,\n data: UpdateEntityParameters,\n txParams?: TxParams,\n): Promise<UpdateEntityReturnType> {\n logger(\"updateEntity %o\", data)\n const txData = opsToTxData({ updates: [data] })\n const receipt = await sendArkivTransaction(client, txData, txParams)\n\n logger(\"Receipt from updateEntity %o\", receipt)\n\n return {\n txHash: receipt.transactionHash as Hash,\n entityKey: receipt.logs[0].topics[1] as Hex,\n }\n}\n","import type { Account, Chain, Client, PublicActions, Transport, WalletActions } from \"viem\"\nimport type {\n ChangeOwnershipParameters,\n ChangeOwnershipReturnType,\n} from \"../../actions/wallet/changeOwnership\"\nimport { changeOwnership } from \"../../actions/wallet/changeOwnership\"\nimport {\n type CreateEntityParameters,\n type CreateEntityReturnType,\n createEntity,\n} from \"../../actions/wallet/createEntity\"\nimport type {\n DeleteEntityParameters,\n DeleteEntityReturnType,\n} from \"../../actions/wallet/deleteEntity\"\nimport { deleteEntity } from \"../../actions/wallet/deleteEntity\"\nimport type {\n ExtendEntityParameters,\n ExtendEntityReturnType,\n} from \"../../actions/wallet/extendEntity\"\nimport { extendEntity } from \"../../actions/wallet/extendEntity\"\nimport type {\n MutateEntitiesParameters,\n MutateEntitiesReturnType,\n} from \"../../actions/wallet/mutateEntities\"\nimport { mutateEntities } from \"../../actions/wallet/mutateEntities\"\nimport type {\n UpdateEntityParameters,\n UpdateEntityReturnType,\n} from \"../../actions/wallet/updateEntity\"\nimport { updateEntity } from \"../../actions/wallet/updateEntity\"\nimport type { TxParams } from \"../../types\"\n\nexport type WalletArkivActions<\n transport extends Transport = Transport,\n chain extends Chain | undefined = Chain | undefined,\n account extends Account | undefined = Account | undefined,\n> = Pick<PublicActions<transport, chain, account>, \"waitForTransactionReceipt\" | \"call\"> &\n Pick<\n WalletActions<chain, account>,\n | \"addChain\"\n | \"sendCalls\"\n | \"waitForCallsStatus\"\n | \"sendTransaction\"\n | \"sendRawTransaction\"\n | \"signMessage\"\n | \"signTransaction\"\n > & {\n /**\n * Creates a new entity.\n *\n * - Docs: https://docs.arkiv.network/ts-sdk/actions/wallet/createEntity\n * - JSON-RPC Methods: [`eth_sendRawTransaction`](https://docs.arkiv.network/dev/json-rpc-api/#mutateEntities)\n *\n * @param data - The entity creation parameters\n * @param txParams - Optional transaction parameters\n * @returns The created entity with transaction hash\n *\n * @throws {InvalidExpirationError} If `expiresIn` is not a positive integer\n * that is a multiple of the block time (2 seconds).\n * @throws {InvalidAttributeError} If a numeric attribute value is not an\n * integer.\n *\n * @example\n * import { createPublicClient, http } from 'arkiv'\n * import { braga } from 'arkiv/chains'\n *\n * const client = createPublicClient({\n * chain: braga,\n * transport: http(),\n * })\n * const { entityKey, txHash } = await client.createEntity({\n * payload: toBytes(JSON.stringify({ entity: { entityType: \"testType\", entityId: \"testId\" } })),\n * attributes: [{ key: \"testKey\", value: \"testValue\" }],\n * expiresIn: 1000,\n * })\n * console.log(\"entityKey\", entityKey)\n * console.log(\"txHash\", txHash)\n * // {\n * // entityKey: \"0x123\",\n * // txHash: \"0x123\",\n * // }\n */\n createEntity: (\n data: CreateEntityParameters,\n txParams?: TxParams,\n ) => Promise<CreateEntityReturnType>\n\n /**\n * Updates the entity with the given key.\n *\n * - Docs: https://docs.arkiv.network/ts-sdk/actions/wallet/updateEntity\n * - JSON-RPC Methods: [`eth_sendRawTransaction`](https://docs.arkiv.network/dev/json-rpc-api/#mutateEntities)\n *\n * @param data - The entity update parameters\n * @param txParams - Optional transaction parameters\n * @returns The updated entity with transaction hash\n *\n * @throws {InvalidExpirationError} If `expiresIn` is not a positive integer\n * that is a multiple of the block time (2 seconds).\n * @throws {InvalidAttributeError} If a numeric attribute value is not an\n * integer.\n *\n * @example\n * import { createWalletClient, http } from 'arkiv'\n * import { braga } from 'arkiv/chains'\n *\n * const client = createWalletClient({\n * chain: braga,\n * transport: http(),\n * })\n */\n updateEntity: (\n data: UpdateEntityParameters,\n txParams?: TxParams,\n ) => Promise<UpdateEntityReturnType>\n\n /**\n * Deletes the entity with the given key.\n *\n * - Docs: https://docs.arkiv.network/ts-sdk/actions/wallet/deleteEntity\n * - JSON-RPC Methods: [`eth_sendRawTransaction`](https://docs.arkiv.network/dev/json-rpc-api/#mutateEntities)\n *\n * @param data - The entity deletion parameters\n * @param txParams - Optional transaction parameters\n * @returns The deleted entity with transaction hash\n *\n * @example\n * import { createWalletClient, http } from 'arkiv'\n * import { braga } from 'arkiv/chains'\n *\n * const client = createWalletClient({\n * chain: braga,\n * transport: http(),\n * })\n * const { entityKey, txHash } = await client.deleteEntity({ entityKey: \"0x123\" })\n * console.log(\"entityKey\", entityKey)\n * console.log(\"txHash\", txHash)\n * // {\n * // entityKey: \"0x123\",\n * // txHash: \"0x123\",\n * // }\n */\n deleteEntity: (\n data: DeleteEntityParameters,\n txParams?: TxParams,\n ) => Promise<DeleteEntityReturnType>\n\n /**\n * Extends the entity with the given key.\n *\n * - Docs: https://docs.arkiv.network/ts-sdk/actions/wallet/extendEntity\n * - JSON-RPC Methods: [`eth_sendRawTransaction`](https://docs.arkiv.network/dev/json-rpc-api/#mutateEntities)\n *\n * @param data - The entity update parameters\n * @param txParams - Optional transaction parameters\n * @returns The updated entity with transaction hash\n *\n * @throws {InvalidExpirationError} If `expiresIn` is not a positive integer\n * that is a multiple of the block time (2 seconds).\n *\n * @example\n * import { createWalletClient, http } from 'arkiv'\n * import { braga } from 'arkiv/chains'\n *\n * const client = createWalletClient({\n * chain: braga,\n * transport: http(),\n * })\n * const { entityKey, txHash } = await client.extendEntity(\"0x123\", {\n * expiresIn: 1000,\n * })\n * console.log(\"entityKey\", entityKey)\n * console.log(\"txHash\", txHash)\n * // {\n * // entityKey: \"0x123\",\n * // txHash: \"0x123\",\n * // }\n */\n extendEntity: (\n data: ExtendEntityParameters,\n txParams?: TxParams,\n ) => Promise<ExtendEntityReturnType>\n\n /**\n * Changes the ownership of the entity with the given address.\n *\n * - Docs: https://docs.arkiv.network/ts-sdk/actions/wallet/changeOwnership\n * - JSON-RPC Methods: [`eth_sendRawTransaction`](https://docs.arkiv.network/dev/json-rpc-api/#mutateEntities)\n *\n * @param data - The ownership change parameters\n * @param txParams - Optional transaction parameters\n * @returns The entity with updated ownership and transaction hash\n */\n changeOwnership: (\n data: ChangeOwnershipParameters,\n txParams?: TxParams,\n ) => Promise<ChangeOwnershipReturnType>\n\n /**\n * Mutates the entities with the given keys.\n *\n * - Docs: https://docs.arkiv.network/ts-sdk/actions/wallet/mutateEntities\n * - JSON-RPC Methods: [`eth_sendRawTransaction`](https://docs.arkiv.network/dev/json-rpc-api/#mutateEntities)\n *\n * @param data - The mutation parameters (creates, updates, deletes, extensions)\n * @param txParams - Optional transaction parameters\n * @returns The mutation result with transaction hash\n *\n * @throws {InvalidExpirationError} If any create/update/extension `expiresIn`\n * is not a positive integer that is a multiple of the block time (2 seconds).\n * @throws {InvalidAttributeError} If a numeric attribute value is not an\n * integer.\n *\n * @example\n * import { createWalletClient, http } from 'arkiv'\n * import { braga } from 'arkiv/chains'\n *\n * const client = createWalletClient({\n * chain: braga,\n * transport: http(),\n * })\n * const { entityKey, txHash } = await client.mutateEntities({\n * creates: [{\n * payload: toBytes(JSON.stringify({ entity: { entityType: \"testType\", entityId: \"testId\" } })),\n * attriubutes: [{ key: \"testKey\", value: \"testValue\" }],\n * expiresIn: 1000,\n * }],\n * updates: [{\n * entityKey: \"0x123\",\n * payload: toBytes(JSON.stringify({ entity: { entityType: \"testType\", entityId: \"testId\" } })),\n * attributes: [{ key: \"testKey\", value: \"testValue\" }],\n * expiresIn: 1000,\n * }],\n * deletes: [{\n * entityKey: \"0x321\",\n * }],\n * extensions: [{\n * entityKey: \"0x1234\",\n * expiresIn: 1000,\n * }],\n * })\n * console.log(\"entityKey\", entityKey)\n * console.log(\"txHash\", txHash)\n * // {\n * // entityKey: \"0x123\",\n * // txHash: \"0x123\",\n * // }\n */\n mutateEntities: (\n data: MutateEntitiesParameters,\n txParams?: TxParams,\n ) => Promise<MutateEntitiesReturnType>\n }\n\nexport function walletArkivActions<\n transport extends Transport = Transport,\n chain extends Chain | undefined = Chain | undefined,\n account extends Account | undefined = Account | undefined,\n>(client: Client<transport, chain, account>) {\n return {\n createEntity: (data: CreateEntityParameters, txParams?: TxParams) =>\n createEntity(client, data, txParams),\n updateEntity: (data: UpdateEntityParameters, txParams?: TxParams) =>\n updateEntity(client, data, txParams),\n deleteEntity: (data: DeleteEntityParameters, txParams?: TxParams) =>\n deleteEntity(client, data, txParams),\n extendEntity: (data: ExtendEntityParameters, txParams?: TxParams) =>\n extendEntity(client, data, txParams),\n changeOwnership: (data: ChangeOwnershipParameters, txParams?: TxParams) =>\n changeOwnership(client, data, txParams),\n mutateEntities: (data: MutateEntitiesParameters, txParams?: TxParams) =>\n mutateEntities(client, data, txParams),\n }\n}\n","import type {\n Account,\n Address,\n Chain,\n Client,\n ParseAccount,\n Prettify,\n RpcSchema,\n Transport,\n WalletClientConfig,\n} from \"viem\"\nimport { createClient, publicActions, walletActions } from \"viem\"\nimport type { ArkivRpcSchema } from \"../types/rpcSchema\"\nimport { type WalletArkivActions, walletArkivActions } from \"./decorators/arkivWallet\"\n\nexport type WalletArkivClient<\n transport extends Transport = Transport,\n chain extends Chain | undefined = Chain | undefined,\n account extends Account | undefined = Account | undefined,\n rpcSchema extends RpcSchema | undefined = ArkivRpcSchema,\n> = Prettify<\n Client<transport, chain, account, rpcSchema, WalletArkivActions<transport, chain, account>>\n>\n\n/**\n * Creates a Public Client with a given [Transport](https://viem.sh/docs/clients/intro) configured for a [Chain](https://viem.sh/docs/clients/chains).\n *\n * - Docs: https://docs.arkiv.network/ts-sdk/clients/public\n *\n * A Public Client is an interface to \"public\" [Ethereum JSON-RPC API](https://ethereum.org/en/developers/docs/apis/json-rpc/), [Arkiv JSON-RPC API](https://docs.arkiv.network/json-rpc/), and [Braga JSON-RPC API](https://braga.holesky.arkiv.network/rpc) methods such as retrieving block numbers, transactions, reading from smart contracts, etc through [Public Actions](/docs/actions/public/introduction).\n *\n * @param parameters - Configuration object for the wallet client (chain, transport, account, etc.)\n * @returns A Arkiv Wallet Client. {@link WalletArkivClient}\n *\n * @example\n * import { createPublicClient, http } from 'arkiv'\n * import { braga } from 'arkiv/chains'\n *\n * const client = createPublicClient({\n * chain: braga,\n * transport: http(),\n * })\n */\nexport function createWalletClient<\n transport extends Transport,\n chain extends Chain | undefined = undefined,\n accountOrAddress extends Account | Address | undefined = undefined,\n rpcSchema extends RpcSchema | undefined = ArkivRpcSchema,\n>(\n parameters: WalletClientConfig<transport, chain, accountOrAddress, rpcSchema>,\n): WalletArkivClient<transport, chain, ParseAccount<accountOrAddress>, rpcSchema> {\n const { key = \"wallet\", name = \"Wallet Client\" } = parameters\n const client = createClient({\n ...parameters,\n key,\n name,\n })\n\n return client\n .extend(publicActions)\n .extend(walletActions)\n .extend(walletArkivActions) as unknown as WalletArkivClient<\n transport,\n chain,\n ParseAccount<accountOrAddress>,\n rpcSchema\n >\n}\n","import type { Chain } from \"viem\"\nimport * as chains from \"../chains\"\n\n// Create a lookup map from all exported chains\nconst chainMap = new Map(Object.entries(chains).map(([key, value]) => [key.toLowerCase(), value]))\n\n/**\n * Get a chain from its name\n * @param name - The name of the chain, case insensitive\n * @returns The chain\n * @throws An error if the chain is not found\n */\nexport function chainFromName(name: string): Chain {\n const chain = chainMap.get(name.toLowerCase())\n if (!chain) {\n throw new Error(`Unknown chain: ${name}`)\n }\n return chain as Chain\n}\n"],"mappings":";;;;;;;;AAGA,MAAMA,WAAS,UAAU,kCAAkC;AAQ3D,eAAsB,eAAe,QAAqB;CACxD,MAAM,cAAc,MAAM,OAAO,QAAQ;EACvC,QAAQ;EACR,QAAQ,EAAE;EACX,CAAC;AACF,UAAO,mBAAmB,YAAY;AACtC,QAAO;EACL,cAAc,OAAO,YAAY,cAAc;EAC/C,kBAAkB,YAAY;EAC9B,eAAe,YAAY;EAC5B;;;;;AChBH,eAAsB,UAAU,QAAqB,KAAU;CAE7D,IAAIC;AACJ,KAAI;AACF,UAAQ,WAAW,IAAI;SACjB;AACN,QAAM,IAAI,MAAM,uBAAuB,IAAI,mCAAmC;;AAGhF,KAAI,MAAM,WAAW,GACnB,OAAM,IAAI,MACR,uBAAuB,MAAM,OAAO,wDACrC;CAGH,MAAM,SAAS,WAAW,MAAM;CAEhC,MAAM,SAAS,MAAM,OAAO,QAAQ;EAClC,QAAQ;EACR,QAAQ,CACN,UAAU,UACV,EACE,aAAa;GACX,KAAK;GACL,YAAY;GACZ,SAAS;GACT,aAAa;GACb,YAAY;GACZ,OAAO;GACP,SAAS;GACT,gBAAgB;GAChB,qBAAqB;GACrB,yBAAyB;GACzB,6BAA6B;GAC9B,EACF,CACF;EACF,CAAC;AAEF,KAAI,CAAC,OAAO,KAAK,OACf,OAAM,IAAI,oBAAoB;AAGhC,QAAO,MAAM,oBAAoB,OAAO,KAAK,GAAG;;;;;AC9ClD,eAAsB,eAAe,QAAqB;AAMxD,QALc,MAAM,OAAO,QAAQ;EACjC,QAAQ;EACR,QAAQ,EAAE;EACX,CAAC;;;;;ACyBJ,eAAsB,MAAM,QAAqB,SAAe,cAA6B;CAC3F,MAAMC,kBAAmC;EACvC,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,QAAQ,MAAM,SAAS;EACtC,eAAe,MAA8B,aAC3C,aAAa,QAAQ,MAAM,SAAS;EACtC,eAAe,MAA8B,aAC3C,aAAa,QAAQ,MAAM,SAAS;EACtC,kBAAkB,MAAiC,aACjD,gBAAgB,QAAQ,MAAM,SAAS;EACzC,iBAAiB,MAAgC,aAC/C,eAAe,QAAQ,MAAM,SAAS;EACzC;;;;;;;;;;;;;;;;;;;;;;;;ACtOH,SAAgB,mBAMd,YACgF;CAChF,MAAM,EAAE,MAAM,UAAU,OAAO,oBAAoB;AAOnD,QANe,aAAa;EAC1B,GAAG;EACH;EACA;EACD,CAAC,CAGC,OAAO,cAAc,CACrB,OAAO,cAAc,CACrB,OAAO,mBAAmB;;;;;ACzD/B,MAAM,WAAW,IAAI,IAAI,OAAO,QAAQC,eAAO,CAAC,KAAK,CAAC,KAAK,WAAW,CAAC,IAAI,aAAa,EAAE,MAAM,CAAC,CAAC;;;;;;;AAQlG,SAAgB,cAAc,MAAqB;CACjD,MAAM,QAAQ,SAAS,IAAI,KAAK,aAAa,CAAC;AAC9C,KAAI,CAAC,MACH,OAAM,IAAI,MAAM,kBAAkB,OAAO;AAE3C,QAAO"}
|
|
1
|
+
{"version":3,"file":"index.js","names":["logger","bytes: Uint8Array","rpcQueryOptions: RpcQueryOptions","query","logger","logger","zlib: typeof import(\"zlib\") | null","brotli: BrotliWasmType | null","logger","logger","logger","logger","logger","logger","createdEntities: Hex[]","updatedEntities: Hex[]","deletedEntities: Hex[]","extendedEntities: Hex[]","ownershipChanges: Hex[]","chains"],"sources":["../src/actions/public/getBlockTiming.ts","../src/actions/public/getEntity.ts","../src/actions/public/getEntityCount.ts","../src/actions/public/query.ts","../src/actions/public/subscribeEntityEvents.ts","../src/clients/decorators/arkivPublic.ts","../src/clients/createPublicClient.ts","../src/utils/compression.ts","../src/utils/validation.ts","../src/utils/arkivTransactions.ts","../src/actions/wallet/changeOwnership.ts","../src/actions/wallet/createEntity.ts","../src/actions/wallet/deleteEntity.ts","../src/actions/wallet/extendEntity.ts","../src/actions/wallet/mutateEntities.ts","../src/actions/wallet/updateEntity.ts","../src/clients/decorators/arkivWallet.ts","../src/clients/createWalletClient.ts","../src/utils/chains.ts"],"sourcesContent":["import type { ArkivClient } from \"../../clients/baseClient\"\nimport { getLogger } from \"../../utils/logger\"\n\nconst logger = getLogger(\"actions:public:get-block-timing\")\n\nexport type GetBlockTimingReturnType = {\n currentBlock: bigint\n currentBlockTime: number\n blockDuration: number\n}\n\nexport async function getBlockTiming(client: ArkivClient) {\n const blockTiming = await client.request({\n method: \"arkiv_getBlockTiming\",\n params: [],\n })\n logger(\"Block timing %o\", blockTiming)\n return {\n currentBlock: BigInt(blockTiming.current_block),\n currentBlockTime: blockTiming.current_block_time,\n blockDuration: blockTiming.duration,\n }\n}\n","import { bytesToHex, type Hex, hexToBytes } from \"viem\"\nimport type { ArkivClient } from \"../../clients/baseClient\"\nimport { NoEntityFoundError } from \"../../errors\"\nimport { entityFromRpcResult } from \"../../utils/entities\"\n\nexport async function getEntity(client: ArkivClient, key: Hex) {\n // Normalize the key into bytes\n let bytes: Uint8Array\n try {\n bytes = hexToBytes(key)\n } catch {\n throw new Error(`Invalid key format: ${key}. Key must be a valid hex string.`)\n }\n\n if (bytes.length !== 32) {\n throw new Error(\n `Invalid key length: ${bytes.length} bytes. Key must be 32 bytes (64 hex characters) long.`,\n )\n }\n\n const hexKey = bytesToHex(bytes)\n\n const result = await client.request({\n method: \"arkiv_query\",\n params: [\n `$key = ${hexKey}`,\n {\n includeData: {\n key: true,\n attributes: true,\n payload: true,\n contentType: true,\n expiration: true,\n owner: true,\n creator: true,\n createdAtBlock: true,\n lastModifiedAtBlock: true,\n transactionIndexInBlock: true,\n operationIndexInTransaction: true,\n },\n },\n ],\n })\n\n if (!result.data.length) {\n throw new NoEntityFoundError()\n }\n\n return await entityFromRpcResult(result.data[0])\n}\n","import type { ArkivClient } from \"../../clients/baseClient\"\n\nexport async function getEntityCount(client: ArkivClient) {\n const count = await client.request({\n method: \"arkiv_getEntityCount\",\n params: [],\n })\n\n return count\n}\n","import { numberToHex } from \"viem\"\nimport type { ArkivClient } from \"../../clients/baseClient\"\nimport type { Entity } from \"../../types/entity\"\nimport type { RpcQueryOptions } from \"../../types/rpcSchema\"\nimport { entityFromRpcResult } from \"../../utils/entities\"\n\nexport type QueryOptionsIncludeData = {\n attributes?: boolean\n payload?: boolean\n metadata?: boolean\n}\n/**\n * @deprecated Server-side ordering is not supported by the network. Sort the fetched\n * entities in JavaScript instead (e.g. `entities.sort(...)`). This type will be removed\n * in a future release.\n */\nexport type QueryOptionsOrderBy = {\n name: string\n type: \"string\" | \"numeric\"\n desc: \"asc\" | \"desc\"\n}\n\nexport type QueryOptions = {\n includeData?: QueryOptionsIncludeData\n atBlock?: bigint\n /**\n * @deprecated Server-side ordering is not supported by the network, so this option has no\n * effect on the returned order. Sort the fetched entities in JavaScript instead\n * (e.g. `entities.sort(...)`). This option will be removed in a future release.\n */\n orderBy?: QueryOptionsOrderBy[]\n resultsPerPage?: number | undefined\n cursor?: string | undefined\n}\n\nexport type QueryReturnType = {\n entities: Entity[]\n cursor: string | undefined\n blockNumber: bigint | undefined\n}\n\nexport async function query(client: ArkivClient, query: string, queryOptions?: QueryOptions) {\n const rpcQueryOptions: RpcQueryOptions = {\n includeData: {\n key: true,\n payload: queryOptions?.includeData?.payload ?? true,\n attributes: queryOptions?.includeData?.attributes ?? false,\n contentType: queryOptions?.includeData?.metadata ?? false,\n expiration: queryOptions?.includeData?.metadata ?? false,\n owner: queryOptions?.includeData?.metadata ?? false,\n creator: queryOptions?.includeData?.metadata ?? false,\n createdAtBlock: queryOptions?.includeData?.metadata ?? false,\n lastModifiedAtBlock: queryOptions?.includeData?.metadata ?? false,\n transactionIndexInBlock: queryOptions?.includeData?.metadata ?? false,\n operationIndexInTransaction: queryOptions?.includeData?.metadata ?? false,\n },\n ...(queryOptions?.atBlock !== undefined && { atBlock: numberToHex(queryOptions.atBlock) }),\n ...(queryOptions?.orderBy && {\n orderBy: queryOptions?.orderBy.map((order) => ({\n name: order.name,\n type: order.type,\n desc: order.desc === \"desc\",\n })),\n }),\n ...(queryOptions?.resultsPerPage !== undefined && {\n resultsPerPage: numberToHex(queryOptions.resultsPerPage),\n }),\n ...(queryOptions?.cursor !== undefined && { cursor: queryOptions?.cursor }),\n }\n\n const result = await client.request({\n method: \"arkiv_query\",\n params: [query, rpcQueryOptions],\n })\n\n const entities = await Promise.all(result.data.map((entity) => entityFromRpcResult(entity)))\n\n return {\n entities,\n cursor: result.cursor,\n blockNumber: BigInt(result.blockNumber),\n }\n}\n","import { decodeEventLog, type Hex, parseAbi, toHex } from \"viem\"\nimport type { ArkivClient } from \"../../clients/baseClient\"\nimport type { PublicArkivClient } from \"../../clients/createPublicClient\"\nimport type {\n OnEntityCreatedEvent,\n OnEntityDeletedEvent,\n OnEntityExpiredEvent,\n OnEntityExpiresInExtendedEvent,\n OnEntityOwnerChangedEvent,\n OnEntityUpdatedEvent,\n} from \"../../types/events\"\nimport { getLogger } from \"../../utils/logger\"\n\nconst logger = getLogger(\"actions:public:subscribe-entity-events\")\n\nexport const arkivABI = parseAbi([\n \"event ArkivEntityCreated(uint256 indexed entityKey, address indexed ownerAddress, uint256 expirationBlock, uint256 cost)\",\n \"event ArkivEntityUpdated(uint256 indexed entityKey, address indexed ownerAddress, uint256 oldExpirationBlock, uint256 newExpirationBlock, uint256 cost)\",\n \"event ArkivEntityExpired(uint256 indexed entityKey, address indexed ownerAddress)\",\n \"event ArkivEntityDeleted(uint256 indexed entityKey, address indexed ownerAddress)\",\n \"event ArkivEntityBTLExtended(uint256 indexed entityKey, address indexed ownerAddress, uint256 oldExpirationBlock, uint256 newExpirationBlock, uint256 cost)\",\n \"event ArkivEntityOwnerChanged(uint256 indexed entityKey, address indexed oldOwnerAddress, address indexed newOwnerAddress)\",\n])\n\nexport async function subscribeEntityEvents(\n client: ArkivClient,\n {\n onError,\n onEntityCreated,\n onEntityUpdated,\n onEntityDeleted,\n onEntityExpired,\n onEntityExpiresInExtended,\n onEntityOwnerChanged,\n }: {\n onError: ((error: Error) => void) | undefined\n onEntityCreated?: ((event: OnEntityCreatedEvent) => void) | undefined\n onEntityUpdated?: ((event: OnEntityUpdatedEvent) => void) | undefined\n onEntityDeleted?: ((event: OnEntityDeletedEvent) => void) | undefined\n onEntityExpired?: ((event: OnEntityExpiredEvent) => void) | undefined\n onEntityExpiresInExtended?: ((event: OnEntityExpiresInExtendedEvent) => void) | undefined\n onEntityOwnerChanged?: ((event: OnEntityOwnerChangedEvent) => void) | undefined\n },\n pollingInterval?: number,\n fromBlock?: bigint,\n): Promise<() => void> {\n const unsubscribe = (client as PublicArkivClient).watchEvent({\n pollingInterval: pollingInterval ?? 1000,\n fromBlock,\n events: arkivABI,\n onLogs: (logs) => {\n logger(\"logs from subscribeEntityEvents %o\", logs)\n for (const log of logs) {\n const event = decodeEventLog({\n abi: arkivABI,\n topics: log.topics as [Hex, ...Hex[]] | [],\n data: log.data,\n })\n logger(\"event from subscribeEntityEvents %o\", event)\n switch (event.eventName) {\n case \"ArkivEntityCreated\":\n onEntityCreated?.({\n entityKey: toHex(event.args.entityKey, { size: 32 }),\n owner: event.args.ownerAddress,\n expirationBlock: Number(event.args.expirationBlock),\n cost: event.args.cost,\n })\n break\n case \"ArkivEntityUpdated\":\n onEntityUpdated?.({\n entityKey: toHex(event.args.entityKey, { size: 32 }),\n owner: event.args.ownerAddress,\n oldExpirationBlock: Number(event.args.oldExpirationBlock),\n newExpirationBlock: Number(event.args.newExpirationBlock),\n cost: event.args.cost,\n })\n break\n case \"ArkivEntityDeleted\":\n onEntityDeleted?.({\n entityKey: toHex(event.args.entityKey, { size: 32 }),\n owner: event.args.ownerAddress,\n })\n break\n case \"ArkivEntityBTLExtended\":\n onEntityExpiresInExtended?.({\n entityKey: toHex(event.args.entityKey, { size: 32 }),\n owner: event.args.ownerAddress,\n oldExpirationBlock: Number(event.args.oldExpirationBlock),\n newExpirationBlock: Number(event.args.newExpirationBlock),\n cost: event.args.cost,\n })\n break\n case \"ArkivEntityExpired\":\n onEntityExpired?.({\n entityKey: toHex(event.args.entityKey, { size: 32 }),\n owner: event.args.ownerAddress,\n })\n break\n case \"ArkivEntityOwnerChanged\":\n onEntityOwnerChanged?.({\n entityKey: toHex(event.args.entityKey, { size: 32 }),\n oldOwner: event.args.oldOwnerAddress,\n newOwner: event.args.newOwnerAddress,\n })\n break\n default:\n console.warn(\"unknown event from subscribeEntityEvents\", event)\n break\n }\n }\n },\n onError: (error) => {\n console.error(\"error from subscribeEntityEvents\", error)\n onError?.(error)\n },\n })\n\n return unsubscribe\n}\n","import type { Account, Chain, Client, Hex, PublicActions, Transport } from \"viem\"\nimport { getBlockTiming } from \"../../actions/public/getBlockTiming\"\nimport { getEntity } from \"../../actions/public/getEntity\"\nimport { getEntityCount } from \"../../actions/public/getEntityCount\"\nimport { type QueryOptions, type QueryReturnType, query } from \"../../actions/public/query\"\nimport { subscribeEntityEvents } from \"../../actions/public/subscribeEntityEvents\"\nimport { QueryBuilder, SelectQueryBuilder } from \"../../query/queryBuilder\"\nimport type { EntitySelection, FullEntity, ProjectedEntity, SelectArg } from \"../../query/selection\"\nimport type { Entity } from \"../../types/entity\"\nimport type {\n OnEntityCreatedEvent,\n OnEntityDeletedEvent,\n OnEntityExpiredEvent,\n OnEntityExpiresInExtendedEvent,\n OnEntityUpdatedEvent,\n} from \"../../types/events\"\n\nexport type PublicArkivActions<\n transport extends Transport = Transport,\n chain extends Chain | undefined = Chain | undefined,\n account extends Account | undefined = Account | undefined,\n> = Pick<\n PublicActions<transport, chain, account>,\n | \"getBalance\"\n | \"getBlock\"\n | \"getBlockNumber\"\n | \"getChainId\"\n | \"getLogs\"\n | \"getTransaction\"\n | \"getTransactionCount\"\n | \"getTransactionReceipt\"\n | \"waitForTransactionReceipt\"\n | \"watchEvent\"\n> & {\n /**\n * Returns the entity with the given key.\n *\n * - Docs: https://docs.arkiv.network/ts-sdk/actions/public/getEntity\n *\n * @param key - The entity key (hex string)\n * @returns The entity with the given key. {@link Entity}\n *\n * @example\n * import { createPublicClient, http } from 'arkiv'\n * import { braga } from 'arkiv/chains'\n *\n * const client = createPublicClient({\n * chain: braga,\n * transport: http(),\n * })\n * const entity = await client.getEntity(\"0x123\")\n * // {\n * // key: \"0x123\",\n * // value: \"0x123\",\n * // }\n */\n getEntity: (key: Hex) => Promise<Entity>\n\n /**\n * Returns a SelectQueryBuilder for building and executing queries — the recommended way to\n * read entities. You declare up front which parts of an entity you want returned, so results\n * always contain exactly the data you asked for.\n *\n * - Docs: https://docs.arkiv.network/ts-sdk/actions/public/query\n *\n * @param selection - What to include in the results. Omit it (or pass `\"*\"`) to select everything,\n * or pass an object to select specific parts (at least one field is required). Every part is\n * opt-in, including the `key`. The selection is flat — each field maps to an entity field.\n * {@link SelectArg}\n * @returns A SelectQueryBuilder instance for building and executing queries. {@link SelectQueryBuilder}\n *\n * @example\n * import { createPublicClient, http } from 'arkiv'\n * import { braga } from 'arkiv/chains'\n * import { eq } from 'arkiv/query'\n *\n * const client = createPublicClient({\n * chain: braga,\n * transport: http(),\n * })\n * // select everything\n * await client.select().where(eq(\"category\", \"docs\")).fetch()\n * await client.select(\"*\").where(eq(\"category\", \"docs\")).fetch()\n * // only the key\n * await client.select({ key: true }).where(eq(\"category\", \"docs\")).fetch()\n * // select specific fields — result typed { owner: Hex; attributes: Attribute[] }\n * await client.select({ owner: true, attributes: true }).fetch()\n * // a single field — result typed { owner: Hex }\n * await client.select({ owner: true }).fetch()\n */\n select: {\n /** Select every field. Pass nothing or `\"*\"`; the returned entities contain all fields. */\n (selection?: \"*\"): SelectQueryBuilder<FullEntity>\n /**\n * Pick the entity fields to return. Set the ones you want to `true` (at least one is required);\n * the result is typed to exactly those fields, so reading anything else is a compile error.\n *\n * Available fields: `key`, `owner`, `creator`, `contentType`, `payload`, `attributes`,\n * `expiresAtBlock`, `createdAtBlock`, `lastModifiedAtBlock`, `transactionIndexInBlock`,\n * `operationIndexInTransaction`.\n *\n * Pass the selection inline so its fields stay literal `true`. A selection stored in a `let`/\n * `const` variable widens to `boolean` and the result type can no longer be narrowed — annotate\n * it `as const` (e.g. `const sel = { owner: true } as const`) in that case.\n *\n * @example\n * client.select({ owner: true, attributes: true }) // entities typed { owner, attributes }\n * client.select({ key: true, payload: true }) // includes payload → toText()/toJson() too\n */\n <const S extends EntitySelection>(selection: S): SelectQueryBuilder<ProjectedEntity<S>>\n /**\n * Dynamic selection: accepts a value typed {@link SelectArg} (e.g. built at runtime). The\n * result cannot be narrowed in this case, so the entities are typed as the full entity.\n */\n (selection: SelectArg): SelectQueryBuilder<FullEntity>\n }\n\n /**\n * Returns a QueryBuilder instance for building and executing queries.\n * The QueryBuilder object follows the Builder pattern, allowing you to chain methods to build a query and then execute it.\n *\n * - Docs: https://docs.arkiv.network/ts-sdk/actions/public/query\n *\n * @deprecated Use {@link select} instead. `buildQuery()` returns only the entity `key` unless\n * you remember to opt in to data with `withAttributes()`/`withMetadata()`/`withPayload()`, which\n * is an easy mistake. `select()` makes the selection explicit. This method remains for backwards\n * compatibility and will be removed in a future release.\n *\n * @returns A QueryBuilder instance for building and executing queries. {@link QueryBuilder}\n *\n * @example\n * import { createPublicClient, http } from 'arkiv'\n * import { braga } from 'arkiv/chains'\n *\n * const client = createPublicClient({\n * chain: braga,\n * transport: http(),\n * })\n * const query = client.buildQuery()\n * const entities = await query.where(\"key\", \"=\", \"value\").ownedBy(\"0x123\").fetch()\n *\n */\n buildQuery: () => QueryBuilder\n\n /**\n * Returns a QueryResult instance for fetching the results of a raw query.\n * If no query options are provided, all payload is included, but no metadata (like owner, expiredAt, etc.) and attributes.\n * @param query - The raw query string\n * @param queryOptions - The optional query options - {@link QueryOptions}\n * @returns A QueryReturnType instance - {@link QueryReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'arkiv'\n * import { braga } from 'arkiv/chains'\n *\n * const client = createPublicClient({\n * chain: braga,\n * transport: http(),\n * })\n * const queryResult = client.query('key = value && $owner = 0x123')\n * // queryResult = { entities: [{ key: \"0x123\", value: \"0x123\" }], cursor: undefined, blockNumber: undefined }\n * const queryResultWithOptions = client.query('key = value && $owner = 0x123', {\n * includeData: {\n * attributes: false,\n * payload: true,\n * metadata: true,\n * },\n * resultsPerPage: 10,\n * cursor: undefined,\n * atBlock: undefined,\n * })\n * // queryResultWithOptions = { entities: [{ key: \"0x123\", value: \"0x123\" }], cursor: \"...\", blockNumber: 32223n }\n */\n query: (query: string, queryOptions?: QueryOptions) => Promise<QueryReturnType>\n\n /**\n * Returns the number of entities in the DBChain.\n * @returns The number of entities in the DBChain\n *\n * @example\n * import { createPublicClient, http } from 'arkiv'\n * import { braga } from 'arkiv/chains'\n *\n * const client = createPublicClient({\n * chain: braga,\n * transport: http(),\n * })\n * const entityCount = await client.getEntityCount()\n * // entityCount = 0\n */\n getEntityCount: () => Promise<number>\n\n /**\n * Returns the current block timing.\n * @returns The current block timing. {@link GetBlockTimingReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'arkiv'\n * import { braga } from 'arkiv/chains'\n *\n * const client = createPublicClient({\n * chain: braga,\n * transport: http(),\n * })\n * const blockTiming = await client.getBlockTiming()\n * // {\n * // currentBlock: 10n, // block number\n * // currentBlockTime: 1234567890, // block timestamp\n * // blockDuration: 2, // in seconds\n * // }\n */\n getBlockTiming: () => Promise<{\n currentBlock: bigint\n currentBlockTime: number\n blockDuration: number\n }>\n\n /**\n * Subscribes to entity events.\n * Takes an object with event handlers: {onError, onEntityCreated, onEntityUpdated, onEntityDeleted, onEntityExpiresInExtended}\n * @param pollingInterval - The polling interval in milliseconds\n * @param fromBlock - The block number to start from\n * @returns A function to unsubscribe from the events\n *\n * @example\n * import { createPublicClient, http } from 'arkiv'\n * import { braga } from 'arkiv/chains'\n *\n * const client = createPublicClient({\n * chain: braga,\n * transport: http(),\n * })\n * const unsubscribe = await client.subscribeEntityEvents({\n * onError: (error) => console.error(\"subscribeEntityEvents error\", error),\n * })\n * unsubscribe() // unsubscribe from the events\n */\n subscribeEntityEvents: (\n {\n onError,\n onEntityCreated,\n onEntityUpdated,\n onEntityDeleted,\n onEntityExpiresInExtended,\n }: {\n onError?: (error: Error) => void\n onEntityCreated?: (event: OnEntityCreatedEvent) => void\n onEntityUpdated?: (event: OnEntityUpdatedEvent) => void\n onEntityDeleted?: (event: OnEntityDeletedEvent) => void\n onEntityExpired?: (event: OnEntityExpiredEvent) => void\n onEntityExpiresInExtended?: (event: OnEntityExpiresInExtendedEvent) => void\n },\n pollingInterval?: number,\n fromBlock?: bigint,\n ) => Promise<() => void>\n}\n\nexport function publicArkivActions<\n transport extends Transport = Transport,\n chain extends Chain | undefined = Chain | undefined,\n account extends Account | undefined = Account | undefined,\n>(client: Client<transport, chain, account>) {\n return {\n getEntity: (key: Hex) => getEntity(client, key),\n query: (rawQuery: string, queryOptions?: QueryOptions) => query(client, rawQuery, queryOptions),\n buildQuery: () => new QueryBuilder(client),\n select: (selection?: SelectArg) => new SelectQueryBuilder(client, selection),\n getBlockTiming: () => getBlockTiming(client),\n getEntityCount: () => getEntityCount(client),\n subscribeEntityEvents: (\n {\n onError,\n onEntityCreated,\n onEntityUpdated,\n onEntityDeleted,\n onEntityExpired,\n onEntityExpiresInExtended,\n }: {\n onError?: (error: Error) => void\n onEntityCreated?: (event: OnEntityCreatedEvent) => void\n onEntityUpdated?: (event: OnEntityUpdatedEvent) => void\n onEntityDeleted?: (event: OnEntityDeletedEvent) => void\n onEntityExpired?: (event: OnEntityExpiredEvent) => void\n onEntityExpiresInExtended?: (event: OnEntityExpiresInExtendedEvent) => void\n },\n pollingInterval?: number,\n fromBlock?: bigint,\n ) =>\n subscribeEntityEvents(\n client,\n {\n onError,\n onEntityCreated,\n onEntityUpdated,\n onEntityDeleted,\n onEntityExpired,\n onEntityExpiresInExtended,\n },\n pollingInterval,\n fromBlock,\n ),\n }\n}\n","import type {\n Account,\n Address,\n Chain,\n Client,\n ParseAccount,\n Prettify,\n PublicClientConfig,\n RpcSchema,\n Transport,\n} from \"viem\"\nimport { createClient, publicActions } from \"viem\"\nimport type { ArkivRpcSchema } from \"../types/rpcSchema\"\nimport { type PublicArkivActions, publicArkivActions } from \"./decorators/arkivPublic\"\n\nexport type PublicArkivClient<\n transport extends Transport = Transport,\n chain extends Chain | undefined = Chain | undefined,\n accountOrAddress extends Account | undefined = undefined,\n rpcSchema extends RpcSchema | undefined = ArkivRpcSchema,\n> = Prettify<\n Client<transport, chain, accountOrAddress, rpcSchema, PublicArkivActions<transport, chain>>\n>\n\n/**\n * Creates a Public Client with a given [Transport](https://viem.sh/docs/clients/intro) configured for a [Chain](https://viem.sh/docs/clients/chains).\n *\n * - Docs: https://docs.arkiv.network/ts-sdk/clients/public\n *\n * A Public Client is an interface to \"public\" [Ethereum JSON-RPC API](https://ethereum.org/en/developers/docs/apis/json-rpc/), [Arkiv JSON-RPC API](https://docs.arkiv.network/json-rpc/), and [Braga JSON-RPC API](https://braga.holesky.arkiv.network/rpc) methods such as retrieving block numbers, transactions, reading from smart contracts, etc through [Public Actions](/docs/actions/public/introduction).\n *\n * @param parameters - Configuration object for the public client (chain, transport, etc.)\n * @returns A Arkiv Public Client. {@link PublicArkivClient}\n *\n * @example\n * import { createPublicClient, http } from 'arkiv'\n * import { braga } from 'arkiv/chains'\n *\n * const client = createPublicClient({\n * chain: braga,\n * transport: http(),\n * })\n */\nexport function createPublicClient<\n transport extends Transport,\n chain extends Chain | undefined = undefined,\n accountOrAddress extends Account | Address | undefined = undefined,\n rpcSchema extends RpcSchema | undefined = ArkivRpcSchema,\n>(\n parameters: PublicClientConfig<transport, chain, accountOrAddress, rpcSchema>,\n): PublicArkivClient<transport, chain, ParseAccount<accountOrAddress>, rpcSchema> {\n const { key = \"public\", name = \"Public Client\" } = parameters\n const client = createClient({\n ...parameters,\n key,\n name,\n })\n\n return client.extend(publicActions).extend(publicArkivActions) as unknown as PublicArkivClient<\n transport,\n chain,\n ParseAccount<accountOrAddress>,\n rpcSchema\n >\n}\n","// src/utils/compression.ts\n\nimport type { BrotliWasmType } from \"brotli-wasm\"\nimport { getLogger } from \"./logger\"\n\nconst logger = getLogger(\"utils:compression\")\n\n// Detect if we're in Node.js environment\nconst isNode = typeof process !== \"undefined\" && process.versions?.node != null\n\nlet zlib: typeof import(\"zlib\") | null = null\nlet brotli: BrotliWasmType | null = null\n\n// Lazy load zlib (Node.js only)\nasync function getZlib(): Promise<typeof import(\"zlib\") | null> {\n if (!isNode) return null\n\n if (!zlib) {\n try {\n zlib = await import(\"zlib\")\n } catch (error) {\n console.error(\"Error importing zlib\", error)\n return null\n }\n }\n return zlib\n}\n\n// Lazy load brotli-wasm (browser/fallback)\nasync function getBrotli(): Promise<BrotliWasmType | null> {\n if (brotli) return brotli\n\n try {\n const brotliModule = await import(\"brotli-wasm\")\n brotli = (brotliModule.default ? await brotliModule.default : brotliModule) as BrotliWasmType\n } catch (error) {\n console.error(\"Error importing brotli-wasm\", error)\n return null\n }\n\n return brotli\n}\n\nexport async function compress(data: Uint8Array): Promise<Uint8Array> {\n logger(\"Compressing data size %d\", data.length)\n\n // Try Node.js zlib first (if available)\n if (isNode) {\n const zlibModule = await getZlib()\n if (zlibModule) {\n try {\n // zlib.brotliCompress expects Buffer, returns Buffer\n const buffer = Buffer.from(data)\n const compressed = zlibModule.brotliCompressSync(buffer)\n const result = new Uint8Array(compressed)\n logger(\"Brotli compressed with zlib size %d\", result.length)\n return result\n } catch (error) {\n console.warn(\"zlib compression failed, falling back to brotli-wasm\", error)\n }\n }\n }\n\n // Fallback to brotli-wasm (browser or if zlib fails)\n const brotliInstance = await getBrotli()\n if (!brotliInstance) {\n console.warn(\"Brotli instance not found, not compressing data\")\n return data\n }\n\n const brotliCompressed = brotliInstance.compress(data)\n logger(\"Brotli compressed with wasm size %d\", brotliCompressed.length)\n return brotliCompressed\n}\n\nexport async function decompress(data: Uint8Array): Promise<Uint8Array> {\n // Try Node.js zlib first (if available)\n if (isNode) {\n const zlibModule = await getZlib()\n if (zlibModule) {\n try {\n // zlib.brotliDecompress expects Buffer, returns Buffer\n const buffer = Buffer.from(data)\n const decompressed = zlibModule.brotliDecompressSync(buffer)\n const result = new Uint8Array(decompressed)\n logger(\"Brotli decompressed with zlib size %d\", result.length)\n return result\n } catch (error) {\n console.warn(\"zlib decompression failed, falling back to brotli-wasm\", error)\n }\n }\n }\n\n // Fallback to brotli-wasm (browser or if zlib fails)\n const brotliInstance = await getBrotli()\n if (!brotliInstance) {\n console.warn(\"Brotli instance not found, not decompressing data\")\n return data\n }\n\n return brotliInstance.decompress(data)\n}\n","import { BLOCK_TIME } from \"../consts\"\nimport { InvalidAttributeError, InvalidExpirationError } from \"../errors\"\nimport type { Attribute } from \"../types\"\n\n/**\n * Expiration on Arkiv is measured in blocks (1 block =\n * 2 seconds), so the value must be a positive integer that is\n * a multiple of the block time.\n *\n * @param expiresIn - The expiration in seconds.\n * @throws {InvalidExpirationError} If the value is not a positive integer that\n * is a multiple of the block time.\n */\nexport function validateExpiresIn(expiresIn: number): void {\n if (!Number.isInteger(expiresIn) || expiresIn <= 0 || expiresIn % BLOCK_TIME !== 0) {\n throw new InvalidExpirationError(expiresIn)\n }\n}\n\n/**\n * Validates a single attribute. Arkiv supports string and number attribute\n * values, but numeric values must be integers.\n *\n * @param attribute - The attribute to validate.\n * @throws {InvalidAttributeError} If the attribute has a non-integer numeric\n * value.\n */\nexport function validateAttribute(attribute: Attribute): void {\n if (typeof attribute.value === \"number\" && !Number.isInteger(attribute.value)) {\n throw new InvalidAttributeError(attribute.key, attribute.value)\n }\n}\n","import { type Hex, hexToString, TransactionExecutionError, toBytes, toHex, toRlp } from \"viem\"\nimport type { ChangeOwnershipParameters } from \"../actions/wallet/changeOwnership\"\nimport type { CreateEntityParameters } from \"../actions/wallet/createEntity\"\nimport type { DeleteEntityParameters } from \"../actions/wallet/deleteEntity\"\nimport type { ExtendEntityParameters } from \"../actions/wallet/extendEntity\"\nimport type { UpdateEntityParameters } from \"../actions/wallet/updateEntity\"\nimport type { ArkivClient } from \"../clients/baseClient\"\nimport type { WalletArkivClient } from \"../clients/createWalletClient\"\nimport { ARKIV_ADDRESS, BLOCK_TIME } from \"../consts\"\nimport { EntityMutationError } from \"../errors\"\nimport type { TxParams } from \"../types\"\nimport { compress } from \"./compression\"\nimport { getLogger } from \"./logger\"\nimport { validateAttribute, validateExpiresIn } from \"./validation\"\n\nconst logger = getLogger(\"utils:arkiv-transactions\")\n\nexport function opsToTxData({\n creates,\n updates,\n deletes,\n extensions,\n ownershipChanges,\n}: {\n creates?: CreateEntityParameters[]\n updates?: UpdateEntityParameters[]\n deletes?: DeleteEntityParameters[]\n extensions?: ExtendEntityParameters[]\n ownershipChanges?: ChangeOwnershipParameters[]\n}) {\n function formatAttributes<T extends string | number | bigint | boolean>(attribute: {\n key: string\n value: T\n }): [Hex, Hex] {\n return [\n toHex(attribute.key),\n toHex(typeof attribute.value === \"number\" && attribute.value === 0 ? \"\" : attribute.value),\n ]\n }\n\n const payload = [\n //creates\n (creates ?? []).map((item) => {\n validateExpiresIn(item.expiresIn)\n item.attributes.forEach(validateAttribute)\n return [\n toHex(item.expiresIn / BLOCK_TIME),\n toHex(item.contentType),\n toHex(item.payload),\n item.attributes\n .filter((attribute) => typeof attribute.value === \"string\")\n .map(formatAttributes),\n item.attributes\n .filter((attribute) => typeof attribute.value === \"number\")\n .map(formatAttributes),\n ]\n }),\n //updates\n (updates ?? []).map((item) => {\n validateExpiresIn(item.expiresIn)\n item.attributes.forEach(validateAttribute)\n return [\n item.entityKey,\n toHex(item.contentType),\n toHex(item.expiresIn / BLOCK_TIME),\n toHex(item.payload),\n item.attributes\n .filter((attribute) => typeof attribute.value === \"string\")\n .map(formatAttributes),\n item.attributes\n .filter((attribute) => typeof attribute.value === \"number\")\n .map(formatAttributes),\n ]\n }),\n //deletes\n (deletes ?? []).map((item) => item.entityKey),\n //extends\n (extensions ?? []).map((item) => {\n validateExpiresIn(item.expiresIn)\n return [item.entityKey, toHex(item.expiresIn / BLOCK_TIME)]\n }),\n //ownershipChanges TODO\n (ownershipChanges ?? []).map((item) => [item.entityKey, item.newOwner]),\n ]\n\n logger(\"txData to send as RLP %o length %d\", payload, payload.length)\n\n return toRlp(payload)\n}\n\nexport async function sendArkivTransaction(client: ArkivClient, data: Hex, txParams?: TxParams) {\n if (!client.account) throw new Error(\"Account required\")\n const walletClient = client as WalletArkivClient\n\n logger(\"Sending transaction %o\", {\n account: client.account,\n chain: client.chain,\n to: ARKIV_ADDRESS,\n value: 0n,\n data,\n ...txParams,\n })\n\n try {\n const compressed = await compress(toBytes(data))\n const txHash = await walletClient.sendTransaction({\n account: client.account,\n chain: client.chain,\n to: ARKIV_ADDRESS,\n value: 0n,\n data: toHex(compressed),\n ...txParams,\n })\n\n const receipt = await walletClient.waitForTransactionReceipt({ hash: txHash })\n logger(\"Tx receipt %o\", receipt)\n if (receipt.status === \"reverted\") {\n try {\n const callResult = await walletClient.call({\n account: client.account,\n to: ARKIV_ADDRESS,\n value: 0n,\n data: toHex(compressed),\n ...txParams,\n })\n throw new EntityMutationError(\n `Transaction ${receipt.transactionHash} reverted. Please make sure the data for entities doesn't contain invalid characters or invalid data types.\n Reason: ${callResult.data ? hexToString(callResult.data) : \"No reason provided by backend.\"}`,\n )\n } catch (err) {\n const error = err as { cause?: { details?: string } }\n const reason = error.cause?.details ?? \"No reason provided by backend.\"\n logger(\n \"Error while calling to get more details about reverted transaction. Reason: %s\",\n reason,\n )\n throw new EntityMutationError(\n `Transaction ${receipt.transactionHash} reverted. Reason: ${reason}`,\n )\n }\n }\n\n return receipt\n } catch (error) {\n let message = \"Transaction failed\"\n if (error instanceof TransactionExecutionError) {\n message += `: ${error.details}`\n } else if (error instanceof EntityMutationError) {\n throw error\n }\n\n logger(\"%s Detailed error stack: %o\", message, error)\n throw new EntityMutationError(message)\n }\n}\n","import type { Hex } from \"viem\"\nimport type { ArkivClient } from \"../../clients/baseClient\"\nimport type { TxParams } from \"../../types\"\nimport { opsToTxData, sendArkivTransaction } from \"../../utils/arkivTransactions\"\nimport { getLogger } from \"../../utils/logger\"\n\nconst logger = getLogger(\"actions:wallet:change-ownership\")\n\n/**\n * Parameters for the deleteEntity function.\n * - entityKey: The key of the entity to delete.\n */\nexport type ChangeOwnershipParameters = {\n entityKey: Hex\n newOwner: Hex\n}\n\n/**\n * Return type for the deleteEntity function.\n * - entityKey: The key of the entity.\n * - txHash: The transaction hash.\n */\nexport type ChangeOwnershipReturnType = {\n entityKey: Hex\n txHash: string\n}\n\nexport async function changeOwnership(\n client: ArkivClient,\n data: ChangeOwnershipParameters,\n txParams?: TxParams,\n): Promise<ChangeOwnershipReturnType> {\n logger(\"changeOwnership %o\", data)\n const txData = opsToTxData({ ownershipChanges: [data] })\n const receipt = await sendArkivTransaction(client, txData, txParams)\n\n logger(\"Receipt from changeOwnership %o\", receipt)\n\n return {\n txHash: receipt.transactionHash,\n entityKey: data.entityKey,\n }\n}\n","import type { Hash, Hex } from \"viem\"\nimport type { ArkivClient } from \"../../clients/baseClient\"\nimport type { Attribute, MimeType, TxParams } from \"../../types\"\nimport { opsToTxData, sendArkivTransaction } from \"../../utils/arkivTransactions\"\nimport { getLogger } from \"../../utils/logger\"\n\nconst logger = getLogger(\"actions:wallet:create-entity\")\n\n/**\n * Parameters for the createEntity function.\n * - payload: The payload of the entity.\n * - attributes: The attributes of the entity. Attribute values may be strings\n * or numbers, but numeric values **must be integers**. To store a non-integer,\n * scale it to an integer (e.g. `1.5` -> `1500`) to preserve numeric ordering,\n * or pass it as a string (e.g. `\"1.5\"`). A non-integer numeric value throws an\n * {@link InvalidAttributeError}.\n * - contentType: The content type of the entity.\n * - expiresIn: How long until the entity expires, in seconds. Because Arkiv\n * measures expiration in blocks (1 block = 2 seconds), this **must be a\n * positive integer and a multiple of the block time (2 seconds)**\n * Invalid values throw an {@link InvalidExpirationError}.\n */\nexport type CreateEntityParameters = {\n payload: Uint8Array\n /** Entity attributes. Numeric values must be integers (scale non-integers, e.g. `1.5` -> `1500`, or use a string). Throws {@link InvalidAttributeError} otherwise. */\n attributes: Attribute[]\n contentType: MimeType | string\n /** Seconds until expiry. Must be a positive integer and a multiple of the 2s block time.\n * Throws {@link InvalidExpirationError} otherwise. */\n expiresIn: number\n}\n\n/**\n * Return type for the createEntity function.\n * - entityKey: The key of the entity.\n * - txHash: The transaction hash.\n */\nexport type CreateEntityReturnType = {\n entityKey: Hex\n txHash: Hash\n}\n\nexport async function createEntity(\n client: ArkivClient,\n data: CreateEntityParameters,\n txParams?: TxParams,\n): Promise<CreateEntityReturnType> {\n logger(\"createEntity %o\", data)\n const txData = opsToTxData({ creates: [data] })\n const receipt = await sendArkivTransaction(client, txData, txParams)\n\n logger(\"Receipt from createEntity %o\", receipt)\n\n return {\n txHash: receipt.transactionHash as Hash,\n entityKey: receipt.logs[0].topics[1] as Hex,\n }\n}\n","import type { Hash, Hex } from \"viem\"\nimport type { ArkivClient } from \"../../clients/baseClient\"\nimport type { TxParams } from \"../../types\"\nimport { opsToTxData, sendArkivTransaction } from \"../../utils/arkivTransactions\"\nimport { getLogger } from \"../../utils/logger\"\n\nconst logger = getLogger(\"actions:wallet:delete-entity\")\n\n/**\n * Parameters for the deleteEntity function.\n * - entityKey: The key of the entity to delete.\n */\nexport type DeleteEntityParameters = {\n entityKey: Hex\n}\n\n/**\n * Return type for the deleteEntity function.\n * - entityKey: The key of the entity.\n * - txHash: The transaction hash.\n */\nexport type DeleteEntityReturnType = {\n entityKey: Hex\n txHash: Hash\n}\n\nexport async function deleteEntity(\n client: ArkivClient,\n data: DeleteEntityParameters,\n txParams?: TxParams,\n): Promise<DeleteEntityReturnType> {\n logger(\"deleteEntity %o\", data)\n const txData = opsToTxData({ deletes: [data] })\n const receipt = await sendArkivTransaction(client, txData, txParams)\n\n logger(\"Receipt from deleteEntity %o\", receipt)\n\n return {\n txHash: receipt.transactionHash as Hash,\n entityKey: data.entityKey,\n }\n}\n","import type { Hash, Hex } from \"viem\"\nimport type { ArkivClient } from \"../../clients/baseClient\"\nimport type { TxParams } from \"../../types\"\nimport { opsToTxData, sendArkivTransaction } from \"../../utils/arkivTransactions\"\nimport { getLogger } from \"../../utils/logger\"\n\nconst logger = getLogger(\"actions:wallet:extend-entity\")\n\n/**\n * Parameters for the extendEntity function.\n * - entityKey: The key of the entity to extend.\n * - expiresIn: How long to extend the entity by, in seconds. Because Arkiv\n * measures expiration in blocks (1 block = 2 seconds), this **must be a\n * positive integer and a multiple of the block time (2 seconds)**.\n * Invalid values throw an {@link InvalidExpirationError}.\n */\nexport type ExtendEntityParameters = {\n entityKey: Hex\n /** Seconds to extend by. Must be a positive integer and a multiple of the 2s block time.\n * Throws {@link InvalidExpirationError} otherwise. */\n expiresIn: number\n}\n\n/**\n * Return type for the extendEntity function.\n * - entityKey: The key of the entity.\n * - txHash: The transaction hash.\n */\nexport type ExtendEntityReturnType = {\n entityKey: Hex\n txHash: Hash\n}\n\nexport async function extendEntity(\n client: ArkivClient,\n data: ExtendEntityParameters,\n txParams?: TxParams,\n): Promise<ExtendEntityReturnType> {\n logger(\"extendEntity %o\", data)\n const txData = opsToTxData({ extensions: [data] })\n const receipt = await sendArkivTransaction(client, txData, txParams)\n\n logger(\"Receipt from extendEntity %o\", receipt)\n\n return {\n txHash: receipt.transactionHash as Hash,\n entityKey: receipt.logs[0].topics[1] as Hex,\n }\n}\n","import type { Hash, Hex, TransactionReceipt } from \"viem\"\nimport type { ArkivClient } from \"../../clients/baseClient\"\nimport type { TxParams } from \"../../types\"\nimport { opsToTxData, sendArkivTransaction } from \"../../utils/arkivTransactions\"\nimport { getLogger } from \"../../utils/logger\"\nimport type { ChangeOwnershipParameters } from \"./changeOwnership\"\n\nconst logger = getLogger(\"actions:wallet:mutate-entities\")\n\nimport type { CreateEntityParameters } from \"./createEntity\"\nimport type { DeleteEntityParameters } from \"./deleteEntity\"\nimport type { ExtendEntityParameters } from \"./extendEntity\"\nimport type { UpdateEntityParameters } from \"./updateEntity\"\n\n/**\n * Parameters for the mutateEntities function.\n * - creates: The creates to perform.\n * - updates: The updates to perform.\n * - deletes: The deletes to perform.\n * - extensions: The extensions to perform.\n */\nexport type MutateEntitiesParameters = {\n creates?: CreateEntityParameters[]\n updates?: UpdateEntityParameters[]\n deletes?: DeleteEntityParameters[]\n extensions?: ExtendEntityParameters[]\n ownershipChanges?: ChangeOwnershipParameters[]\n}\n\nfunction parseReceipt(receipt: TransactionReceipt, params: MutateEntitiesParameters) {\n const createdEntities: Hex[] = []\n const updatedEntities: Hex[] = []\n const deletedEntities: Hex[] = []\n const extendedEntities: Hex[] = []\n const ownershipChanges: Hex[] = []\n\n const totalCreates = params.creates?.length ?? 0\n const totalUpdates = params.updates?.length ?? 0\n const totalDeletes = params.deletes?.length ?? 0\n const totalExtensions = params.extensions?.length ?? 0\n\n // iterate over all logs and parse the event\n // logs go in the following order: creates, deleted, updates, extends, ownership changes\n for (let index = 0; index < receipt.logs.length; index++) {\n const log = receipt.logs[index]\n\n if (index < totalCreates) {\n createdEntities.push(log.topics[1] as Hex)\n } else if (index < totalCreates + totalDeletes) {\n deletedEntities.push(log.topics[1] as Hex)\n } else if (index < totalCreates + totalUpdates + totalDeletes) {\n updatedEntities.push(log.topics[1] as Hex)\n } else if (index < totalCreates + totalUpdates + totalDeletes + totalExtensions) {\n extendedEntities.push(log.topics[1] as Hex)\n } else {\n ownershipChanges.push(log.topics[1] as Hex)\n }\n }\n\n return { createdEntities, updatedEntities, deletedEntities, extendedEntities, ownershipChanges }\n}\n\n/**\n * Return type for the mutateEntities function.\n * - txHash: The transaction hash.\n * - createdEntities: The keys of the created entities.\n * - updatedEntities: The keys of the updated entities.\n * - deletedEntities: The keys of the deleted entities.\n * - extendedEntities: The keys of the extended entities.\n * - ownershipChanges: The keys of the ownership changes.\n */\nexport type MutateEntitiesReturnType = {\n txHash: Hash\n createdEntities: Hex[]\n updatedEntities: Hex[]\n deletedEntities: Hex[]\n extendedEntities: Hex[]\n ownershipChanges: Hex[]\n}\nexport async function mutateEntities(\n client: ArkivClient,\n data: MutateEntitiesParameters,\n txParams?: TxParams,\n): Promise<MutateEntitiesReturnType> {\n if (!data.creates && !data.updates && !data.deletes && !data.extensions) {\n throw new Error(\"No operations to perform\")\n }\n\n const txData = opsToTxData({\n creates: data.creates ?? [],\n updates: data.updates ?? [],\n deletes: data.deletes ?? [],\n extensions: data.extensions ?? [],\n ownershipChanges: data.ownershipChanges ?? [],\n })\n\n const receipt = await sendArkivTransaction(client, txData, txParams)\n\n logger(\"Receipt from mutateEntities %o\", receipt)\n\n const { createdEntities, updatedEntities, deletedEntities, extendedEntities, ownershipChanges } =\n parseReceipt(receipt, data)\n return {\n txHash: receipt.transactionHash as Hash,\n createdEntities,\n updatedEntities,\n deletedEntities,\n extendedEntities,\n ownershipChanges,\n }\n}\n","import type { Hash, Hex } from \"viem\"\nimport type { ArkivClient } from \"../../clients/baseClient\"\nimport type { Attribute, MimeType, TxParams } from \"../../types\"\nimport { opsToTxData, sendArkivTransaction } from \"../../utils/arkivTransactions\"\nimport { getLogger } from \"../../utils/logger\"\n\nconst logger = getLogger(\"actions:wallet:update-entity\")\n\n/**\n * Parameters for the updateEntity function.\n * - entityKey: The key of the entity to update.\n * - payload: The payload of the entity.\n * - attributes: The attributes of the entity. Attribute values may be strings\n * or numbers, but numeric values **must be integers**. To store a non-integer,\n * scale it to an integer (e.g. `1.5` -> `1500`) to preserve numeric ordering,\n * or pass it as a string (e.g. `\"1.5\"`). A non-integer numeric value throws an\n * {@link InvalidAttributeError}.\n * - contentType: The content type of the entity.\n * - expiresIn: How long until the entity expires, in seconds. Because Arkiv\n * measures expiration in blocks (1 block = 2 seconds), this **must be a\n * positive integer and a multiple of the block time (2 seconds)**.\n * Invalid values throw an {@link InvalidExpirationError}.\n */\nexport type UpdateEntityParameters = {\n entityKey: Hex\n payload: Uint8Array\n /** Entity attributes. Numeric values must be integers (scale non-integers, e.g. `1.5` -> `1500`, or use a string). Throws {@link InvalidAttributeError} otherwise. */\n attributes: Attribute[]\n contentType: MimeType | string\n /** Seconds until expiry. Must be a positive integer and a multiple of the 2s block time.\n * Throws {@link InvalidExpirationError} otherwise. */\n expiresIn: number\n}\n\n/**\n * Return type for the updateEntity function.\n * - entityKey: The key of the entity.\n * - txHash: The transaction hash.\n */\nexport type UpdateEntityReturnType = {\n entityKey: Hex\n txHash: Hash\n}\n\nexport async function updateEntity(\n client: ArkivClient,\n data: UpdateEntityParameters,\n txParams?: TxParams,\n): Promise<UpdateEntityReturnType> {\n logger(\"updateEntity %o\", data)\n const txData = opsToTxData({ updates: [data] })\n const receipt = await sendArkivTransaction(client, txData, txParams)\n\n logger(\"Receipt from updateEntity %o\", receipt)\n\n return {\n txHash: receipt.transactionHash as Hash,\n entityKey: receipt.logs[0].topics[1] as Hex,\n }\n}\n","import type { Account, Chain, Client, PublicActions, Transport, WalletActions } from \"viem\"\nimport type {\n ChangeOwnershipParameters,\n ChangeOwnershipReturnType,\n} from \"../../actions/wallet/changeOwnership\"\nimport { changeOwnership } from \"../../actions/wallet/changeOwnership\"\nimport {\n type CreateEntityParameters,\n type CreateEntityReturnType,\n createEntity,\n} from \"../../actions/wallet/createEntity\"\nimport type {\n DeleteEntityParameters,\n DeleteEntityReturnType,\n} from \"../../actions/wallet/deleteEntity\"\nimport { deleteEntity } from \"../../actions/wallet/deleteEntity\"\nimport type {\n ExtendEntityParameters,\n ExtendEntityReturnType,\n} from \"../../actions/wallet/extendEntity\"\nimport { extendEntity } from \"../../actions/wallet/extendEntity\"\nimport type {\n MutateEntitiesParameters,\n MutateEntitiesReturnType,\n} from \"../../actions/wallet/mutateEntities\"\nimport { mutateEntities } from \"../../actions/wallet/mutateEntities\"\nimport type {\n UpdateEntityParameters,\n UpdateEntityReturnType,\n} from \"../../actions/wallet/updateEntity\"\nimport { updateEntity } from \"../../actions/wallet/updateEntity\"\nimport type { TxParams } from \"../../types\"\n\nexport type WalletArkivActions<\n transport extends Transport = Transport,\n chain extends Chain | undefined = Chain | undefined,\n account extends Account | undefined = Account | undefined,\n> = Pick<PublicActions<transport, chain, account>, \"waitForTransactionReceipt\" | \"call\"> &\n Pick<\n WalletActions<chain, account>,\n | \"addChain\"\n | \"sendCalls\"\n | \"waitForCallsStatus\"\n | \"sendTransaction\"\n | \"sendRawTransaction\"\n | \"signMessage\"\n | \"signTransaction\"\n > & {\n /**\n * Creates a new entity.\n *\n * - Docs: https://docs.arkiv.network/ts-sdk/actions/wallet/createEntity\n * - JSON-RPC Methods: [`eth_sendRawTransaction`](https://docs.arkiv.network/dev/json-rpc-api/#mutateEntities)\n *\n * @param data - The entity creation parameters\n * @param txParams - Optional transaction parameters\n * @returns The created entity with transaction hash\n *\n * @throws {InvalidExpirationError} If `expiresIn` is not a positive integer\n * that is a multiple of the block time (2 seconds).\n * @throws {InvalidAttributeError} If a numeric attribute value is not an\n * integer.\n *\n * @example\n * import { createPublicClient, http } from 'arkiv'\n * import { braga } from 'arkiv/chains'\n *\n * const client = createPublicClient({\n * chain: braga,\n * transport: http(),\n * })\n * const { entityKey, txHash } = await client.createEntity({\n * payload: toBytes(JSON.stringify({ entity: { entityType: \"testType\", entityId: \"testId\" } })),\n * attributes: [{ key: \"testKey\", value: \"testValue\" }],\n * expiresIn: 1000,\n * })\n * console.log(\"entityKey\", entityKey)\n * console.log(\"txHash\", txHash)\n * // {\n * // entityKey: \"0x123\",\n * // txHash: \"0x123\",\n * // }\n */\n createEntity: (\n data: CreateEntityParameters,\n txParams?: TxParams,\n ) => Promise<CreateEntityReturnType>\n\n /**\n * Updates the entity with the given key.\n *\n * - Docs: https://docs.arkiv.network/ts-sdk/actions/wallet/updateEntity\n * - JSON-RPC Methods: [`eth_sendRawTransaction`](https://docs.arkiv.network/dev/json-rpc-api/#mutateEntities)\n *\n * @param data - The entity update parameters\n * @param txParams - Optional transaction parameters\n * @returns The updated entity with transaction hash\n *\n * @throws {InvalidExpirationError} If `expiresIn` is not a positive integer\n * that is a multiple of the block time (2 seconds).\n * @throws {InvalidAttributeError} If a numeric attribute value is not an\n * integer.\n *\n * @example\n * import { createWalletClient, http } from 'arkiv'\n * import { braga } from 'arkiv/chains'\n *\n * const client = createWalletClient({\n * chain: braga,\n * transport: http(),\n * })\n */\n updateEntity: (\n data: UpdateEntityParameters,\n txParams?: TxParams,\n ) => Promise<UpdateEntityReturnType>\n\n /**\n * Deletes the entity with the given key.\n *\n * - Docs: https://docs.arkiv.network/ts-sdk/actions/wallet/deleteEntity\n * - JSON-RPC Methods: [`eth_sendRawTransaction`](https://docs.arkiv.network/dev/json-rpc-api/#mutateEntities)\n *\n * @param data - The entity deletion parameters\n * @param txParams - Optional transaction parameters\n * @returns The deleted entity with transaction hash\n *\n * @example\n * import { createWalletClient, http } from 'arkiv'\n * import { braga } from 'arkiv/chains'\n *\n * const client = createWalletClient({\n * chain: braga,\n * transport: http(),\n * })\n * const { entityKey, txHash } = await client.deleteEntity({ entityKey: \"0x123\" })\n * console.log(\"entityKey\", entityKey)\n * console.log(\"txHash\", txHash)\n * // {\n * // entityKey: \"0x123\",\n * // txHash: \"0x123\",\n * // }\n */\n deleteEntity: (\n data: DeleteEntityParameters,\n txParams?: TxParams,\n ) => Promise<DeleteEntityReturnType>\n\n /**\n * Extends the entity with the given key.\n *\n * - Docs: https://docs.arkiv.network/ts-sdk/actions/wallet/extendEntity\n * - JSON-RPC Methods: [`eth_sendRawTransaction`](https://docs.arkiv.network/dev/json-rpc-api/#mutateEntities)\n *\n * @param data - The entity update parameters\n * @param txParams - Optional transaction parameters\n * @returns The updated entity with transaction hash\n *\n * @throws {InvalidExpirationError} If `expiresIn` is not a positive integer\n * that is a multiple of the block time (2 seconds).\n *\n * @example\n * import { createWalletClient, http } from 'arkiv'\n * import { braga } from 'arkiv/chains'\n *\n * const client = createWalletClient({\n * chain: braga,\n * transport: http(),\n * })\n * const { entityKey, txHash } = await client.extendEntity(\"0x123\", {\n * expiresIn: 1000,\n * })\n * console.log(\"entityKey\", entityKey)\n * console.log(\"txHash\", txHash)\n * // {\n * // entityKey: \"0x123\",\n * // txHash: \"0x123\",\n * // }\n */\n extendEntity: (\n data: ExtendEntityParameters,\n txParams?: TxParams,\n ) => Promise<ExtendEntityReturnType>\n\n /**\n * Changes the ownership of the entity with the given address.\n *\n * - Docs: https://docs.arkiv.network/ts-sdk/actions/wallet/changeOwnership\n * - JSON-RPC Methods: [`eth_sendRawTransaction`](https://docs.arkiv.network/dev/json-rpc-api/#mutateEntities)\n *\n * @param data - The ownership change parameters\n * @param txParams - Optional transaction parameters\n * @returns The entity with updated ownership and transaction hash\n */\n changeOwnership: (\n data: ChangeOwnershipParameters,\n txParams?: TxParams,\n ) => Promise<ChangeOwnershipReturnType>\n\n /**\n * Mutates the entities with the given keys.\n *\n * - Docs: https://docs.arkiv.network/ts-sdk/actions/wallet/mutateEntities\n * - JSON-RPC Methods: [`eth_sendRawTransaction`](https://docs.arkiv.network/dev/json-rpc-api/#mutateEntities)\n *\n * @param data - The mutation parameters (creates, updates, deletes, extensions)\n * @param txParams - Optional transaction parameters\n * @returns The mutation result with transaction hash\n *\n * @throws {InvalidExpirationError} If any create/update/extension `expiresIn`\n * is not a positive integer that is a multiple of the block time (2 seconds).\n * @throws {InvalidAttributeError} If a numeric attribute value is not an\n * integer.\n *\n * @example\n * import { createWalletClient, http } from 'arkiv'\n * import { braga } from 'arkiv/chains'\n *\n * const client = createWalletClient({\n * chain: braga,\n * transport: http(),\n * })\n * const { entityKey, txHash } = await client.mutateEntities({\n * creates: [{\n * payload: toBytes(JSON.stringify({ entity: { entityType: \"testType\", entityId: \"testId\" } })),\n * attriubutes: [{ key: \"testKey\", value: \"testValue\" }],\n * expiresIn: 1000,\n * }],\n * updates: [{\n * entityKey: \"0x123\",\n * payload: toBytes(JSON.stringify({ entity: { entityType: \"testType\", entityId: \"testId\" } })),\n * attributes: [{ key: \"testKey\", value: \"testValue\" }],\n * expiresIn: 1000,\n * }],\n * deletes: [{\n * entityKey: \"0x321\",\n * }],\n * extensions: [{\n * entityKey: \"0x1234\",\n * expiresIn: 1000,\n * }],\n * })\n * console.log(\"entityKey\", entityKey)\n * console.log(\"txHash\", txHash)\n * // {\n * // entityKey: \"0x123\",\n * // txHash: \"0x123\",\n * // }\n */\n mutateEntities: (\n data: MutateEntitiesParameters,\n txParams?: TxParams,\n ) => Promise<MutateEntitiesReturnType>\n }\n\nexport function walletArkivActions<\n transport extends Transport = Transport,\n chain extends Chain | undefined = Chain | undefined,\n account extends Account | undefined = Account | undefined,\n>(client: Client<transport, chain, account>) {\n return {\n createEntity: (data: CreateEntityParameters, txParams?: TxParams) =>\n createEntity(client, data, txParams),\n updateEntity: (data: UpdateEntityParameters, txParams?: TxParams) =>\n updateEntity(client, data, txParams),\n deleteEntity: (data: DeleteEntityParameters, txParams?: TxParams) =>\n deleteEntity(client, data, txParams),\n extendEntity: (data: ExtendEntityParameters, txParams?: TxParams) =>\n extendEntity(client, data, txParams),\n changeOwnership: (data: ChangeOwnershipParameters, txParams?: TxParams) =>\n changeOwnership(client, data, txParams),\n mutateEntities: (data: MutateEntitiesParameters, txParams?: TxParams) =>\n mutateEntities(client, data, txParams),\n }\n}\n","import type {\n Account,\n Address,\n Chain,\n Client,\n ParseAccount,\n Prettify,\n RpcSchema,\n Transport,\n WalletClientConfig,\n} from \"viem\"\nimport { createClient, publicActions, walletActions } from \"viem\"\nimport type { ArkivRpcSchema } from \"../types/rpcSchema\"\nimport { type WalletArkivActions, walletArkivActions } from \"./decorators/arkivWallet\"\n\nexport type WalletArkivClient<\n transport extends Transport = Transport,\n chain extends Chain | undefined = Chain | undefined,\n account extends Account | undefined = Account | undefined,\n rpcSchema extends RpcSchema | undefined = ArkivRpcSchema,\n> = Prettify<\n Client<transport, chain, account, rpcSchema, WalletArkivActions<transport, chain, account>>\n>\n\n/**\n * Creates a Public Client with a given [Transport](https://viem.sh/docs/clients/intro) configured for a [Chain](https://viem.sh/docs/clients/chains).\n *\n * - Docs: https://docs.arkiv.network/ts-sdk/clients/public\n *\n * A Public Client is an interface to \"public\" [Ethereum JSON-RPC API](https://ethereum.org/en/developers/docs/apis/json-rpc/), [Arkiv JSON-RPC API](https://docs.arkiv.network/json-rpc/), and [Braga JSON-RPC API](https://braga.holesky.arkiv.network/rpc) methods such as retrieving block numbers, transactions, reading from smart contracts, etc through [Public Actions](/docs/actions/public/introduction).\n *\n * @param parameters - Configuration object for the wallet client (chain, transport, account, etc.)\n * @returns A Arkiv Wallet Client. {@link WalletArkivClient}\n *\n * @example\n * import { createPublicClient, http } from 'arkiv'\n * import { braga } from 'arkiv/chains'\n *\n * const client = createPublicClient({\n * chain: braga,\n * transport: http(),\n * })\n */\nexport function createWalletClient<\n transport extends Transport,\n chain extends Chain | undefined = undefined,\n accountOrAddress extends Account | Address | undefined = undefined,\n rpcSchema extends RpcSchema | undefined = ArkivRpcSchema,\n>(\n parameters: WalletClientConfig<transport, chain, accountOrAddress, rpcSchema>,\n): WalletArkivClient<transport, chain, ParseAccount<accountOrAddress>, rpcSchema> {\n const { key = \"wallet\", name = \"Wallet Client\" } = parameters\n const client = createClient({\n ...parameters,\n key,\n name,\n })\n\n return client\n .extend(publicActions)\n .extend(walletActions)\n .extend(walletArkivActions) as unknown as WalletArkivClient<\n transport,\n chain,\n ParseAccount<accountOrAddress>,\n rpcSchema\n >\n}\n","import type { Chain } from \"viem\"\nimport * as chains from \"../chains\"\n\n// Create a lookup map from all exported chains\nconst chainMap = new Map(Object.entries(chains).map(([key, value]) => [key.toLowerCase(), value]))\n\n/**\n * Get a chain from its name\n * @param name - The name of the chain, case insensitive\n * @returns The chain\n * @throws An error if the chain is not found\n */\nexport function chainFromName(name: string): Chain {\n const chain = chainMap.get(name.toLowerCase())\n if (!chain) {\n throw new Error(`Unknown chain: ${name}`)\n }\n return chain as Chain\n}\n"],"mappings":";;;;;;;;AAGA,MAAMA,WAAS,UAAU,kCAAkC;AAQ3D,eAAsB,eAAe,QAAqB;CACxD,MAAM,cAAc,MAAM,OAAO,QAAQ;EACvC,QAAQ;EACR,QAAQ,EAAE;EACX,CAAC;AACF,UAAO,mBAAmB,YAAY;AACtC,QAAO;EACL,cAAc,OAAO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C,CAGC,OAAO,cAAc,CACrB,OAAO,cAAc,CACrB,OAAO,mBAAmB;;;;;ACzD/B,MAAM,WAAW,IAAI,IAAI,OAAO,QAAQC,eAAO,CAAC,KAAK,CAAC,KAAK,WAAW,CAAC,IAAI,aAAa,EAAE,MAAM,CAAC,CAAC;;;;;;;AAQlG,SAAgB,cAAc,MAAqB;CACjD,MAAM,QAAQ,SAAS,IAAI,KAAK,aAAa,CAAC;AAC9C,KAAI,CAAC,MACH,OAAM,IAAI,MAAM,kBAAkB,OAAO;AAE3C,QAAO"}
|
package/dist/query/index.cjs
CHANGED
package/dist/query/index.d.cts
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import "../entity-
|
|
2
|
-
import { C as neq, S as lte, T as or, _ as and, a as asc, b as gte, c as FullEntity, d as SelectionFields, f as selectionToIncludeData, g as PredicateType, h as PredicateContainerType, i as SelectQueryBuilder, l as ProjectedEntity, m as Predicate, n as OrderByAttribute, o as desc, p as QueryResult, r as QueryBuilder, s as EntitySelection, t as BaseQueryBuilder, u as SelectArg, v as eq, w as not, x as lt, y as gt } from "../index-
|
|
1
|
+
import "../entity-B6g_EPm1.cjs";
|
|
2
|
+
import { C as neq, S as lte, T as or, _ as and, a as asc, b as gte, c as FullEntity, d as SelectionFields, f as selectionToIncludeData, g as PredicateType, h as PredicateContainerType, i as SelectQueryBuilder, l as ProjectedEntity, m as Predicate, n as OrderByAttribute, o as desc, p as QueryResult, r as QueryBuilder, s as EntitySelection, t as BaseQueryBuilder, u as SelectArg, v as eq, w as not, x as lt, y as gt } from "../index-Ds9dwqb5.cjs";
|
|
3
3
|
export { BaseQueryBuilder, EntitySelection, FullEntity, OrderByAttribute, Predicate, PredicateContainerType, PredicateType, ProjectedEntity, QueryBuilder, QueryResult, SelectArg, SelectQueryBuilder, SelectionFields, and, asc, desc, eq, gt, gte, lt, lte, neq, not, or, selectionToIncludeData };
|
package/dist/query/index.d.ts
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import "../entity-
|
|
2
|
-
import { C as neq, S as lte, T as or, _ as and, a as asc, b as gte, c as FullEntity, d as SelectionFields, f as selectionToIncludeData, g as PredicateType, h as PredicateContainerType, i as SelectQueryBuilder, l as ProjectedEntity, m as Predicate, n as OrderByAttribute, o as desc, p as QueryResult, r as QueryBuilder, s as EntitySelection, t as BaseQueryBuilder, u as SelectArg, v as eq, w as not, x as lt, y as gt } from "../index-
|
|
1
|
+
import "../entity-qoLMAuuk.js";
|
|
2
|
+
import { C as neq, S as lte, T as or, _ as and, a as asc, b as gte, c as FullEntity, d as SelectionFields, f as selectionToIncludeData, g as PredicateType, h as PredicateContainerType, i as SelectQueryBuilder, l as ProjectedEntity, m as Predicate, n as OrderByAttribute, o as desc, p as QueryResult, r as QueryBuilder, s as EntitySelection, t as BaseQueryBuilder, u as SelectArg, v as eq, w as not, x as lt, y as gt } from "../index-DdspxNAA.js";
|
|
3
3
|
export { BaseQueryBuilder, EntitySelection, FullEntity, OrderByAttribute, Predicate, PredicateContainerType, PredicateType, ProjectedEntity, QueryBuilder, QueryResult, SelectArg, SelectQueryBuilder, SelectionFields, and, asc, desc, eq, gt, gte, lt, lte, neq, not, or, selectionToIncludeData };
|
package/dist/query/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { a as desc, i as asc, n as QueryBuilder, o as selectionToIncludeData, r as SelectQueryBuilder, s as QueryResult, t as BaseQueryBuilder } from "../queryBuilder-
|
|
1
|
+
import { a as desc, i as asc, n as QueryBuilder, o as selectionToIncludeData, r as SelectQueryBuilder, s as QueryResult, t as BaseQueryBuilder } from "../queryBuilder-D2uwP9jI.js";
|
|
2
2
|
import "../consts-BV4PR-de.js";
|
|
3
3
|
|
|
4
4
|
//#region src/query/predicate.ts
|
|
@@ -400,6 +400,10 @@ function selectionToIncludeData(selection) {
|
|
|
400
400
|
* @param attributeType - The type of the attribute to order by (string or number)
|
|
401
401
|
* @returns Input for orderBy method
|
|
402
402
|
*
|
|
403
|
+
* @deprecated Server-side ordering is not supported by the network, so `orderBy` (and this
|
|
404
|
+
* helper) have no effect on the returned order. Sort the fetched entities in JavaScript
|
|
405
|
+
* instead (e.g. `entities.sort(...)`). This function will be removed in a future release.
|
|
406
|
+
*
|
|
403
407
|
* @example
|
|
404
408
|
* const ascAttribute = asc("name", "string")
|
|
405
409
|
*/
|
|
@@ -416,6 +420,10 @@ function asc(attributeName, attributeType) {
|
|
|
416
420
|
* @param attributeType - The type of the attribute to order by (string or number)
|
|
417
421
|
* @returns Input for orderBy method
|
|
418
422
|
*
|
|
423
|
+
* @deprecated Server-side ordering is not supported by the network, so `orderBy` (and this
|
|
424
|
+
* helper) have no effect on the returned order. Sort the fetched entities in JavaScript
|
|
425
|
+
* instead (e.g. `entities.sort(...)`). This function will be removed in a future release.
|
|
426
|
+
*
|
|
419
427
|
* @example
|
|
420
428
|
* const descAttribute = desc("name", "string")
|
|
421
429
|
*/
|
|
@@ -693,4 +701,4 @@ var SelectQueryBuilder = class extends BaseQueryBuilder {
|
|
|
693
701
|
|
|
694
702
|
//#endregion
|
|
695
703
|
export { desc as a, entityFromRpcResult as c, InvalidExpirationError as d, NoCursorOrLimitError as f, getLogger as h, asc as i, EntityMutationError as l, NoMoreResultsError as m, QueryBuilder as n, selectionToIncludeData as o, NoEntityFoundError as p, SelectQueryBuilder as r, QueryResult as s, BaseQueryBuilder as t, InvalidAttributeError as u };
|
|
696
|
-
//# sourceMappingURL=queryBuilder-
|
|
704
|
+
//# sourceMappingURL=queryBuilder-D2uwP9jI.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"queryBuilder-D2uwP9jI.js","names":["enabledNamespaces: Set<string>","disabledNamespaces: Set<string>","logger","logger","predicate","queryOptions: RpcQueryOptions","order"],"sources":["../src/utils/logger.ts","../src/errors.ts","../src/types/entity.ts","../src/utils/entities.ts","../src/query/engine.ts","../src/query/queryResult.ts","../src/query/selection.ts","../src/query/queryBuilder.ts"],"sourcesContent":["const ROOT_NAMESPACE = \"arkiv\"\n\n// Debug logger type - returns a function that can be called to log messages\ntype DebugLogger = (...args: unknown[]) => void\n\n// Get DEBUG environment variable (works in both Node.js and browser)\nfunction getDebugEnv(): string {\n if (typeof process !== \"undefined\") {\n const debugEnv = process?.env?.DEBUG\n if (debugEnv) {\n return debugEnv\n }\n }\n // Browser: check localStorage\n if (typeof globalThis !== \"undefined\" && \"localStorage\" in globalThis) {\n try {\n const storage = (globalThis as { localStorage?: Storage }).localStorage\n return storage?.getItem(\"DEBUG\") || \"\"\n } catch {\n // localStorage might not be available\n }\n }\n return \"\"\n}\n\n// Parse debug patterns and check if a namespace matches\nfunction matchesPattern(namespace: string, pattern: string): boolean {\n // Exact match\n if (pattern === namespace) return true\n\n // Wildcard match: \"arkiv:*\" matches \"arkiv:query\", \"arkiv:rpc\", etc.\n if (pattern.endsWith(\"*\")) {\n const prefix = pattern.slice(0, -1)\n return namespace.startsWith(prefix)\n }\n\n // Negative match: \"-arkiv:query\" excludes \"arkiv:query\"\n if (pattern.startsWith(\"-\")) {\n const excludePattern = pattern.slice(1)\n return !matchesPattern(namespace, excludePattern)\n }\n\n return false\n}\n\n// Check if a namespace is enabled for debugging\nfunction isEnabled(namespace: string): boolean {\n const debugEnv = getDebugEnv()\n if (!debugEnv) return false\n\n // Split by comma/space and check each pattern\n const patterns = debugEnv.split(/[\\s,]+/).filter((p) => p.length > 0)\n\n // If no patterns, nothing is enabled\n if (patterns.length === 0) return false\n\n // Check if any pattern matches (or if explicitly excluded)\n let enabled = false\n for (const pattern of patterns) {\n if (pattern.startsWith(\"-\")) {\n // Exclude pattern - if it matches, disable\n if (matchesPattern(namespace, pattern)) {\n return false\n }\n } else if (matchesPattern(namespace, pattern)) {\n enabled = true\n }\n }\n\n return enabled\n}\n\n// Store enabled namespaces (for programmatic enable/disable)\nconst enabledNamespaces: Set<string> = new Set()\nconst disabledNamespaces: Set<string> = new Set()\n\n// Color palette for namespace coloring (distinct, readable colors)\nconst COLOR_PALETTE = [\n \"#0000FF\", // blue\n \"#008000\", // green\n \"#FF0000\", // red\n \"#FF00FF\", // magenta\n \"#FFA500\", // orange\n \"#800080\", // purple\n \"#00CED1\", // dark turquoise\n \"#FF1493\", // deep pink\n \"#32CD32\", // lime green\n \"#1E90FF\", // dodger blue\n \"#FF4500\", // orange red\n \"#9370DB\", // medium purple\n \"#00FA9A\", // medium spring green\n \"#FFD700\", // gold\n \"#DC143C\", // crimson\n \"#00BFFF\", // deep sky blue\n \"#FF69B4\", // hot pink\n \"#20B2AA\", // light sea green\n \"#DA70D6\", // orchid\n \"#4682B4\", // steel blue\n]\n\n// Detect if we're in Node.js (for ANSI colors) or browser (for CSS colors)\nconst isNode = typeof process !== \"undefined\" && process.versions?.node != null\n\n// ANSI color codes for Node.js (bright, distinct colors)\nconst ANSI_COLORS = [\n \"\\x1b[94m\", // bright blue\n \"\\x1b[92m\", // bright green\n \"\\x1b[91m\", // bright red\n \"\\x1b[95m\", // bright magenta\n \"\\x1b[93m\", // bright yellow\n \"\\x1b[96m\", // bright cyan\n \"\\x1b[35m\", // magenta\n \"\\x1b[36m\", // cyan\n \"\\x1b[32m\", // green\n \"\\x1b[34m\", // blue\n \"\\x1b[33m\", // yellow\n \"\\x1b[31m\", // red\n \"\\x1b[90m\", // bright black (gray)\n \"\\x1b[37m\", // white\n \"\\x1b[1m\", // bold (as a color option)\n]\n\nconst ANSI_RESET = \"\\x1b[0m\"\nconst ANSI_BOLD = \"\\x1b[1m\"\n\n// Cache colors for namespaces (same namespace = same color)\nconst namespaceColors = new Map<string, { css: string; ansi: string }>()\n\n// Generate a consistent color for a namespace based on its hash\nfunction getColorForNamespace(namespace: string): { css: string; ansi: string } {\n // Check cache first\n const cachedColor = namespaceColors.get(namespace)\n if (cachedColor) {\n return cachedColor\n }\n\n // Simple hash function to convert string to number\n let hash = 0\n for (let i = 0; i < namespace.length; i++) {\n const char = namespace.charCodeAt(i)\n hash = (hash << 5) - hash + char\n hash = hash & hash // Convert to 32-bit integer\n }\n\n // Use absolute value and modulo to get index\n const colorIndex = Math.abs(hash) % COLOR_PALETTE.length\n const cssColor = COLOR_PALETTE[colorIndex]\n const ansiColor = ANSI_COLORS[colorIndex % ANSI_COLORS.length]\n\n const color = { css: cssColor, ansi: ansiColor }\n\n // Cache the color\n namespaceColors.set(namespace, color)\n\n return color\n}\n\n// Create a debug logger function\nfunction createDebugLogger(namespace: string): DebugLogger {\n // Get the color for this namespace (consistent across calls)\n const colors = getColorForNamespace(namespace)\n\n return (...args: unknown[]) => {\n // Check if enabled via environment variable or programmatically\n const envEnabled = isEnabled(namespace)\n const progEnabled = enabledNamespaces.has(namespace) && !disabledNamespaces.has(namespace)\n\n if (envEnabled || progEnabled) {\n if (isNode) {\n // Node.js: use ANSI color codes\n const coloredNamespace = `${ANSI_BOLD}${colors.ansi}${namespace}${ANSI_RESET}`\n console.log(coloredNamespace, ...args)\n } else {\n // Browser: use CSS styling with %c\n // The format is: console.log(\"%cstyled%cnormal\", style1, style2, ...args)\n // This colors the namespace, then resets for the rest\n const style1 = `color: ${colors.css}; font-weight: bold`\n const style2 = \"color: inherit; font-weight: normal\"\n // Combine namespace with a space, then log with styles\n console.log(`%c${namespace}%c`, style1, style2, ...args)\n }\n }\n }\n}\n\nexport const getLogger = (scope: string): DebugLogger => {\n const namespace = `${ROOT_NAMESPACE}:${scope}`\n return createDebugLogger(namespace)\n}\n\nexport const enableDebug = (namespaces: string): void => {\n // Parse and add namespaces to enabled set\n const patterns = namespaces.split(/[\\s,]+/).filter((p) => p.length > 0)\n for (const pattern of patterns) {\n if (pattern.startsWith(\"-\")) {\n // Remove from enabled, add to disabled\n const namespace = pattern.slice(1)\n enabledNamespaces.delete(namespace)\n disabledNamespaces.add(namespace)\n } else {\n enabledNamespaces.add(pattern)\n disabledNamespaces.delete(pattern)\n }\n }\n}\n\nexport const disableDebug = (): void => {\n enabledNamespaces.clear()\n disabledNamespaces.clear()\n}\n","import { BLOCK_TIME } from \"./consts\"\n\nexport class EntityMutationError extends Error {\n constructor(message: string) {\n super(message)\n this.name = \"EntityMutationError\"\n }\n}\nexport class InvalidExpirationError extends Error {\n constructor(expiresIn: unknown) {\n super(\n `Invalid expiresIn: ${String(expiresIn)}. expiresIn must be a positive integer and a multiple of the Arkiv block time (${BLOCK_TIME} seconds), because expiration is measured in whole blocks (1 block = ${BLOCK_TIME} seconds).`,\n )\n this.name = \"InvalidExpirationError\"\n }\n}\nexport class InvalidAttributeError extends Error {\n constructor(key: string, value: number) {\n super(\n `Invalid numeric value for attribute \"${key}\": ${String(value)}. Numeric attribute values must be integers. To keep numeric ordering/range queries, scale it to an integer (e.g. Math.round(${String(value)} * 1000), dividing by 1000 on read); otherwise store it as a string (e.g. \"${String(value)}\").`,\n )\n this.name = \"InvalidAttributeError\"\n }\n}\n\nexport class NoMoreResultsError extends Error {\n constructor() {\n super(\"No more results\")\n this.name = \"NoMoreResultsError\"\n }\n}\n\nexport class NoCursorOrLimitError extends Error {\n constructor() {\n super(\"Cursor and limit must be defined to fetch next\")\n this.name = \"NoCursorOrLimitError\"\n }\n}\n\nexport class NoEntityFoundError extends Error {\n constructor() {\n super(\"No entity found\")\n this.name = \"NoEntityFoundError\"\n }\n}\n","import { bytesToString, type Hex } from \"viem\"\nimport type { MimeType } from \"../types\"\nimport type { Attribute } from \"./attributes\"\n\nexport class Entity {\n key: Hex\n contentType: MimeType | undefined\n owner: Hex | undefined\n creator: Hex | undefined\n expiresAtBlock: bigint | undefined\n createdAtBlock: bigint | undefined\n lastModifiedAtBlock: bigint | undefined\n transactionIndexInBlock: bigint | undefined\n operationIndexInTransaction: bigint | undefined\n payload: Uint8Array | undefined\n attributes: Attribute[]\n\n constructor(\n key: Hex,\n contentType: MimeType | undefined = undefined,\n owner: Hex | undefined = undefined,\n creator: Hex | undefined = undefined,\n expiresAtBlock: bigint | undefined = undefined,\n createdAtBlock: bigint | undefined = undefined,\n lastModifiedAtBlock: bigint | undefined = undefined,\n transactionIndexInBlock: bigint | undefined = undefined,\n operationIndexInTransaction: bigint | undefined = undefined,\n payload: Uint8Array | undefined = undefined,\n attributes: Attribute[],\n ) {\n this.key = key\n this.owner = owner\n this.creator = creator\n this.expiresAtBlock = expiresAtBlock\n this.createdAtBlock = createdAtBlock\n this.lastModifiedAtBlock = lastModifiedAtBlock\n this.transactionIndexInBlock = transactionIndexInBlock\n this.operationIndexInTransaction = operationIndexInTransaction\n this.payload = payload\n this.attributes = attributes\n this.contentType = contentType\n }\n\n /**\n * Converts the entity payload from bytes to a string and returns it.\n * Throws an error if the payload is undefined, which may occur if the entity was not queried with the withPayload option.\n * Throws an error if the conversion from bytes to string fails.\n * @returns The entity payload as a string.\n */\n toText(): string {\n if (this.payload === undefined) {\n throw new Error(\n \"Entity has no payload – it was probably queried without withPayload(true) via QueryBuilder\",\n )\n }\n try {\n return bytesToString(this.payload)\n } catch (e) {\n throw new Error(\n `Failed to convert entity payload to text: ${e instanceof Error ? e.message : String(e)}`,\n { cause: e },\n )\n }\n }\n\n /**\n * Parses the entity payload as JSON and returns the resulting object.\n * Throws an error if the payload is undefined, which may occur if the entity was not queried with the withPayload option.\n * Throws an error if the payload is empty or cannot be parsed as JSON.\n * @returns The parsed JSON object from the entity payload.\n */\n toJson(): any {\n const text = this.toText()\n if (!text) {\n throw new Error(\"Entity has empty payload, cannot parse as JSON\")\n }\n try {\n return JSON.parse(text)\n } catch (e) {\n throw new Error(\n `Failed to parse entity payload as JSON: ${e instanceof Error ? e.message : String(e)}`,\n { cause: e },\n )\n }\n }\n}\n","import { toBytes } from \"viem\"\nimport { Entity } from \"../types/entity\"\nimport type { RpcEntity } from \"../types/rpcSchema\"\nimport { getLogger } from \"./logger\"\n\nconst logger = getLogger(\"utils:entities\")\n\nexport async function entityFromRpcResult(rpcEntity: RpcEntity) {\n logger(\"entityFromRpcResult %o\", rpcEntity)\n\n return new Entity(\n rpcEntity.key,\n rpcEntity.contentType,\n rpcEntity.owner,\n rpcEntity.creator,\n rpcEntity.expiresAt !== undefined ? BigInt(rpcEntity.expiresAt) : undefined,\n rpcEntity.createdAtBlock !== undefined ? BigInt(rpcEntity.createdAtBlock) : undefined,\n rpcEntity.lastModifiedAtBlock !== undefined ? BigInt(rpcEntity.lastModifiedAtBlock) : undefined,\n rpcEntity.transactionIndexInBlock !== undefined\n ? BigInt(rpcEntity.transactionIndexInBlock)\n : undefined,\n rpcEntity.operationIndexInTransaction !== undefined\n ? BigInt(rpcEntity.operationIndexInTransaction)\n : undefined,\n rpcEntity.value !== undefined ? toBytes(rpcEntity.value) : undefined,\n [\n ...(rpcEntity.stringAttributes ?? []).map(({ key, value }) => ({\n key,\n value,\n })),\n ...(rpcEntity.numericAttributes ?? []).map(({ key, value }) => ({\n key,\n value: Number(value),\n })),\n ],\n )\n}\n","import type { Hex } from \"viem\"\nimport { hexToNumber, numberToHex } from \"viem\"\nimport type { ArkivClient } from \"../clients/baseClient\"\nimport type { RpcIncludeData, RpcOrderByAttribute, RpcQueryOptions } from \"../types/rpcSchema\"\nimport { getLogger } from \"../utils/logger\"\nimport type { Predicate } from \"./predicate\"\n\nconst logger = getLogger(\"query:engine\")\n\nfunction processPredicates(predicates: Predicate[]): string {\n const processValue = (value: string | number) => {\n if (typeof value === \"string\") {\n return `\"${value}\"`\n }\n return value\n }\n return predicates\n .map((predicate) => {\n switch (predicate.type) {\n case \"eq\":\n return `${predicate.key} = ${processValue(predicate.value)}`\n case \"neq\":\n return `${predicate.key} != ${processValue(predicate.value)}`\n case \"gt\":\n return `${predicate.key} > ${processValue(predicate.value)}`\n case \"gte\":\n return `${predicate.key} >= ${processValue(predicate.value)}`\n case \"lt\":\n return `${predicate.key} < ${processValue(predicate.value)}`\n case \"lte\":\n return `${predicate.key} <= ${processValue(predicate.value)}`\n case \"not\":\n return `!${predicate.key}`\n case \"or\":\n return `(${predicate.predicates.map((predicate) => processPredicates([predicate])).join(\" || \")})`\n case \"and\":\n return `(${predicate.predicates.map((predicate) => processPredicates([predicate])).join(\" && \")})`\n default:\n return \"\"\n }\n })\n .join(\" && \")\n}\n\nexport async function processQuery(\n client: ArkivClient,\n queryParams: {\n predicates: Predicate[]\n limit: number | undefined\n cursor: string | undefined\n ownedBy: Hex | undefined\n createdBy: Hex | undefined\n orderBy: RpcOrderByAttribute[] | undefined\n validAtBlock?: bigint | undefined\n withAttributes?: boolean | undefined\n withMetadata?: boolean | undefined\n withPayload?: boolean | undefined\n /**\n * Fully-resolved include-data for fine-grained selection. When provided it takes\n * precedence over the `withAttributes`/`withMetadata`/`withPayload` booleans.\n */\n includeData?: RpcIncludeData | undefined\n },\n) {\n const {\n predicates,\n limit,\n cursor,\n ownedBy,\n createdBy,\n orderBy,\n validAtBlock,\n withAttributes,\n withMetadata,\n withPayload,\n includeData,\n } = queryParams\n\n logger(\"Processing query with params %o\", {\n predicates,\n cursor,\n limit,\n ownedBy,\n createdBy,\n orderBy,\n validAtBlock,\n withAttributes,\n withMetadata,\n withPayload,\n includeData,\n })\n\n let query = processPredicates(predicates)\n if (ownedBy) {\n query += ` && $owner=${ownedBy}`\n }\n if (createdBy) {\n query += ` && $creator=${createdBy}`\n }\n\n // remove leading and trailing spaces and leading &&\n query = query.trim()\n if (query.startsWith(\"&& \")) {\n query = query.slice(3)\n }\n\n const queryOptions: RpcQueryOptions = {\n includeData:\n includeData ??\n ({\n key: true,\n attributes: withAttributes ?? false,\n payload: withPayload ?? false,\n contentType: withMetadata ?? false,\n expiration: withMetadata ?? false,\n owner: withMetadata ?? false,\n creator: withMetadata ?? false,\n createdAtBlock: withMetadata ?? false,\n lastModifiedAtBlock: withMetadata ?? false,\n transactionIndexInBlock: withMetadata ?? false,\n operationIndexInTransaction: withMetadata ?? false,\n } as RpcIncludeData),\n }\n\n if (validAtBlock !== undefined) {\n queryOptions.atBlock = numberToHex(validAtBlock)\n }\n if (limit !== undefined) {\n queryOptions.resultsPerPage = numberToHex(limit)\n }\n if (cursor !== undefined) {\n queryOptions.cursor = cursor\n }\n if (orderBy !== undefined) {\n queryOptions.orderBy = orderBy\n }\n\n logger(\"Built query to send %s %o\", query, {\n includeData: queryOptions.includeData,\n atBlock: queryOptions.atBlock ? hexToNumber(queryOptions.atBlock) : undefined,\n orderBy: queryOptions.orderBy,\n resultsPerPage: queryOptions.resultsPerPage,\n cursor: queryOptions.cursor,\n })\n\n const result = await client.request({\n method: \"arkiv_query\",\n params: [query, queryOptions],\n })\n logger(\"Raw result from query %o\", result)\n\n return result\n}\n","import { NoCursorOrLimitError, NoMoreResultsError } from \"../errors\"\nimport type { Entity } from \"../types/entity\"\nimport { getLogger } from \"../utils/logger\"\nimport type { BaseQueryBuilder } from \"./queryBuilder\"\n\nconst logger = getLogger(\"query:result\")\n\n/**\n * The result of a query. Holds the fetched entities and supports cursor-based pagination.\n *\n * @typeParam TEntity - The shape of each entity, inferred from the query builder\n * (a full {@link Entity}, or a projected object inferred from a `select()` selection).\n */\nexport class QueryResult<TEntity = Entity> {\n entities: TEntity[]\n private _endOfIteration: boolean\n private _cursor: string | undefined\n private _limit: number | undefined\n private _validAtBlock: bigint | undefined\n private _queryBuilder: BaseQueryBuilder<TEntity>\n\n // Public getters for internal state\n get queryBuilder(): BaseQueryBuilder<TEntity> {\n return this._queryBuilder\n }\n\n get cursor(): string | undefined {\n return this._cursor\n }\n\n constructor(\n entities: TEntity[],\n queryBuilder: BaseQueryBuilder<TEntity>,\n cursor: string | undefined,\n limit: number | undefined,\n validAtBlock: bigint | undefined,\n ) {\n this.entities = entities\n this._queryBuilder = queryBuilder\n this._endOfIteration = !limit || entities.length < limit\n this._cursor = cursor\n this._limit = limit\n this._validAtBlock = validAtBlock\n }\n\n async next() {\n if (this._cursor === undefined || this._limit === undefined) {\n throw new NoCursorOrLimitError()\n }\n if (this._endOfIteration) {\n throw new NoMoreResultsError()\n }\n this._queryBuilder.cursor(this._cursor)\n const result = await this._queryBuilder.fetch()\n this.entities = result.entities\n // Update the query builder reference\n this._queryBuilder = result.queryBuilder\n // Check if we've reached the end (no more cursor or we got fewer entities than limit)\n this._endOfIteration = !result.cursor || result.entities.length < this._limit\n // Update the cursor\n this._cursor = result.cursor\n\n // TODO check current block height and if it is not too old\n logger(\"Current block height for next page %s\", this._validAtBlock?.toString() ?? \"unknown\")\n }\n\n hasNextPage() {\n return !this._endOfIteration\n }\n}\n","import type { Entity } from \"../types/entity\"\nimport type { RpcIncludeData } from \"../types/rpcSchema\"\n\n/** The entity fields that can be selected. These match the fields of {@link Entity} one-to-one. */\ntype DataKey =\n | \"key\"\n | \"contentType\"\n | \"owner\"\n | \"creator\"\n | \"expiresAtBlock\"\n | \"createdAtBlock\"\n | \"lastModifiedAtBlock\"\n | \"transactionIndexInBlock\"\n | \"operationIndexInTransaction\"\n | \"attributes\"\n | \"payload\"\n\n/**\n * The parts of an entity that can be selected. Every field is opt-in (including the `key`) and maps\n * directly to a field of the returned {@link Entity} — the selection is flat.\n */\nexport type SelectionFields = { [K in DataKey]?: boolean }\n\n/**\n * Requires at least one property of `T` to be present.\n * `{}` is not assignable, which is how `select({})` is rejected at compile time.\n */\ntype AtLeastOne<T, K extends keyof T = keyof T> = {\n [P in K]: Required<Pick<T, P>> & Partial<Omit<T, P>>\n}[K]\n\n/**\n * A non-empty entity selection — the object form accepted by `select()`. At least one field must be\n * selected.\n */\nexport type EntitySelection = AtLeastOne<SelectionFields>\n\n/** Argument accepted by `select()` — a non-empty {@link EntitySelection}, or `\"*\"` for everything. */\nexport type SelectArg = EntitySelection | \"*\"\n\n/**\n * The result of a selection `S`: an {@link Entity} narrowed to exactly the selected fields (each\n * non-`undefined`). The shape is flat and backwards compatible — e.g. `select({ owner: true })`\n * yields `{ owner: Hex }` accessed as `entity.owner`. Accessing an unselected field is a compile\n * error.\n *\n * The `toText()` / `toJson()` helpers operate on the payload, so they are only present when\n * `payload` was selected — calling them otherwise would always throw.\n */\nexport type ProjectedEntity<S> = {\n readonly [K in keyof S as S[K] extends true ? K : never]: K extends keyof Entity\n ? NonNullable<Entity[K]>\n : never\n} & (S extends { payload: true } ? Pick<Entity, \"toText\" | \"toJson\"> : unknown)\n\n/** A selection of every field, used to type the result of `select()` / `select(\"*\")`. */\ntype AllSelected = { [K in DataKey]: true }\n\n/** The projected entity type when everything is selected — every field, plus the methods. */\nexport type FullEntity = ProjectedEntity<AllSelected>\n\n/**\n * Converts a {@link SelectArg} into the {@link RpcIncludeData} understood by the query engine.\n * Every field is opt-in — anything not explicitly selected defaults to `false`, including the key.\n * `undefined` or `\"*\"` selects everything.\n *\n * @param selection - The selection to convert\n * @returns The fully-resolved include-data object for the RPC query\n * @throws If an empty selection object is provided\n *\n * @example\n * selectionToIncludeData() // everything\n * selectionToIncludeData(\"*\") // everything\n * selectionToIncludeData({ key: true }) // only the key\n * selectionToIncludeData({ owner: true }) // only the owner\n */\nexport function selectionToIncludeData(selection?: SelectArg): RpcIncludeData {\n if (selection === undefined || selection === \"*\") {\n return {\n key: true,\n attributes: true,\n payload: true,\n contentType: true,\n expiration: true,\n owner: true,\n creator: true,\n createdAtBlock: true,\n lastModifiedAtBlock: true,\n transactionIndexInBlock: true,\n operationIndexInTransaction: true,\n }\n }\n\n // At least one field must be opted in. This rejects both `{}` and selections whose fields are\n // all explicitly `false` (e.g. `select({ key: false })`), which the type system permits.\n if (!Object.values(selection).some((selected) => selected === true)) {\n throw new Error(\n 'select() requires at least one field to be selected. Pass select() or select(\"*\") to select everything.',\n )\n }\n\n return {\n key: selection.key ?? false,\n attributes: selection.attributes ?? false,\n payload: selection.payload ?? false,\n contentType: selection.contentType ?? false,\n // The selection uses the entity field name `expiresAtBlock`; the RPC calls it `expiration`.\n expiration: selection.expiresAtBlock ?? false,\n owner: selection.owner ?? false,\n creator: selection.creator ?? false,\n createdAtBlock: selection.createdAtBlock ?? false,\n lastModifiedAtBlock: selection.lastModifiedAtBlock ?? false,\n transactionIndexInBlock: selection.transactionIndexInBlock ?? false,\n operationIndexInTransaction: selection.operationIndexInTransaction ?? false,\n }\n}\n","import type { Hex } from \"viem\"\nimport type { ArkivClient } from \"../clients/baseClient\"\nimport type { Entity } from \"../types/entity\"\nimport type { RpcEntity, RpcIncludeData, RpcOrderByAttribute } from \"../types/rpcSchema\"\nimport { entityFromRpcResult } from \"../utils/entities\"\nimport { processQuery } from \"./engine\"\nimport type { Predicate } from \"./predicate\"\nimport { QueryResult } from \"./queryResult\"\nimport { type SelectArg, selectionToIncludeData } from \"./selection\"\n\n/**\n * @deprecated Server-side ordering is not supported by the network. Sort the fetched\n * entities in JavaScript instead (e.g. `entities.sort(...)`). This type will be removed\n * in a future release.\n */\nexport type OrderByAttribute = {\n name: string\n type: \"string\" | \"number\"\n order: \"asc\" | \"desc\"\n}\n\n/**\n * Helper function to create an ascending order by attribute\n * @param attributeName - The name of the attribute to order by\n * @param attributeType - The type of the attribute to order by (string or number)\n * @returns Input for orderBy method\n *\n * @deprecated Server-side ordering is not supported by the network, so `orderBy` (and this\n * helper) have no effect on the returned order. Sort the fetched entities in JavaScript\n * instead (e.g. `entities.sort(...)`). This function will be removed in a future release.\n *\n * @example\n * const ascAttribute = asc(\"name\", \"string\")\n */\nexport function asc(attributeName: string, attributeType: \"string\" | \"number\"): OrderByAttribute {\n return {\n name: attributeName,\n type: attributeType,\n order: \"asc\",\n }\n}\n\n/**\n * Helper function to create a descending order by attribute\n * @param attributeName - The name of the attribute to order by\n * @param attributeType - The type of the attribute to order by (string or number)\n * @returns Input for orderBy method\n *\n * @deprecated Server-side ordering is not supported by the network, so `orderBy` (and this\n * helper) have no effect on the returned order. Sort the fetched entities in JavaScript\n * instead (e.g. `entities.sort(...)`). This function will be removed in a future release.\n *\n * @example\n * const descAttribute = desc(\"name\", \"string\")\n */\nexport function desc(attributeName: string, attributeType: \"string\" | \"number\"): OrderByAttribute {\n return {\n name: attributeName,\n type: attributeType,\n order: \"desc\",\n }\n}\n\n/**\n * Data-selection parameters forwarded to the query engine on each fetch.\n * Subclasses of {@link BaseQueryBuilder} decide which parts of an entity are fetched.\n */\ntype SelectionParams = {\n withAttributes?: boolean | undefined\n withMetadata?: boolean | undefined\n withPayload?: boolean | undefined\n includeData?: RpcIncludeData | undefined\n}\n\n/**\n * BaseQueryBuilder holds the query-building logic shared by every query builder\n * (filtering, ordering, pagination, execution). It follows the Builder pattern,\n * allowing methods to be chained. Subclasses decide how data selection is expressed\n * by implementing the protected `selectionParams` method.\n *\n * Use {@link SelectQueryBuilder} via `client.select()` to build and execute queries.\n *\n * @typeParam TEntity - The shape of each entity produced by {@link BaseQueryBuilder.fetch}.\n */\nexport abstract class BaseQueryBuilder<TEntity> {\n protected _client: ArkivClient\n protected _ownedBy: Hex | undefined\n protected _createdBy: Hex | undefined\n protected _orderBy: RpcOrderByAttribute[] | undefined\n protected _validAtBlock: bigint | undefined\n protected _limit: number | undefined\n protected _cursor: string | undefined\n protected _predicates: Predicate[]\n\n constructor(client: ArkivClient) {\n this._client = client\n this._predicates = []\n }\n\n /**\n * Sets the ownedBy filter\n * @param ownedBy - The address of the owner\n * @returns The query builder instance\n *\n * @example\n * const builder = client.select()\n * builder.ownedBy(\"0x1234567890123456789012345678901234567890\")\n */\n ownedBy(ownedBy: Hex): this {\n this._ownedBy = ownedBy\n return this\n }\n\n /**\n * Sets the createdBy filter\n * @param createdBy - The address of the creator\n * @returns The query builder instance\n *\n * @example\n * const builder = client.select()\n * builder.createdBy(\"0x1234567890123456789012345678901234567890\")\n */\n createdBy(createdBy: Hex): this {\n this._createdBy = createdBy\n return this\n }\n\n /**\n * Sets the orderBy for the query.\n * It can be called multiple times to order by multiple attributes.\n * The order of the attributes is important. The first attribute is the primary order by attribute.\n * You can use the helper functions asc() and desc() as input for this method.\n * @param attributeName - The name of the attribute to order by\n * @param attributeType - The type of the attribute to order by (string or number)\n * @param order - The order to set the order by (asc or desc)\n * @returns The query builder instance\n *\n * @deprecated Server-side ordering is not supported by the network, so this method has no\n * effect on the returned order. Sort the fetched entities in JavaScript instead, e.g.\n * `result.entities.sort((a, b) => ...)`. This method will be removed in a future release.\n *\n * @example\n * const builder = client.select()\n * builder.orderBy(\"name\", \"string\", \"desc\")\n * builder.orderBy(asc(\"name\", \"string\"))\n * builder.orderBy(desc(\"name\", \"string\"))\n */\n orderBy(attributeName: string, attributeType: \"string\" | \"number\", order?: \"asc\" | \"desc\"): this\n /**\n * Sets the orderBy for the query.\n * This method takes the OrderByAttribute object as an argument and is mainly\n * used to use the helper functions asc() and desc() to create the OrderByAttribute instances.\n * @param orderByAttribute - The OrderByAttribute instance to set\n * @returns The query builder instance\n *\n * @deprecated Server-side ordering is not supported by the network, so this method has no\n * effect on the returned order. Sort the fetched entities in JavaScript instead, e.g.\n * `result.entities.sort((a, b) => ...)`. This method will be removed in a future release.\n *\n * @example\n * const builder = client.select()\n * builder.orderBy(asc(\"name\", \"string\"))\n * builder.orderBy(desc(\"name\", \"string\"))\n */\n orderBy(orderByAttribute: OrderByAttribute): this\n orderBy(\n attributeNameOrOrderByAttribute: string | OrderByAttribute,\n attributeType?: \"string\" | \"number\",\n order: \"asc\" | \"desc\" = \"asc\",\n ): this {\n if (!this._orderBy) {\n this._orderBy = []\n }\n\n const pushOrderByAttribute = ({ name, type, order }: OrderByAttribute) => {\n this._orderBy?.push({\n name,\n type: type === \"number\" ? \"numeric\" : type,\n desc: order === \"desc\",\n })\n }\n\n if (typeof attributeNameOrOrderByAttribute === \"string\") {\n if (!attributeType) {\n throw new Error(\"attributeType is required when using positional orderBy arguments\")\n }\n pushOrderByAttribute({\n name: attributeNameOrOrderByAttribute,\n type: attributeType,\n order,\n })\n } else {\n pushOrderByAttribute(attributeNameOrOrderByAttribute)\n }\n\n return this\n }\n\n /**\n * Sets the limit for the query\n * @param limit - The number of entities to return\n * @returns The query builder instance\n *\n * @example\n * const builder = client.select()\n * builder.limit(10)\n */\n limit(limit: number): this {\n this._limit = limit\n return this\n }\n\n /**\n * Sets the cursor for the query - it is advances setting which rather shouldn't be used manually but it is provided from query result if limit is used (pagination).\n * @param cursor - The cursor to set which tells to RPC Query server where to start or continue the query.\n * @returns The query builder instance\n *\n * @example\n * const builder = client.select()\n * builder.cursor(\"0xABC123\")\n */\n cursor(cursor: string): this {\n this._cursor = cursor\n return this\n }\n\n /**\n * Sets the validAtBlock for the query which tells at which block height the state we are intested.\n * If not set, the latest block is used.\n * @param validAtBlock - The block number to set\n * @returns The query builder instance\n *\n * @example\n * const builder = client.select()\n * builder.validAtBlock(10000)\n */\n validAtBlock(validAtBlock: bigint): this {\n this._validAtBlock = validAtBlock\n return this\n }\n\n /**\n * Sets the predicates for the query limiting the results. It can be a single predicate,\n * multiple predicates passed as separate arguments, or an array of predicates - all combined with 'and'.\n * Predicates can be nested using 'or' and 'and' predicates.\n * @param predicates - The predicates to set, either as a single array or as separate arguments\n * @returns The query builder instance\n *\n * @example\n * const builder = client.select()\n * builder.where(eq(\"name\", \"John\"))\n * builder.where(eq(\"name\", \"John\"), eq(\"age\", 30))\n * builder.where([eq(\"name\", \"John\"), eq(\"age\", 30)])\n * builder.where(eq(\"name\", \"John\"), or(eq(\"age\", 30), eq(\"age\", 31)))\n * builder.where(eq(\"name\", \"John\"), and(eq(\"age\", 30), eq(\"age\", 31)))\n * builder.where(eq(\"name\", \"John\"), or(eq(\"age\", 30), and(eq(\"age\", 31), eq(\"age\", 32))))\n * builder.where(eq(\"name\", \"John\"), and(eq(\"age\", 30), or(eq(\"age\", 31), eq(\"age\", 32))))\n */\n where(predicates: Predicate[]): this\n where(...predicates: Predicate[]): this\n where(...predicates: (Predicate | Predicate[])[]) {\n this._predicates.push(...predicates.flat())\n return this\n }\n\n /**\n * Returns the data-selection parameters forwarded to the query engine.\n * Subclasses decide which parts of an entity are fetched.\n */\n protected abstract selectionParams(): SelectionParams\n\n /**\n * Builds a single result entity from a raw RPC entity. Subclasses decide the produced shape\n * (a full {@link Entity}, or a projected object inferred from the selection).\n */\n protected abstract projectEntity(rpcEntity: RpcEntity): TEntity | Promise<TEntity>\n\n /**\n * Fetches the entities from the query.\n * It will return a QueryResult instance which can be used to fetch the next and previous pages.\n * @returns The QueryResult instance {@link QueryResult}\n *\n * @example\n * const builder = client.select()\n * const result = await builder.where(eq(\"name\", \"John\")).fetch()\n * // result = { entities: [Entity, Entity, Entity], next: async () => QueryResult, previous: async () => QueryResult }\n */\n async fetch(): Promise<QueryResult<TEntity>> {\n const queryResult = await processQuery(this._client, {\n predicates: this._predicates,\n limit: this._limit,\n cursor: this._cursor,\n ownedBy: this._ownedBy,\n createdBy: this._createdBy,\n orderBy: this._orderBy,\n validAtBlock: this._validAtBlock,\n ...this.selectionParams(),\n })\n\n const entities = await Promise.all(queryResult.data.map((entity) => this.projectEntity(entity)))\n\n this.cursor(queryResult.cursor)\n this.validAtBlock(BigInt(queryResult.blockNumber ?? 0))\n\n return new QueryResult<TEntity>(entities, this, this._cursor, this._limit, this._validAtBlock)\n }\n\n /**\n * Counts the entities from the query.\n * @returns The number of entities\n *\n * @example\n * const builder = client.select()\n * const result = await builder.where(eq(\"name\", \"John\")).count()\n * // result = 10\n */\n async count() {\n const queryResult = await processQuery(this._client, {\n predicates: this._predicates,\n limit: this._limit,\n cursor: this._cursor,\n ownedBy: this._ownedBy,\n createdBy: this._createdBy,\n orderBy: undefined,\n validAtBlock: this._validAtBlock,\n withAttributes: false,\n withMetadata: false,\n withPayload: false,\n })\n\n return queryResult.data.length ?? 0\n }\n}\n\n/**\n * QueryBuilder is a helper class to build queries to the Arkiv DBChains.\n * It can be used to fetch entities from the Arkiv DBChains. It follows the Builder pattern allowing chaining of methods.\n *\n * By default the result includes only the entity `key`. Additional data is opt-in through\n * `withAttributes()`, `withMetadata()` and `withPayload()`.\n *\n * @deprecated Use {@link SelectQueryBuilder} via `client.select()` instead. Declaring the\n * selection up front avoids the common mistake of forgetting to opt in to data and getting back\n * entities with only their `key` populated. This class remains for backwards compatibility and\n * will be removed in a future release.\n *\n * @param client - The Arkiv client\n * @returns The QueryBuilder instance {@link QueryBuilder}\n */\nexport class QueryBuilder extends BaseQueryBuilder<Entity> {\n private _withAttributes: boolean | undefined\n private _withMetadata: boolean | undefined\n private _withPayload: boolean | undefined\n\n /**\n * Sets the withAttributes flag which will return the attributes for the entities if true\n * @param withAttributes - The boolean value to set\n * @returns The QueryBuilder instance\n *\n * @example\n * const builder = client.buildQuery()\n * builder.withAttributes(true)\n */\n withAttributes(withAttributes: boolean = true): this {\n this._withAttributes = withAttributes\n return this\n }\n\n /**\n * Sets the withMetadata flag which will return the metadata (like owner, expiredAt, etc.) for the entities if true\n * @param withMetadata - The boolean value to set\n * @returns The QueryBuilder instance\n *\n * @example\n * const builder = client.buildQuery()\n * builder.withMetadata(true)\n */\n withMetadata(withMetadata: boolean = true): this {\n this._withMetadata = withMetadata\n return this\n }\n\n /**\n * Sets the withPayload flag which will return the payload for the entities if true\n * @param withPayload - The boolean value to set\n * @returns The QueryBuilder instance\n *\n * @example\n * const builder = client.buildQuery()\n * builder.withPayload(true)\n */\n withPayload(withPayload: boolean = true): this {\n this._withPayload = withPayload\n return this\n }\n\n protected selectionParams(): SelectionParams {\n return {\n withAttributes: this._withAttributes,\n withMetadata: this._withMetadata,\n withPayload: this._withPayload,\n }\n }\n\n protected projectEntity(rpcEntity: RpcEntity): Promise<Entity> {\n return entityFromRpcResult(rpcEntity)\n }\n}\n\n/**\n * SelectQueryBuilder is the recommended query builder. It requires the selection to be declared\n * up front, so results always contain exactly the data you asked for — and the type of each\n * returned entity is narrowed to exactly the selected fields.\n *\n * The selection is fixed at construction time and is flat — each field maps to an entity field.\n * Create one via `client.select(...)` rather than constructing it directly, so the result type is\n * inferred from the selection.\n *\n * @typeParam TEntity - The projected entity shape, inferred from the selection by `client.select()`.\n *\n * @example\n * // everything\n * await client.select().where(eq(\"name\", \"John\")).fetch()\n * await client.select(\"*\").where(eq(\"name\", \"John\")).fetch()\n * // specific fields\n * await client.select({ owner: true, attributes: true }).fetch()\n * // a single field — result is typed (flat) { owner: Hex }\n * await client.select({ owner: true }).fetch()\n */\nexport class SelectQueryBuilder<TEntity> extends BaseQueryBuilder<TEntity> {\n private _includeData: RpcIncludeData\n\n constructor(client: ArkivClient, selection?: SelectArg) {\n super(client)\n this._includeData = selectionToIncludeData(selection)\n }\n\n protected selectionParams(): SelectionParams {\n return { includeData: this._includeData }\n }\n\n protected async projectEntity(rpcEntity: RpcEntity): Promise<TEntity> {\n // The runtime value is a full Entity (with methods); the static type is narrowed to the\n // selected fields via `client.select()`'s inference.\n return (await entityFromRpcResult(rpcEntity)) as unknown as TEntity\n }\n}\n"],"mappings":";;;;AAAA,MAAM,iBAAiB;AAMvB,SAAS,cAAsB;AAC7B,KAAI,OAAO,YAAY,aAAa;EAClC,MAAM,WAAW,SAAS,KAAK;AAC/B,MAAI,SACF,QAAO;;AAIX,KAAI,OAAO,eAAe,eAAe,kBAAkB,WACzD,KAAI;AAEF,SADiB,WAA0C,cAC3C,QAAQ,QAAQ,IAAI;SAC9B;AAIV,QAAO;;AAIT,SAAS,eAAe,WAAmB,SAA0B;AAEnE,KAAI,YAAY,UAAW,QAAO;AAGlC,KAAI,QAAQ,SAAS,IAAI,EAAE;EACzB,MAAM,SAAS,QAAQ,MAAM,GAAG,GAAG;AACnC,SAAO,UAAU,WAAW,OAAO;;AAIrC,KAAI,QAAQ,WAAW,IAAI,CAEzB,QAAO,CAAC,eAAe,WADA,QAAQ,MAAM,EAAE,CACU;AAGnD,QAAO;;AAIT,SAAS,UAAU,WAA4B;CAC7C,MAAM,WAAW,aAAa;AAC9B,KAAI,CAAC,SAAU,QAAO;CAGtB,MAAM,WAAW,SAAS,MAAM,SAAS,CAAC,QAAQ,MAAM,EAAE,SAAS,EAAE;AAGrE,KAAI,SAAS,WAAW,EAAG,QAAO;CAGlC,IAAI,UAAU;AACd,MAAK,MAAM,WAAW,SACpB,KAAI,QAAQ,WAAW,IAAI,EAEzB;MAAI,eAAe,WAAW,QAAQ,CACpC,QAAO;YAEA,eAAe,WAAW,QAAQ,CAC3C,WAAU;AAId,QAAO;;AAIT,MAAMA,oCAAiC,IAAI,KAAK;AAChD,MAAMC,qCAAkC,IAAI,KAAK;AAGjD,MAAM,gBAAgB;CACpB;CACA;CACA;C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Ae,EAAE,CAAC;AAEvD,SAAO,IAAI,YAAqB,UAAU,MAAM,KAAK,SAAS,KAAK,QAAQ,KAAK,cAAc;;;;;;;;;;;CAYhG,MAAM,QAAQ;AAcZ,UAboB,MAAM,aAAa,KAAK,SAAS;GACnD,YAAY,KAAK;GACjB,OAAO,KAAK;GACZ,QAAQ,KAAK;GACb,SAAS,KAAK;GACd,WAAW,KAAK;GAChB,SAAS;GACT,cAAc,KAAK;GACnB,gBAAgB;GAChB,cAAc;GACd,aAAa;GACd,CAAC,EAEiB,KAAK,UAAU;;;;;;;;;;;;;;;;;;AAmBtC,IAAa,eAAb,cAAkC,iBAAyB;CACzD,AAAQ;CACR,AAAQ;CACR,AAAQ;;;;;;;;;;CAWR,eAAe,iBAA0B,MAAY;AACnD,OAAK,kBAAkB;AACvB,SAAO;;;;;;;;;;;CAYT,aAAa,eAAwB,MAAY;AAC/C,OAAK,gBAAgB;AACrB,SAAO;;;;;;;;;;;CAYT,YAAY,cAAuB,MAAY;AAC7C,OAAK,eAAe;AACpB,SAAO;;CAGT,AAAU,kBAAmC;AAC3C,SAAO;GACL,gBAAgB,KAAK;GACrB,cAAc,KAAK;GACnB,aAAa,KAAK;GACnB;;CAGH,AAAU,cAAc,WAAuC;AAC7D,SAAO,oBAAoB,UAAU;;;;;;;;;;;;;;;;;;;;;;;AAwBzC,IAAa,qBAAb,cAAiD,iBAA0B;CACzE,AAAQ;CAER,YAAY,QAAqB,WAAuB;AACtD,QAAM,OAAO;AACb,OAAK,eAAe,uBAAuB,UAAU;;CAGvD,AAAU,kBAAmC;AAC3C,SAAO,EAAE,aAAa,KAAK,cAAc;;CAG3C,MAAgB,cAAc,WAAwC;AAGpE,SAAQ,MAAM,oBAAoB,UAAU"}
|
|
@@ -400,6 +400,10 @@ function selectionToIncludeData(selection) {
|
|
|
400
400
|
* @param attributeType - The type of the attribute to order by (string or number)
|
|
401
401
|
* @returns Input for orderBy method
|
|
402
402
|
*
|
|
403
|
+
* @deprecated Server-side ordering is not supported by the network, so `orderBy` (and this
|
|
404
|
+
* helper) have no effect on the returned order. Sort the fetched entities in JavaScript
|
|
405
|
+
* instead (e.g. `entities.sort(...)`). This function will be removed in a future release.
|
|
406
|
+
*
|
|
403
407
|
* @example
|
|
404
408
|
* const ascAttribute = asc("name", "string")
|
|
405
409
|
*/
|
|
@@ -416,6 +420,10 @@ function asc(attributeName, attributeType) {
|
|
|
416
420
|
* @param attributeType - The type of the attribute to order by (string or number)
|
|
417
421
|
* @returns Input for orderBy method
|
|
418
422
|
*
|
|
423
|
+
* @deprecated Server-side ordering is not supported by the network, so `orderBy` (and this
|
|
424
|
+
* helper) have no effect on the returned order. Sort the fetched entities in JavaScript
|
|
425
|
+
* instead (e.g. `entities.sort(...)`). This function will be removed in a future release.
|
|
426
|
+
*
|
|
419
427
|
* @example
|
|
420
428
|
* const descAttribute = desc("name", "string")
|
|
421
429
|
*/
|
package/dist/types/index.d.cts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { A as RpcIncludeData, C as QueryOptionsIncludeData, E as GetBlockTimingReturnType, M as RpcQueryOptions, N as MimeType, O as ArkivRpcSchema, S as QueryOptions, T as QueryReturnType, _ as DeleteEntityReturnType, a as OnEntityExpiredEvent, b as ChangeOwnershipParameters, c as OnEntityUpdatedEvent, d as MutateEntitiesReturnType, f as UpdateEntityParameters, g as DeleteEntityParameters, h as ExtendEntityReturnType, i as OnEntityDeletedEvent, j as RpcOrderByAttribute, k as RpcEntity, l as Attribute, m as ExtendEntityParameters, n as TxParams, o as OnEntityExpiresInExtendedEvent, p as UpdateEntityReturnType, r as OnEntityCreatedEvent, s as OnEntityOwnerChangedEvent, t as Entity, u as MutateEntitiesParameters, v as CreateEntityParameters, w as QueryOptionsOrderBy, x as ChangeOwnershipReturnType, y as CreateEntityReturnType } from "../entity-
|
|
1
|
+
import { A as RpcIncludeData, C as QueryOptionsIncludeData, E as GetBlockTimingReturnType, M as RpcQueryOptions, N as MimeType, O as ArkivRpcSchema, S as QueryOptions, T as QueryReturnType, _ as DeleteEntityReturnType, a as OnEntityExpiredEvent, b as ChangeOwnershipParameters, c as OnEntityUpdatedEvent, d as MutateEntitiesReturnType, f as UpdateEntityParameters, g as DeleteEntityParameters, h as ExtendEntityReturnType, i as OnEntityDeletedEvent, j as RpcOrderByAttribute, k as RpcEntity, l as Attribute, m as ExtendEntityParameters, n as TxParams, o as OnEntityExpiresInExtendedEvent, p as UpdateEntityReturnType, r as OnEntityCreatedEvent, s as OnEntityOwnerChangedEvent, t as Entity, u as MutateEntitiesParameters, v as CreateEntityParameters, w as QueryOptionsOrderBy, x as ChangeOwnershipReturnType, y as CreateEntityReturnType } from "../entity-B6g_EPm1.cjs";
|
|
2
2
|
export { ArkivRpcSchema, Attribute, ChangeOwnershipParameters, ChangeOwnershipReturnType, CreateEntityParameters, CreateEntityReturnType, DeleteEntityParameters, DeleteEntityReturnType, Entity, ExtendEntityParameters, ExtendEntityReturnType, GetBlockTimingReturnType, MimeType, MutateEntitiesParameters, MutateEntitiesReturnType, OnEntityCreatedEvent, OnEntityDeletedEvent, OnEntityExpiredEvent, OnEntityExpiresInExtendedEvent, OnEntityOwnerChangedEvent, OnEntityUpdatedEvent, QueryOptions, QueryOptionsIncludeData, QueryOptionsOrderBy, QueryReturnType, RpcEntity, RpcIncludeData, RpcOrderByAttribute, RpcQueryOptions, TxParams, UpdateEntityParameters, UpdateEntityReturnType };
|