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

Ready to release sdk version 0.2.9 #3034

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
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
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ type UsesignAndExecuteTransactionOptions = Omit<
'mutationFn'
>

export function UseSignAndExecuteTransaction({
export function useSignAndExecuteTransaction({
mutationKey,
...mutationOptions
}: UsesignAndExecuteTransactionOptions = {}): UseMutationResult<
Expand Down
17 changes: 17 additions & 0 deletions sdk/typescript/rooch-sdk-kit/src/hooks/useSession.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
// Copyright (c) RoochNetwork
// SPDX-License-Identifier: Apache-2.0

import { useSessionStore } from './useSessionsStore.js'

/**
* Retrieves the all session account
*/
export function useSession(scope: string) {
return useSessionStore((state) =>
state.sessions.find((item) =>
scope.includes('::')
? item.getScopes().find((_scope) => _scope === scope)
: item.getScopes().find((_scope) => _scope.startsWith(scope)) !== undefined,
),
)
}
2 changes: 1 addition & 1 deletion sdk/typescript/rooch-sdk-kit/src/hooks/useSessions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import { useSessionStore } from './useSessionsStore.js'
/**
* Retrieves the all session account
*/
export function useSession() {
export function useSessions() {
return useSessionStore((state) =>
state.sessions.sort((a, b) => b.getCreateTime() - a.getCreateTime()),
)
Expand Down
4 changes: 2 additions & 2 deletions sdk/typescript/rooch-sdk-kit/src/hooks/wallet/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,9 @@
export * from './useAddresses.js'
export * from './useAutoConnectWallet.js'
export * from './useConnectWallet.js'
export * from './useCurrentAccount.js'
export * from './useCurrentAddress.js'
export * from './useCurrentWallet.js'
export * from './useWalletCreateSession.js'
export * from './useWallets.js'
export * from './useWalletStore.js'
export * from './useWalletChanged.js'
export * from './useConnectionStatus.js'
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,9 @@
import { useQuery } from '@tanstack/react-query'
import { useLayoutEffect, useState } from 'react'

import {
useWalletStore,
useConnectWallet,
useWallets,
useCurrentWallet,
useCurrentAddress,
} from './index.js'
import { useConnectWallet, useWallets, useCurrentWallet, useCurrentAddress } from './index.js'

import { useWalletStore } from './useWalletStore'

export function useAutoConnectWallet(): 'disabled' | 'idle' | 'attempted' {
const { mutateAsync: connectWallet } = useConnectWallet()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import { useWalletStore } from './useWalletStore.js'
import { walletMutationKeys } from '../../constants/index.js'
import { Wallet } from '../../wellet/index.js'
import { useSessionStore } from '../useSessionsStore.js'
import { useSession } from '../useSessions.js'
import { useSessions } from '../useSessions.js'

type ConnectWalletArgs = {
wallet: Wallet
Expand All @@ -34,7 +34,7 @@ export function useConnectWallet({
ConnectWalletArgs,
unknown
> {
const sessions = useSession()
const sessions = useSessions()
const setCurrentSession = useSessionStore((state) => state.setCurrentSession)
const setWalletConnected = useWalletStore((state) => state.setWalletConnected)
const setWalletDisconnected = useWalletStore((state) => state.setWalletDisconnected)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
// Copyright (c) RoochNetwork
// SPDX-License-Identifier: Apache-2.0

import { useWalletStore } from './useWalletStore'

export function useConnectionStatus() {
return useWalletStore((state) => state.connectionStatus)
}
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
// Copyright (c) RoochNetwork
// SPDX-License-Identifier: Apache-2.0

import { useWalletStore } from './index.js'
import { useWalletStore } from './useWalletStore'

/**
* Retrieves all wallets
Expand Down
17 changes: 5 additions & 12 deletions sdk/typescript/rooch-sdk-kit/src/http/httpTransport.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,21 +5,17 @@ import {
RoochHTTPTransport,
RoochTransportRequestOptions,
RoochHTTPTransportOptions,
ErrorValidateInvalidAccountAuthKey,
ErrorValidateSessionIsExpired,
} from '@roochnetwork/rooch-sdk'

type SessionExpiredCallbackType = () => void

export class HTTPTransport extends RoochHTTPTransport {
private readonly sessionExpiredCallback: SessionExpiredCallbackType
private readonly requestErrorCallback: (code: number, msg: string) => void

constructor(
options: RoochHTTPTransportOptions,
sessionExpiredCallback: SessionExpiredCallbackType,
requestErrorCallback: (code: number, msg: string) => void,
) {
super(options)
this.sessionExpiredCallback = sessionExpiredCallback
this.requestErrorCallback = requestErrorCallback
}

async request<T>(input: RoochTransportRequestOptions): Promise<T> {
Expand All @@ -28,11 +24,8 @@ export class HTTPTransport extends RoochHTTPTransport {
result = await super.request(input)
return result
} catch (e: any) {
if (
'code' in e &&
(e.code === ErrorValidateInvalidAccountAuthKey || e.code === ErrorValidateSessionIsExpired)
) {
this.sessionExpiredCallback()
if ('code' in e) {
this.requestErrorCallback(e.code, e.message)
}
throw e
}
Expand Down
50 changes: 50 additions & 0 deletions sdk/typescript/rooch-sdk-kit/src/provider/errorProvider.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
// Copyright (c) RoochNetwork
// SPDX-License-Identifier: Apache-2.0

import { createContext, ReactNode, useContext, useMemo, useState } from 'react'

export type ErrorType = {
code: number
msg: string
}

export interface ErrorProviderContext {
error: ErrorType | null
setError: (error: ErrorType) => void
resolve: () => void
}

const ErrorContext = createContext<ErrorProviderContext | null>(null)

export const useError = () => {
const ctx = useContext(ErrorContext)!
return {
error: ctx.error,
resolve: ctx.resolve,
}
}

export const useSetError = () => {
const ctx = useContext(ErrorContext)!
return ctx.setError
}

export type ErrorProviderProps = {
children: ReactNode
}

export const ErrorProvider = (props: ErrorProviderProps) => {
const { children } = props
const [error, setError] = useState<ErrorType | null>(null)

const ctx = useMemo((): ErrorProviderContext => {
return {
error: error,
setError: setError,
resolve: () => {
setError(null)
},
}
}, [error])
return <ErrorContext.Provider value={ctx}>{children}</ErrorContext.Provider>
}
1 change: 1 addition & 0 deletions sdk/typescript/rooch-sdk-kit/src/provider/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,4 @@
export * from './roochProvider.js'
export * from './walletProvider.js'
export type { NetworkConfigs } from './clientProvider.js'
export { useError } from './errorProvider.js'
11 changes: 7 additions & 4 deletions sdk/typescript/rooch-sdk-kit/src/provider/roochProvider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { createContext, useRef } from 'react'
import { NetworkConfigs, RoochClientProvider } from './clientProvider.js'
import { createSessionStore, SessionStore } from './sessionStore.js'
import { getDefaultStorage, StorageType } from '../utils/index.js'
import { ErrorProvider } from './errorProvider.js'

const DEFAULT_SESSION_STORAGE_KEY = function (_?: string) {
return 'rooch-sdk-kit:rooch-session-info'
Expand All @@ -17,7 +18,7 @@ export const RoochContext = createContext<SessionStore | null>(null)
export type RoochProviderProps<T extends NetworkConfigs> = {
networks?: NetworkConfigs
onNetworkChange?: (network: keyof T & string) => void

requestErrorCallback?: (code: number) => void
children: ReactNode
} & (
| {
Expand All @@ -42,9 +43,11 @@ export function RoochProvider<T extends NetworkConfigs>(props: RoochProviderProp
)
return (
<RoochContext.Provider value={storeRef.current}>
<RoochClientProvider networks={networks} defaultNetwork={defaultNetwork}>
{children}
</RoochClientProvider>
<ErrorProvider>
<RoochClientProvider networks={networks} defaultNetwork={defaultNetwork}>
{children}
</RoochClientProvider>
</ErrorProvider>
</RoochContext.Provider>
)
}
46 changes: 30 additions & 16 deletions sdk/typescript/rooch-sdk-kit/src/provider/useDefaultClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,22 @@
// SPDX-License-Identifier: Apache-2.0

import { useCallback, useMemo } from 'react'
import { isRoochClient, RoochClient } from '@roochnetwork/rooch-sdk'
import {
ErrorValidateInvalidAccountAuthKey,
ErrorValidateSessionIsExpired,
isRoochClient,
RoochClient,
} from '@roochnetwork/rooch-sdk'
import { useSessionStore } from '../hooks/useSessionsStore.js'
import { NetworkConfig } from '../hooks/index.js'
import { NetworkConfigs } from './clientProvider.js'
import { HTTPTransport } from '../http/httpTransport.js'
import { useSetError } from './errorProvider.js'

const DEFAULT_CREATE_CLIENT = (
_name: string,
config: NetworkConfig | RoochClient,
setCurrentSession: any,
requestErrorCallback: (code: number, msg: string) => void,
) => {
if (isRoochClient(config)) {
return config
Expand All @@ -21,7 +27,7 @@ const DEFAULT_CREATE_CLIENT = (
{
url: config.url!.toString(),
},
setCurrentSession,
requestErrorCallback,
)

return new RoochClient(config)
Expand All @@ -37,19 +43,27 @@ export function useDefaultClient(params: UseRoochClientParams) {

const currentSession = useSessionStore((state) => state.currentSession)
const removeSession = useSessionStore((state) => state.removeSession)
const clearSession = useCallback(() => {
try {
if (currentSession) {
removeSession(currentSession)
const setError = useSetError()
const _requestErrorCallback = useCallback(
(code: number, msg: string) => {
try {
if (code === ErrorValidateInvalidAccountAuthKey || code === ErrorValidateSessionIsExpired) {
if (currentSession) {
removeSession(currentSession)
}
}
} catch (e) {
console.error(e)
}
} catch (e) {
console.error(e)
}
}, [removeSession, currentSession])

const client = useMemo(() => {
return DEFAULT_CREATE_CLIENT(currentNetwork, networks[currentNetwork], clearSession)
}, [currentNetwork, networks, clearSession])
setError({
code: code,
msg: msg,
})
},
[removeSession, currentSession, setError],
)

return client
return useMemo(() => {
return DEFAULT_CREATE_CLIENT(currentNetwork, networks[currentNetwork], _requestErrorCallback)
}, [currentNetwork, networks, _requestErrorCallback])
}
36 changes: 34 additions & 2 deletions sdk/typescript/rooch-sdk/scripts/gen.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ const options: {
typeAlias?: string
alias?: string
flatten?: boolean
create?: Record<string, ts.TypeNode>
}
>
methods: Record<
Expand All @@ -60,7 +61,13 @@ const options: {
}
>
} = {
types: {},
types: {
BalanceInfoView: {
create: {
fixedBalance: ts.factory.createKeywordTypeNode(ts.SyntaxKind.NumberKeyword),
},
},
},
methods: {
// rooch_executeViewFunction: {
// params:{
Expand All @@ -72,13 +79,15 @@ const options: {
params: {
account_addr: {
alias: 'owner',
typeAlias: 'address',
},
},
},
rooch_getBalances: {
params: {
account_addr: {
alias: 'owner',
typeAlias: 'address',
},
},
},
Expand Down Expand Up @@ -169,7 +178,11 @@ fileGenerator.statements.push(
normalizeName(name),
undefined,
undefined,
await createObjectMembers(schema as Extract<OpenRpcType, { type: 'object' }>),
await createObjectMembers(
schema as Extract<OpenRpcType, { type: 'object' }>,
undefined,
name,
),
),
)
}),
Expand All @@ -193,6 +206,17 @@ methodGenerator.imports.push(
),
ts.factory.createStringLiteral('./generated.js'),
),
ts.factory.createImportDeclaration(
undefined,
ts.factory.createImportClause(
true,
undefined,
ts.factory.createNamedImports([
ts.factory.createImportSpecifier(false, undefined, ts.factory.createIdentifier('address')),
]),
),
ts.factory.createStringLiteral('../../types/index.js'),
),
)

methodGenerator.statements.push(
Expand Down Expand Up @@ -273,6 +297,7 @@ async function createMethodParam(method: OpenRpcMethod, param: OpenRpcParam) {
async function createObjectMembers(
type: Extract<OpenRpcTypeRef, { type: 'object' }>,
namespace?: string,
typeName?: string,
) {
const members: ts.TypeElement[] = []

Expand Down Expand Up @@ -328,6 +353,13 @@ async function createObjectMembers(
)),
)

if (typeName && options.types[typeName]?.create) {
const additionalFields = options.types[typeName].create
for (const [fieldName, fieldType] of Object.entries(additionalFields)) {
members.push(ts.factory.createPropertySignature(undefined, fieldName, undefined, fieldType))
}
}

return members
}

Expand Down
Loading
Loading