Skip to content

Add useCrossVmSpendNft hook #2460

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 13 commits into from
Jun 6, 2025
Merged
Show file tree
Hide file tree
Changes from 12 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
5 changes: 5 additions & 0 deletions .changeset/tiny-rabbits-try.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@onflow/kit": minor
---

Add `useCrossVmSpendNft` hook
12 changes: 12 additions & 0 deletions packages/kit/src/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,19 +2,31 @@ export const CONTRACT_ADDRESSES = {
testnet: {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Are we doing emulator or pushing that once we figure out how to solve it better?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yup, once the changes have been pushed thru to the CLI we can do the emulator but right now the VM bridge doesn't deploy.

EVM: "0x8c5303eaa26202d6",
FungibleToken: "0x9a0766d93b6608b7",
NonFungibleToken: "0x631e88ae7f1d7c20",
ViewResolver: "0x631e88ae7f1d7c20",
MetadataViews: "0x631e88ae7f1d7c20",
FlowToken: "0x7e60df042a9c0868",
ScopedFTProviders: "0xdfc20aee650fcbdf",
FlowEVMBridge: "0xdfc20aee650fcbdf",
FlowEVMBridgeUtils: "0xdfc20aee650fcbdf",
FlowEVMBridgeConfig: "0xdfc20aee650fcbdf",
FungibleTokenMetadataViews: "0x9a0766d93b6608b7",
},
mainnet: {
EVM: "0xe467b9dd11fa00df",
FungibleToken: "0xf233dcee88fe0abe",
NonFungibleToken: "0x1d7e57aa55817448",
ViewResolver: "0x1d7e57aa55817448",
MetadataViews: "0x1d7e57aa55817448",
FlowToken: "0x1654653399040a61",
ScopedFTProviders: "0x1e4aa0b87d10b141",
FlowEVMBridge: "0x1e4aa0b87d10b141",
FlowEVMBridgeUtils: "0x1e4aa0b87d10b141",
FlowEVMBridgeConfig: "0x1e4aa0b87d10b141",
FungibleTokenMetadataViews: "0xf233dcee88fe0abe",
},
}

export const CADENCE_UFIX64_PRECISION = 8

export const DEFAULT_EVM_GAS_LIMIT = "15000000"
12 changes: 6 additions & 6 deletions packages/kit/src/hooks/useCrossVmBatchTransaction.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,12 +56,12 @@ describe("useBatchEvmTransaction", () => {
const result = encodeCalls(mockCalls as any)

expect(result).toEqual([
[
{key: "to", value: "0x123"},
{key: "data", value: ""},
{key: "gasLimit", value: "100000"},
{key: "value", value: "0"},
],
{
to: "0x123",
data: "",
gasLimit: "100000",
value: "0",
},
])
})
})
Expand Down
42 changes: 25 additions & 17 deletions packages/kit/src/hooks/useCrossVmBatchTransaction.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,9 @@ import {
} from "@tanstack/react-query"
import {useFlowChainId} from "./useFlowChainId"
import {useFlowQueryClient} from "../provider/FlowQueryClient"
import {DEFAULT_EVM_GAS_LIMIT} from "../constants"

interface useCrossVmBatchTransactionArgs {
export interface UseCrossVmBatchTransactionArgs {
mutation?: Omit<
UseMutationOptions<
{
Expand All @@ -26,7 +27,7 @@ interface useCrossVmBatchTransactionArgs {
>
}

interface useCrossVmBatchTransactionResult
export interface UseCrossVmBatchTransactionResult
extends Omit<
UseMutationResult<
{
Expand Down Expand Up @@ -57,7 +58,7 @@ interface useCrossVmBatchTransactionResult
}>
}

interface EvmBatchCall {
export interface EvmBatchCall {
// The target EVM contract address (as a string)
address: string
// The contract ABI fragment
Expand All @@ -71,13 +72,14 @@ interface EvmBatchCall {
// The value to send with the call
value?: bigint
}
interface CallOutcome {

export interface CallOutcome {
status: "passed" | "failed" | "skipped"
hash?: string
errorMessage?: string
}

type EvmTransactionExecutedData = {
export interface EvmTransactionExecutedData {
hash: string[]
index: string
type: string
Expand All @@ -93,25 +95,23 @@ type EvmTransactionExecutedData = {
stateUpdateChecksum: string
}

// Helper to encode our ca lls using viem.
// Returns an array of objects with keys "address" and "data" (hex-encoded string without the "0x" prefix).
export function encodeCalls(
calls: EvmBatchCall[]
): Array<Array<{key: string; value: string}>> {
): Array<{to: string; data: string; gasLimit: string; value: string}> {
return calls.map(call => {
const encodedData = encodeFunctionData({
abi: call.abi,
functionName: call.functionName,
args: call.args,
})

return [
{key: "to", value: call.address},
{key: "data", value: fcl.sansPrefix(encodedData) ?? ""},
{key: "gasLimit", value: call.gasLimit?.toString() ?? "15000000"},
{key: "value", value: call.value?.toString() ?? "0"},
]
}) as any
return {
to: call.address,
data: fcl.sansPrefix(encodedData) ?? "",
gasLimit: call.gasLimit?.toString() ?? DEFAULT_EVM_GAS_LIMIT,
value: call.value?.toString() ?? "0",
}
})
}

const EVM_CONTRACT_ADDRESSES = {
Expand Down Expand Up @@ -178,7 +178,7 @@ transaction(calls: [{String: AnyStruct}], mustPass: Bool) {
*/
export function useCrossVmBatchTransaction({
mutation: mutationOptions = {},
}: useCrossVmBatchTransactionArgs = {}): useCrossVmBatchTransactionResult {
}: UseCrossVmBatchTransactionArgs = {}): UseCrossVmBatchTransactionResult {
const chainId = useFlowChainId()
const cadenceTx = chainId.data
? getCadenceBatchTransaction(chainId.data)
Expand All @@ -203,7 +203,15 @@ export function useCrossVmBatchTransaction({
cadence: cadenceTx,
args: (arg, t) => [
arg(
encodedCalls,
encodedCalls.map(call => [
{key: "to", value: call.to},
{key: "data", value: call.data},
{
key: "gasLimit",
value: call.gasLimit,
},
{key: "value", value: call.value},
]),
t.Array(
t.Dictionary([
{key: t.String, value: t.String},
Expand Down
171 changes: 171 additions & 0 deletions packages/kit/src/hooks/useCrossVmSpendNft.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,171 @@
import {renderHook, act, waitFor} from "@testing-library/react"
import * as fcl from "@onflow/fcl"
import {FlowProvider} from "../provider"
import {
getCrossVmSpendNftransaction,
useCrossVmSpendNft,
} from "./useCrossVmSpendNft"
import {useFlowChainId} from "./useFlowChainId"

jest.mock("@onflow/fcl", () => require("../__mocks__/fcl").default)
jest.mock("viem", () => ({
encodeFunctionData: jest.fn(),
bytesToHex: jest.fn(x => `0x${x}`),
}))
jest.mock("./useFlowChainId", () => ({
useFlowChainId: jest.fn(),
}))

describe("useBatchEvmTransaction", () => {
const mockCalls = [
{
address: "0x123",
abi: [{type: "function", name: "test"}],
functionName: "test",
args: [1, 2],
gasLimit: BigInt(100000),
value: BigInt(0),
},
]

const mockTxId = "0x123"
const mockTxResult = {
events: [
{
type: "TransactionExecuted",
data: {
hash: ["1", "2", "3"],
errorCode: "0",
errorMessage: "",
},
},
],
}

beforeEach(() => {
jest.clearAllMocks()
jest.mocked(useFlowChainId).mockReturnValue({
data: "mainnet",
isLoading: false,
} as any)
})

describe("getCrossVmSpendNftTransaction", () => {
it("should return correct cadence for mainnet", () => {
const result = getCrossVmSpendNftransaction("mainnet")
expect(result).toContain("import EVM from 0xe467b9dd11fa00df")
})

it("should return correct cadence for testnet", () => {
const result = getCrossVmSpendNftransaction("testnet")
expect(result).toContain("import EVM from 0x8c5303eaa26202d6")
})

it("should throw error for unsupported chain", () => {
expect(() => getCrossVmSpendNftransaction("unsupported")).toThrow(
"Unsupported chain: unsupported"
)
})
})

describe("useCrossVmBatchTransaction", () => {
test("should handle successful transaction", async () => {
jest.mocked(fcl.mutate).mockResolvedValue(mockTxId)
jest.mocked(fcl.tx).mockReturnValue({
onceExecuted: jest.fn().mockResolvedValue(mockTxResult),
} as any)

let result: any
let rerender: any
await act(async () => {
;({result, rerender} = renderHook(useCrossVmSpendNft, {
wrapper: FlowProvider,
}))
})

await act(async () => {
await result.current.spendNft({
calls: mockCalls,
nftIdentifier: "nft123",
nftIds: ["1", "2"],
})
rerender()
})

await waitFor(() => result.current.isPending === false)

expect(result.current.isError).toBe(false)
expect(result.current.data).toBe(mockTxId)
})

it("should handle missing chain ID", async () => {
;(useFlowChainId as jest.Mock).mockReturnValue({
data: null,
isLoading: false,
})

let hookResult: any

await act(async () => {
const {result} = renderHook(() => useCrossVmSpendNft(), {
wrapper: FlowProvider,
})
hookResult = result
})

await act(async () => {
await hookResult.current.spendNft({calls: mockCalls})
})

await waitFor(() => expect(hookResult.current.isError).toBe(true))
expect(hookResult.current.error?.message).toBe("No current chain found")
})

it("should handle loading chain ID", async () => {
;(useFlowChainId as jest.Mock).mockReturnValue({
data: null,
isLoading: true,
})

let hookResult: any

await act(async () => {
const {result} = renderHook(() => useCrossVmSpendNft(), {
wrapper: FlowProvider,
})
hookResult = result
})

await act(async () => {
await hookResult.current.spendNft(mockCalls)
})

await waitFor(() => expect(hookResult.current.isError).toBe(true))
expect(hookResult.current.error?.message).toBe("No current chain found")
})

it("should handle mutation error", async () => {
;(fcl.mutate as jest.Mock).mockRejectedValue(new Error("Mutation failed"))

let hookResult: any

await act(async () => {
const {result} = renderHook(() => useCrossVmSpendNft(), {
wrapper: FlowProvider,
})
hookResult = result
})

await act(async () => {
await hookResult.current.spendNft({
calls: mockCalls,
nftIdentifier: "nft123",
nftIds: ["1", "2"],
})
})

await waitFor(() => expect(hookResult.current.isError).toBe(true))
expect(hookResult.current.error?.message).toBe("Mutation failed")
})
})
})
Loading