Skip to content

Added useFlowQueryRaw hook #2523

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 6 commits into from
Jun 19, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions .changeset/wicked-bikes-peel.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
"@onflow/fcl-core": minor
"@onflow/fcl": minor
"@onflow/kit": minor
---

Added useFlowQueryRaw hook to execute a query and get non-decoded data as result.
55 changes: 55 additions & 0 deletions packages/fcl-core/src/exec/query-raw.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
import * as sdk from "@onflow/sdk"
import type {ArgsFn} from "./args"
import {normalizeArgs} from "./utils/normalize-args"
import {preQuery} from "./utils/pre"
import {prepTemplateOpts} from "./utils/prep-template-opts"

export interface QueryOptions {
cadence?: string
args?: ArgsFn
template?: any
isSealed?: boolean
limit?: number
}

/**
* @description Allows you to submit scripts to query the blockchain and get raw response data.
*
* @param opts Query Options and configuration
* @param opts.cadence Cadence Script used to query Flow
* @param opts.args Arguments passed to cadence script
* @param opts.template Interaction Template for a script
* @param opts.isSealed Block Finality
* @param opts.limit Compute Limit for Query
* @returns A promise that resolves to the raw query result
*
* @example
* const cadence = `
* cadence: `
* access(all) fun main(a: Int, b: Int, c: Address): Int {
* log(c)
* return a + b
* }
* `.trim()
*
* const args = (arg, t) => [
* arg(5, t.Int),
* arg(7, t.Int),
* arg("0xb2db43ad6bc345fec9", t.Address),
* ]
*
* await queryRaw({ cadence, args })
*/
export async function queryRaw(opts: QueryOptions = {}): Promise<any> {
await preQuery(opts)
opts = await prepTemplateOpts(opts)

return sdk.send([
sdk.script(opts.cadence!),
sdk.args(normalizeArgs(opts.args || [])),
sdk.atLatestBlock(opts.isSealed ?? false),
opts.limit &&
typeof opts.limit === "number" &&
(sdk.limit(opts.limit!) as any),
])
}
48 changes: 0 additions & 48 deletions packages/fcl-core/src/exec/query.js

This file was deleted.

34 changes: 34 additions & 0 deletions packages/fcl-core/src/exec/query.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import * as sdk from "@onflow/sdk"
import {QueryOptions, queryRaw} from "./query-raw"

/**
* @description Allows you to submit scripts to query the blockchain.
*
* @param opts Query Options and configuration
* @param opts.cadence Cadence Script used to query Flow
* @param opts.args Arguments passed to cadence script
* @param opts.template Interaction Template for a script
* @param opts.isSealed Block Finality
* @param opts.limit Compute Limit for Query
* @returns A promise that resolves to the query result
*
* @example
* const cadence = `
* cadence: `
* access(all) fun main(a: Int, b: Int, c: Address): Int {
* log(c)
* return a + b
* }
* `.trim()
*
* const args = (arg, t) => [
* arg(5, t.Int),
* arg(7, t.Int),
* arg("0xb2db43ad6bc345fec9", t.Address),
* ]
*
* await query({ cadence, args })
*/
export async function query(opts: QueryOptions = {}): Promise<any> {
return queryRaw(opts).then(sdk.decode)
}
1 change: 1 addition & 0 deletions packages/fcl-core/src/fcl-core.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
export {VERSION} from "./VERSION"
export {query} from "./exec/query"
export {queryRaw} from "./exec/query-raw"
export {verifyUserSignatures} from "./exec/verify"
export {serialize} from "./serialize"
export {transaction as tx, TransactionError} from "./transaction"
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import {config, invariant} from "@onflow/sdk"
import {log, LEVELS} from "@onflow/util-logger"
import {query} from "../exec/query.js"
import {query} from "../exec/query"
import {generateTemplateId} from "./generate-template-id/generate-template-id.js"
import {getChainId} from "../utils"

Expand Down
1 change: 1 addition & 0 deletions packages/fcl/src/fcl.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
export {
VERSION,
query,
queryRaw,
verifyUserSignatures,
serialize,
tx,
Expand Down
1 change: 1 addition & 0 deletions packages/kit/src/__mocks__/fcl.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ export default {
events: jest.fn(),
mutate: jest.fn(),
query: jest.fn(),
queryRaw: jest.fn(),
tx: jest.fn(),
config: () => ({
subscribe: sharedSubscribe,
Expand Down
1 change: 1 addition & 0 deletions packages/kit/src/hooks/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ export {useFlowConfig} from "./useFlowConfig"
export {useFlowEvents} from "./useFlowEvents"
export {useFlowMutate} from "./useFlowMutate"
export {useFlowQuery} from "./useFlowQuery"
export {useFlowQueryRaw} from "./useFlowQueryRaw"
export {useFlowRevertibleRandom} from "./useFlowRevertibleRandom"
export {useCrossVmBatchTransaction} from "./useCrossVmBatchTransaction"
export {useCrossVmTokenBalance} from "./useCrossVmTokenBalance"
Expand Down
53 changes: 52 additions & 1 deletion packages/kit/src/hooks/useFlowQuery.test.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import {renderHook, act, waitFor} from "@testing-library/react"
import * as fcl from "@onflow/fcl"
import {FlowProvider} from "../provider"
import {useFlowQuery} from "./useFlowQuery"
import {useFlowQuery, encodeQueryArgs} from "./useFlowQuery"

jest.mock("@onflow/fcl", () => require("../__mocks__/fcl").default)

Expand Down Expand Up @@ -183,4 +183,55 @@ describe("useFlowQuery", () => {

await waitFor(() => expect(hookResult.current.data).toEqual(updatedResult))
})

describe("encodeQueryArgs", () => {
beforeEach(() => {
// Clear mocks
jest.clearAllMocks()
})

test("returns undefined when args is undefined", () => {
const result = encodeQueryArgs(undefined)
expect(result).toBeUndefined()
})

test("returns undefined when args is null", () => {
const result = encodeQueryArgs(null as any)
expect(result).toBeUndefined()
})

test("encodes single argument correctly", () => {
const argsFunction = (arg: typeof fcl.arg, t: typeof fcl.t) => [
arg("42", t.Int),
]

const result = encodeQueryArgs(argsFunction)

expect(result).toEqual([{type: "Int", value: "42"}])
})

test("encodes multiple arguments correctly", () => {
const argsFunction = (arg: typeof fcl.arg, t: typeof fcl.t) => [
arg("42", t.Int),
arg("hello", t.String),
arg("0x1234567890abcdef", t.Address),
]

const result = encodeQueryArgs(argsFunction)

expect(result).toEqual([
{type: "Int", value: "42"},
{type: "String", value: "hello"},
{type: "Address", value: "0x1234567890abcdef"},
])
})

test("handles empty args array", () => {
const argsFunction = (arg: typeof fcl.arg, t: typeof fcl.t) => []

const result = encodeQueryArgs(argsFunction)

expect(result).toEqual([])
})
})
})
15 changes: 9 additions & 6 deletions packages/kit/src/hooks/useFlowQuery.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,14 @@ import {useQuery, UseQueryResult, UseQueryOptions} from "@tanstack/react-query"
import {useCallback} from "react"
import {useFlowQueryClient} from "../provider/FlowQueryClient"

export function encodeQueryArgs(
args?: (arg: typeof fcl.arg, t: typeof fcl.t) => unknown[]
): any[] | undefined {
// Encode the arguments to a JSON-CDC object so they can be deterministically
// serialized and used as the query key.
return args?.(fcl.arg, fcl.t)?.map((x: any) => x.xform.asArgument(x.value))
}

export interface UseFlowQueryArgs {
cadence: string
args?: (arg: typeof fcl.arg, t: typeof fcl.t) => unknown[]
Expand Down Expand Up @@ -32,12 +40,7 @@ export function useFlowQuery({
return fcl.query({cadence, args})
}, [cadence, args])

// Encode the arguments to a JSON-CDC object so they can be deterministically
// serialized and used as the query key.
const encodedArgs = args?.(fcl.arg, fcl.t)?.map((x: any) =>
x.xform.asArgument(x.value)
)

const encodedArgs = encodeQueryArgs(args)
return useQuery<unknown, Error>(
{
queryKey: ["flowQuery", cadence, encodedArgs],
Expand Down
Loading