Skip to content

Commit

Permalink
feat: implement resolve request module
Browse files Browse the repository at this point in the history
  • Loading branch information
xstelea committed Oct 3, 2024
1 parent ade0fe7 commit 2dd5155
Show file tree
Hide file tree
Showing 20 changed files with 759 additions and 549 deletions.
28 changes: 15 additions & 13 deletions examples/simple-dapp/src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@ import {
} from '@radixdlt/radix-dapp-toolkit'

const dAppDefinitionAddress = import.meta.env.VITE_DAPP_DEFINITION_ADDRESS
const widgetUrl = import.meta.env.VITE_WIDGET_DAPP_URL
const networkId = RadixNetwork.Stokenet
const storageModule = LocalStorageModule(
`rdt:${dAppDefinitionAddress}:${networkId}`,
Expand Down Expand Up @@ -76,15 +75,16 @@ addCb.onclick = () => {
const dAppToolkit = RadixDappToolkit({
dAppDefinitionAddress,
networkId,
featureFlags: ['ExperimentalMobileSupport'],
logger,
})

const gatewayApi = GatewayApiClient.initialize(
dAppToolkit.gatewayApi.clientConfig,
)

dAppToolkit.walletApi.provideChallengeGenerator(async () => generateRolaChallenge())
dAppToolkit.walletApi.provideChallengeGenerator(async () =>
generateRolaChallenge(),
)

dAppToolkit.walletApi.setRequestData(
DataRequestBuilder.persona().withProof(),
Expand All @@ -107,16 +107,18 @@ resetButton.onclick = () => {

sendTxButton.onclick = () => {
dAppToolkit.walletApi.sendTransaction({
transactionManifest: `CALL_METHOD
Address("component_tdx_2_1cptxxxxxxxxxfaucetxxxxxxxxx000527798379xxxxxxxxxyulkzl")
"free"
;
CALL_METHOD
Address("account_tdx_2_12yfw30hdc445j4lnepw7dmrkjcqcswsrxlff5r07mrjq9f8mnnn2r5")
"try_deposit_batch_or_abort"
Expression("ENTIRE_WORKTOP")
Enum<0u8>()
;`,
transactionManifest: `
CALL_METHOD
Address("component_tdx_2_1cptxxxxxxxxxfaucetxxxxxxxxx000527798379xxxxxxxxxyulkzl")
"free"
;
CALL_METHOD
Address("account_tdx_2_1299trm47s3x648jemhu3lfm4d6gt73289rd9s2hpdjm3tp5pdwq4m5")
"try_deposit_batch_or_abort"
Expression("ENTIRE_WORKTOP")
Enum<0u8>()
;`,
})
}

Expand Down
15 changes: 9 additions & 6 deletions package-lock.json

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

3 changes: 3 additions & 0 deletions packages/common/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,7 @@ export type WalletRequest<
timestamp: number
showCancel?: boolean
transactionIntentHash?: string
transactionStatus?: string
walletInteraction: any
walletResponse?: any
metadata: Record<string, string | number | boolean>
Expand All @@ -76,4 +77,6 @@ export type RequestItem = {
walletResponse?: any
sentToWallet?: boolean
isOneTimeRequest?: boolean
metadata?: Record<string, string | number | boolean>
walletData?: any
}
4 changes: 2 additions & 2 deletions packages/dapp-toolkit/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@
"immer": "^10.0.4",
"lit": "^3.1.2",
"lit-html": "^3.1.2",
"neverthrow": "^6.1.0",
"neverthrow": "^8.0.0",
"rxjs": "^7.8.1",
"tslog": ">=4.8.0",
"uuid": "^10.0.0",
Expand All @@ -95,4 +95,4 @@
"publishConfig": {
"registry": "https://registry.npmjs.org"
}
}
}
3 changes: 1 addition & 2 deletions packages/dapp-toolkit/src/helpers/parse-json.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,12 @@
import type { Result } from 'neverthrow'
import { err, ok } from 'neverthrow'
import { typedError } from './typed-error'

export const parseJSON = <T = Record<string, any>>(
text: string,
): Result<T, Error> => {
try {
return ok(JSON.parse(text))
} catch (error) {
return err(typedError(error))
return err(error as Error)
}
}
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
import {
concatMap,
delay,
filter,
finalize,
first,
from,
fromEvent,
map,
merge,
Expand All @@ -10,12 +13,10 @@ import {
Subscription,
switchMap,
tap,
timer,
} from 'rxjs'
import { ConnectButton } from '@radixdlt/connect-button'
import type {
Account,
RadixButtonStatus,
RadixButtonTheme,
RequestItem,
} from 'radix-connect-common'
Expand Down Expand Up @@ -314,7 +315,6 @@ export const ConnectButtonModule = (
onCancelRequestItem$: subjects.onCancelRequestItem.asObservable(),
onIgnoreTransactionItem$: subjects.onIgnoreTransactionItem.asObservable(),
onLinkClick$: subjects.onLinkClick.asObservable(),
setStatus: (value: RadixButtonStatus) => subjects.status.next(value),
setTheme: (value: RadixButtonTheme) => subjects.theme.next(value),
setMode: (value: 'light' | 'dark') => subjects.mode.next(value),
setActiveTab: (value: 'sharing' | 'requests') =>
Expand Down Expand Up @@ -385,12 +385,6 @@ export const ConnectButtonModule = (
walletRequestModule.requestItems$
.pipe(
tap((items) => {
const hasPendingItem = items.find((item) => item.status === 'pending')

if (hasPendingItem) {
connectButtonApi.setStatus('pending')
}

connectButtonApi.setRequestItems([...items].reverse())
}),
)
Expand Down Expand Up @@ -465,22 +459,27 @@ export const ConnectButtonModule = (
subscriptions.add(
walletRequestModule.interactionStatusChange$
.pipe(
mergeMap((newStatus) => {
statusStorage.setState({
status: newStatus === 'success' ? 'success' : 'error',
})

return timer(2000).pipe(
tap(() => {
const result = walletRequestModule.getPendingRequests()
result.map((pendingItems) => {
statusStorage.setState({
status: pendingItems.length ? 'pending' : 'default',
})
})
mergeMap((newStatus) =>
from(
statusStorage.setState({
status:
newStatus === 'success'
? 'success'
: newStatus === 'fail'
? 'error'
: 'pending',
}),
)
}),
).pipe(
delay(2000),
concatMap(() =>
walletRequestModule.getPendingRequests().andThen((items) =>
statusStorage.setState({
status: items.length ? 'pending' : 'default',
}),
),
),
),
),
)
.subscribe(),
)
Expand Down
1 change: 0 additions & 1 deletion packages/dapp-toolkit/src/modules/connect-button/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,6 @@ export type ConnectButtonModuleOutput = {
type: 'account' | 'transaction' | 'showQrCode' | 'setupGuide' | 'getWallet'
data: string
}>
setStatus: (value: RadixButtonStatus) => void
setMode: (value: 'light' | 'dark') => void
setTheme: (value: RadixButtonTheme) => void
setActiveTab: (value: 'sharing' | 'requests') => void
Expand Down
12 changes: 7 additions & 5 deletions packages/dapp-toolkit/src/modules/state/state.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { BehaviorSubject, Subscription, filter } from 'rxjs'
import { RdtState, WalletData, walletDataDefault } from './types'
import { Logger } from '../../helpers'
import { StorageModule } from '../storage'
import { ok, okAsync } from 'neverthrow'
import { ok, okAsync, ResultAsync } from 'neverthrow'

export type StateModule = ReturnType<typeof StateModule>

Expand All @@ -13,20 +13,22 @@ export const StateModule = (input: {
}
}) => {
const logger = input?.logger?.getSubLogger({ name: 'StateModule' })
const storageModule = input.providers.storageModule
const storageModule: StorageModule<RdtState> = input.providers.storageModule

const subscriptions = new Subscription()

const setState = (state: RdtState) => storageModule.setState(state)

const getState = () =>
const getState = (): ResultAsync<RdtState, never> =>
storageModule
.getState()
.orElse(() => okAsync(defaultState))
.andThen((state) => (state ? ok(state) : ok(defaultState)))

const patchState = (state: Partial<RdtState>) =>
getState().andThen((oldState) => setState({ ...oldState, ...state } as RdtState))
getState().andThen((oldState) =>
setState({ ...oldState, ...state } as RdtState),
)

const defaultState = {
walletData: walletDataDefault,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import { ErrorType } from '../../../error'
import { WalletInteraction } from '../../../schemas'
import type { StorageModule } from '../../storage'
import { ResultAsync, errAsync } from 'neverthrow'
import { WalletData } from '../../state'
export type RequestItemModuleInput = {
logger?: Logger
providers: { storageModule: StorageModule<RequestItem> }
Expand Down Expand Up @@ -70,11 +71,15 @@ export const RequestItemModule = (input: RequestItemModuleInput) => {
status,
error,
transactionIntentHash,
metadata = {},
walletData,
}: {
id: string
status: RequestStatusTypes
error?: string
transactionIntentHash?: string
walletData?: WalletData
metadata?: Record<string, string | number | boolean>
}): ResultAsync<void, { reason: string }> => {
return storageModule
.getItemById(id)
Expand All @@ -83,10 +88,16 @@ export const RequestItemModule = (input: RequestItemModuleInput) => {
if (item) {
const updated = {
...item,
walletData,
status:
item.status === RequestStatus.ignored ? item.status : status,
metadata: item.metadata
? { ...item.metadata, ...metadata }
: metadata,
} as RequestItem

if (updated.status === 'fail') {
updated.transactionIntentHash = transactionIntentHash!
updated.error = error!
}
if (
Expand All @@ -95,9 +106,10 @@ export const RequestItemModule = (input: RequestItemModuleInput) => {
) {
updated.transactionIntentHash = transactionIntentHash!
}
if (['success', 'fail', 'ignored', 'cancelled'].includes(updated.status)) {
if (
['success', 'fail', 'ignored', 'cancelled'].includes(updated.status)
) {
delete updated.walletInteraction
delete updated.walletResponse
}
logger?.debug({ method: 'updateRequestItemStatus', updated })
return storageModule
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export * from './resolvers'
export * from './request-resolver.module'
export * from './type'
Loading

0 comments on commit 2dd5155

Please sign in to comment.