Skip to content
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

Fix mutation parameters when using Zod #21

Merged
merged 8 commits into from
Apr 29, 2024
Merged
Show file tree
Hide file tree
Changes from 6 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
72 changes: 36 additions & 36 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 2 additions & 2 deletions packages/data-facade/src/facade.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,11 +32,11 @@ function handlerQueryBuilder<TResolver extends ResolverFunc>(

function buildUseMutation() {
return <TResolver extends ResolverFunc>(resolver: TResolver) => ({
useMutation: (opts?: UseMutationOptions<Awaited<ReturnType<TResolver>>, Error, unknown, unknown>) => {
useMutation: (opts?: UseMutationOptions<Awaited<ReturnType<TResolver>>, Error, Parameters<TResolver>[0], unknown>) => {
return useMutation<
Awaited<ReturnType<TResolver>>,
Error,
unknown,
Parameters<TResolver>[0],
unknown
>({
...opts,
Expand Down
4 changes: 3 additions & 1 deletion packages/data-facade/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,9 @@ export type HandlerQueryBuilderReturn<TResolver extends ResolverFunc> = (
type UseMutationType<
TResolver extends ResolverFunc,
TReturn = Awaited<ReturnType<TResolver>>,
> = (opts?: UseMutationOptions<TReturn, Error, unknown, unknown>) => UseMutationResult<TReturn>;
> = Parameters<TResolver>["length"] extends 0
? (opts?: UseMutationOptions<TReturn, Error, null | undefined, unknown>) => UseMutationResult<TReturn>
: (opts?: UseMutationOptions<TReturn, Error, Parameters<TResolver>[0], unknown>) => UseMutationResult<TReturn>

export type HandlerMutationBuilderReturn<TResolver extends ResolverFunc> =
() => {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
package expo.modules.ironfishnativemodule

import expo.modules.kotlin.records.Field
import expo.modules.kotlin.modules.Module
import expo.modules.kotlin.modules.ModuleDefinition
import expo.modules.kotlin.records.Record

class ExpoKey(
@Field
Expand All @@ -28,7 +30,7 @@ class IronfishNativeModule : Module() {
// The module will be accessible from `requireNativeModule('IronfishNativeModule')` in JavaScript.
Name("IronfishNativeModule")

AsyncFunction("generateKey") { ->
Function("generateKey") { ->
val k = uniffi.rust_lib.generateKey()

ExpoKey(
Expand All @@ -41,25 +43,15 @@ class IronfishNativeModule : Module() {
)
}

Function("spendingKeyToWords") { privateKey: String, languageCode: Long ->
try {
return spendingKeyToWords(privateKey: privateKey, languageCode: languageCode)
} catch (error: Exception) {
error.printStackTrace()
throw error
}
Function("spendingKeyToWords") { privateKey: String, languageCode: Int ->
uniffi.rust_lib.spendingKeyToWords(privateKey, languageCode)
}

Function("wordsToSpendingKey") { words: String, languageCode: Long ->
try {
return wordsToSpendingKey(words: words, languageCode: languageCode)
} catch (error: Exception) {
error.printStackTrace()
throw error
}
Function("wordsToSpendingKey") { words: String, languageCode: Int ->
uniffi.rust_lib.wordsToSpendingKey(words, languageCode)
}

AsyncFunction("generateKeyFromPrivateKey") { privateKey: String ->
Function("generateKeyFromPrivateKey") { privateKey: String ->
val k = uniffi.rust_lib.generateKeyFromPrivateKey(privateKey)

ExpoKey(
Expand All @@ -73,12 +65,7 @@ class IronfishNativeModule : Module() {
}

Function("isValidPublicAddress") { hexAddress: String ->
try {
uniffi.rust_lib.isValidPublicAddress(hexAddress: hexAddress)
} catch (error: Exception) {
error.printStackTrace()
throw error
}
uniffi.rust_lib.isValidPublicAddress(hexAddress)
}
}
}
37 changes: 36 additions & 1 deletion packages/mobile-app/app/(tabs)/transact.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ import { View, Text, ScrollView, TextInput } from "react-native";
import { useFacade } from "../../data/facades";
import { Button } from "@ironfish/ui";
import { useQueryClient } from "@tanstack/react-query";
import React from "react";
import { AccountFormat } from "@ironfish/sdk";

export default function Transact() {
const facade = useFacade();
Expand All @@ -15,8 +17,24 @@ export default function Transact() {
})
}
});
const importAccount = facade.importAccount.useMutation({
onSuccess: () => {
qc.invalidateQueries({
queryKey: ['getAccounts']
})
}
});
const removeAccount = facade.removeAccount.useMutation({
onSuccess: () => {
qc.invalidateQueries({
queryKey: ['getAccounts']
})
}
});
const exportAccount = facade.exportAccount.useMutation();

const [importAccountText, setImportAccountText] = React.useState('')

return (
<ScrollView>
<Text>Accounts</Text>
Expand All @@ -25,7 +43,15 @@ export default function Transact() {
<Text>{account.name}</Text>
<Button
onClick={async () => {
const otherResult = await exportAccount.mutateAsync({ name: account.name });
await removeAccount.mutateAsync({ name: account.name });
console.log('Removed Account', account.name)
}}
>
Remove Account
</Button>
<Button
onClick={async () => {
const otherResult = await exportAccount.mutateAsync({ name: account.name, format: AccountFormat.Base64Json });
console.log('Exported Account:', otherResult)
}}
>
Expand All @@ -41,6 +67,15 @@ export default function Transact() {
>
Create Account
</Button>
<TextInput value={importAccountText} onChangeText={setImportAccountText} placeholder="Import account"/>
<Button
onClick={async () => {
const otherResult = await importAccount.mutateAsync({ account: importAccountText });
console.log('Imported Account:', otherResult)
}}
>
Import Account
</Button>
</ScrollView>
);
}
67 changes: 58 additions & 9 deletions packages/mobile-app/data/facades/accounts/demoHandlers.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { f } from "data-facade";
import { z } from "zod";
import { AccountsMethods } from "./types";
import { AccountFormat, LanguageKey } from "@ironfish/sdk";

let ACCOUNTS = [
{ id: 0, name: "alice", viewOnlyAccount: "alice" },
Expand All @@ -14,11 +15,6 @@ async function getAccounts(limit: number) {
}

export const accountsHandlers = f.facade<AccountsMethods>({
getAccounts: f.handler.query(async () => {
const accounts = await getAccounts(ACCOUNTS.length);
console.log("getAccounts", accounts);
return accounts;
}),
createAccount: f.handler
.input(
z.object({
Expand All @@ -35,17 +31,70 @@ export const accountsHandlers = f.facade<AccountsMethods>({
ACCOUNTS.push(account);
return account;
}),
// The enums used when exporting are tricky to use with Zod
exportAccount: f.handler
.mutation(async ({ name }: { name: string, format: AccountFormat, language?: LanguageKey, viewOnly?: boolean }) => {
const account = ACCOUNTS.find((a) => a.name === name)
if (account === undefined) {
throw new Error(`No account found with name ${name}`);
}
return JSON.stringify(account);
}),
getAccount: f.handler.input(
z.object({
name: z.string(),
}),
).query(async ({ name }) => {
const account = ACCOUNTS.find((a) => a.name === name);
if (account === undefined) {
throw new Error(`No account found with name ${name}`);
}
return account
}),
getAccounts: f.handler.query(async () => {
const accounts = await getAccounts(ACCOUNTS.length);
console.log("getAccounts", accounts);
return accounts;
}),
importAccount: f.handler
.input(
z.object({
account: z.string(),
name: z.string(),
}),
)
.mutation(async ({ name }) => {
const account = ACCOUNTS.find((a) => a.name === name)
if (account === undefined) {
.mutation(async ({ account, name }) => {
const existingId = ACCOUNTS.at(-1)?.id
if (existingId === undefined) {
throw new Error("No accounts found");
}
return JSON.stringify(account);
const importedAccount = { id: existingId + 1, name, viewOnlyAccount: account }
console.log("createAccount", account);
ACCOUNTS.push(importedAccount);
return importedAccount;
}),
removeAccount: f.handler
.input(
z.object({
name: z.string(),
}),
)
.mutation(async ({ name }) => {
const accountIndex = ACCOUNTS.findIndex((a) => a.name === name);
ACCOUNTS.splice(accountIndex, 1);
}),
renameAccount: f.handler
.input(
z.object({
name: z.string(),
newName: z.string(),
}),
)
.mutation(async ({ name, newName }) => {
const account = ACCOUNTS.find((a) => a.name === name);
if (!account) {
throw new Error("No account found");
}
account.name = newName;
}),
});
Loading
Loading