@n1xyz/wallet-widget 0.0.25 → 0.0.27
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md
CHANGED
|
@@ -109,15 +109,15 @@ function SigningExample() {
|
|
|
109
109
|
|
|
110
110
|
### N1WalletProvider Props
|
|
111
111
|
|
|
112
|
-
| Prop
|
|
113
|
-
|
|
114
|
-
| children
|
|
115
|
-
| providedSessionMode | N1SessionMode
|
|
116
|
-
| appId
|
|
117
|
-
| darkMode
|
|
118
|
-
| onError
|
|
119
|
-
| faucetUrl
|
|
120
|
-
| nord
|
|
112
|
+
| Prop | Type | Required | Default | Description |
|
|
113
|
+
|---------------------|------------------------------|----------|---------|----------------------------------------|
|
|
114
|
+
| children | React.ReactNode | Yes | - | Child components |
|
|
115
|
+
| providedSessionMode | N1SessionMode | Yes | - | Session mode (Nord or NTS) |
|
|
116
|
+
| appId | string | Yes | - | Your application ID |
|
|
117
|
+
| darkMode | boolean | No | true | Enable dark mode UI |
|
|
118
|
+
| onError | (error: WalletError) => void | No | - | Error handler callback |
|
|
119
|
+
| faucetUrl | string | No | - | URL for faucet service |
|
|
120
|
+
| nord | Nord | No | - | Nord instance (required for Nord mode) |
|
|
121
121
|
|
|
122
122
|
### N1SessionMode
|
|
123
123
|
|
|
@@ -132,22 +132,22 @@ enum N1SessionMode {
|
|
|
132
132
|
|
|
133
133
|
The context provides the following values:
|
|
134
134
|
|
|
135
|
-
| Property
|
|
136
|
-
|
|
137
|
-
| address
|
|
138
|
-
| appId
|
|
139
|
-
| balances
|
|
140
|
-
| chain
|
|
141
|
-
| isConnected
|
|
142
|
-
| sessionMode
|
|
143
|
-
| sessionPubKey
|
|
144
|
-
| setShowLogin
|
|
145
|
-
| showLogin
|
|
146
|
-
| signMessageWithSessionKey
|
|
147
|
-
| signMessageWithWalletKey
|
|
135
|
+
| Property | Type | Description |
|
|
136
|
+
|------------------------------|------------------------------------|----------------------------------|
|
|
137
|
+
| address | string | User's wallet address |
|
|
138
|
+
| appId | string | Application ID |
|
|
139
|
+
| balances | Balance[] | User's token balances |
|
|
140
|
+
| chain | string | Current blockchain |
|
|
141
|
+
| isConnected | boolean | Connection status |
|
|
142
|
+
| sessionMode | N1SessionMode | Current session mode |
|
|
143
|
+
| sessionPubKey | Uint8Array | Session public key |
|
|
144
|
+
| setShowLogin | (show: boolean) => void | Show/hide login modal |
|
|
145
|
+
| showLogin | boolean | Login modal visibility state |
|
|
146
|
+
| signMessageWithSessionKey | (message: any) => Promise<any> | Sign message with session key |
|
|
147
|
+
| signMessageWithWalletKey | (message: any) => Promise<any> | Sign message with wallet key |
|
|
148
148
|
| signTransactionWithWalletKey | (transaction: any) => Promise<any> | Sign transaction with wallet key |
|
|
149
|
-
| username
|
|
150
|
-
| walletPubKey
|
|
149
|
+
| username | string | User's username |
|
|
150
|
+
| walletPubKey | Uint8Array | Wallet public key |
|
|
151
151
|
|
|
152
152
|
## Error Handling
|
|
153
153
|
|
|
@@ -164,11 +164,7 @@ export var DepositProvider = function (_a) {
|
|
|
164
164
|
case 1:
|
|
165
165
|
_a.trys.push([1, 8, , 9]);
|
|
166
166
|
usdcToken = nord.tokens.find(function (t) { return t.symbol === 'USDC'; });
|
|
167
|
-
return [4 /*yield*/, nordUser.
|
|
168
|
-
amount: 100,
|
|
169
|
-
tokenId: 0,
|
|
170
|
-
recipient: undefined
|
|
171
|
-
})];
|
|
167
|
+
return [4 /*yield*/, nordUser.depositSpl(parseFloat(amount), usdcToken.tokenId)];
|
|
172
168
|
case 2:
|
|
173
169
|
txId = _a.sent();
|
|
174
170
|
accountInitialized = false;
|
|
@@ -214,7 +210,7 @@ export var DepositProvider = function (_a) {
|
|
|
214
210
|
return [3 /*break*/, 9];
|
|
215
211
|
case 8:
|
|
216
212
|
depositError_1 = _a.sent();
|
|
217
|
-
logger.warn('Error using
|
|
213
|
+
logger.warn('Error using depositSpl, falling back to mock implementation:', depositError_1);
|
|
218
214
|
setIsDepositing(false);
|
|
219
215
|
errorMessage = depositError_1 instanceof Error
|
|
220
216
|
? depositError_1.message
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"DepositContext.js","sourceRoot":"","sources":["../../../../src/Modal/NordFlow/context/DepositContext.tsx"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,OAAc,EAAE,aAAa,EAAE,WAAW,EAAE,UAAU,EAAE,SAAS,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,OAAO,CAAC;AACnG,OAAO,EACL,cAAc,GAEf,MAAM,mCAAmC,CAAC;AAC3C,OAAO,EACL,kBAAkB,EAClB,0BAA0B,GAC3B,MAAM,yBAAyB,CAAC;AAEjC,OAAO,EAAE,MAAM,EAAE,MAAM,uBAAuB,CAAC;AAE/C,OAAO,EAAE,SAAS,EAAE,MAAM,UAAU,CAAC;AAErC,OAAO,EAAE,mBAAmB,EAAE,MAAM,eAAe,CAAC;AAiBpD,0CAA0C;AAC1C,IAAM,cAAc,GAAG,aAAa,CAAkC,SAAS,CAAC,CAAC;AAOjF;;GAEG;AACH,MAAM,CAAC,IAAM,eAAe,GAAmC,UAAC,EAE/D;QADC,QAAQ,cAAA;IAER,yBAAyB;IACnB,IAAA,KAKF,mBAAmB,EAAE,EAJvB,KAAK,WAAA,EACL,OAAO,aAAA,EACP,UAAU,gBAAA,EACV,aAAa,mBACU,CAAC;IAE1B,qBAAqB;IACf,IAAA,KAMF,kBAAkB,EAAE,EALtB,OAAO,aAAA,EACP,IAAI,UAAA,EACJ,wBAAwB,8BAAA,EACxB,yBAAyB,+BAAA,EACzB,QAAQ,cACc,CAAC;IACjB,IAAA,WAAW,GAAK,0BAA0B,EAAE,YAAjC,CAAkC;IAErD,QAAQ;IACF,IAAA,KAAoC,QAAQ,CAChD,OAAO,CAAC,aAAa,CACtB,EAFM,aAAa,QAAA,EAAE,gBAAgB,QAErC,CAAC;IAEF,wBAAwB;IAClB,IAAA,KAAsB,QAAQ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AAyD,CAAC,CAAC;IAC7E,CAAC;IACD,OAAO,OAAO,CAAC;AACjB,CAAC,CAAC","sourcesContent":["import React, { createContext, useCallback, useContext, useEffect, useRef, useState } from 'react';\nimport {\n getExplorerUrl,\n TransactionResult,\n} from '../../../Logic/transactionManager';\nimport {\n useN1WalletContext,\n useN1WalletInternalContext,\n} from '../../../Provider/hooks';\nimport { N1SessionMode } from '../../../Provider/types';\nimport { logger } from '../../../utils/logger';\nimport { AVAILABLE_CHAINS } from '../constants';\nimport { FlowState } from '../types';\nimport { isNordConfigured } from '../utils/nordUtils';\nimport { useFlowStateContext } from './FlowContext';\n\n// Define the shape of the deposit context value\nexport interface DepositContextValue {\n amount: string;\n isDepositing: boolean;\n transactionId: string | null;\n transactionResult: TransactionResult | null;\n authStatus: 'loading' | 'success' | 'error';\n authErrorMessage: string | null;\n authStatusMessage: string | null;\n updateAmount: (newAmount: string) => void;\n startDeposit: () => Promise<void>;\n completeDeposit: () => void;\n performAuth: () => Promise<void>;\n}\n\n// Create the context with a default value\nconst DepositContext = createContext<DepositContextValue | undefined>(undefined);\n\n// Props for the provider component\ninterface DepositProviderProps {\n children: React.ReactNode;\n}\n\n/**\n * Provider component for the deposit context\n */\nexport const DepositProvider: React.FC<DepositProviderProps> = ({\n children,\n}) => {\n // Get flow state context\n const {\n state,\n context,\n transition,\n updateContext,\n } = useFlowStateContext();\n\n // Get wallet context\n const {\n address,\n nord,\n signMessageWithWalletKey,\n signMessageWithSessionKey,\n nordUser,\n } = useN1WalletContext();\n const { sessionMode } = useN1WalletInternalContext();\n\n // chain\n const [selectedChain, setSelectedChain] = useState<string | null>(\n context.selectedChain\n );\n\n // transaction & deposit\n const [amount, setAmount] = useState(context.amount);\n const [isDepositing, setIsDepositing] = useState(false);\n const [transactionId, setTransactionId] = useState<string | null>(context.transactionId);\n const [transactionResult, setTransactionResult] = useState<TransactionResult | null>(null);\n\n\n // auth\n const [authStatus, setAuthStatus] = useState<'loading' | 'success' | 'error'>('loading');\n const [authErrorMessage, setAuthErrorMessage] = useState<string | null>(null);\n const [authStatusMessage, setAuthStatusMessage] = useState<string | null>(null);\n\n // Use refs to track previous values\n const prevContextRef = useRef(context);\n\n\n /**\n * Handle an error by transitioning to error state\n */\n const handleError = useCallback(\n (error: Error) => {\n logger.error('Flow error:', error);\n transition(FlowState.ERROR, { error });\n },\n [transition]\n );\n\n /**\n * Authenticate session\n */\n const performAuth = useCallback(async () => {\n try {\n // Step 1: Tell user to sign transaction\n setAuthStatusMessage(\n 'Please sign the transaction to authenticate your session'\n );\n\n if (!nordUser) {\n throw new Error('Nord user is not initialized');\n }\n\n // Step 2: Call nordUser.refreshSession and get sessionId\n setAuthStatusMessage('Session is being authenticated...');\n\n // Get the session public key from the nordUser\n const sessionPubKey = nordUser.sessionPubKey;\n if (!sessionPubKey) {\n throw new Error('Session public key is not available');\n }\n\n // Refresh the session\n await nordUser.refreshSession(sessionPubKey);\n await nordUser.updateAccountId();\n\n // Get the sessionId after refresh\n const sessionId = nordUser.sessionId;\n if (!sessionId) {\n throw new Error('Failed to get session ID after refresh');\n }\n\n logger.debug('Session refreshed successfully', {\n sessionId: sessionId.toString(),\n });\n\n // Step 3: Store sessionId in localStorage\n if (address) {\n const sessionIdKey = `n1_sessionId_${address}`;\n localStorage.setItem(sessionIdKey, sessionId.toString());\n logger.debug('Stored sessionId in localStorage', { key: sessionIdKey });\n }\n\n // Step 4: Update status to success\n setAuthStatus('success');\n\n // updateContext({ hasActiveSession: true });\n setTimeout(() => {\n transition(FlowState.FINAL_SUCCESS, { hasActiveSession: true, hasNordAccount: true });\n }, 100);\n\n } catch (error) {\n console.error('Authentication error:', error);\n setAuthStatus('error');\n setAuthErrorMessage(\n error instanceof Error ? error.message : 'Unknown error occurred'\n );\n }\n }, [updateContext, transition, address, nordUser]);\n\n /**\n * Update amount for deposit\n */\n const updateAmount = useCallback(\n (newAmount: string) => {\n setAmount(newAmount);\n if (state === FlowState.AMOUNT_INPUT) {\n updateContext({ amount: newAmount });\n } else {\n transition(state, { amount: newAmount });\n }\n },\n [state, transition, updateContext]\n );\n\n /**\n * Start deposit process\n */\n const startDeposit = useCallback(async () => {\n if (isDepositing) return;\n\n logger.debug('Starting deposit process');\n\n if (!amount || parseFloat(amount) <= 0) {\n handleError(new Error('Invalid amount'));\n return;\n }\n\n setIsDepositing(true);\n transition(FlowState.DEPOSIT_PROGRESS);\n\n try {\n const usdcToken = nord!.tokens.find((t: any) => t.symbol === 'USDC');\n\n const txId = await nordUser.deposit(\n {\n amount: 100,\n tokenId: 0,\n recipient: undefined\n }\n );\n\n let accountInitialized = false;\n for (let i = 0; i < 70; i++) {\n const exists = await nord?.getUser({ pubkey: address });\n if (exists) {\n accountInitialized = true;\n break;\n }\n await new Promise((resolve) => setTimeout(resolve, 5000));\n }\n\n if (!accountInitialized) {\n throw new Error('Account failed to intialize on N1.');\n }\n\n logger.debug('Deposit successful using Nord-TS', txId);\n\n // Create transaction result object immediately after successful deposit\n const result: TransactionResult = {\n success: true,\n transactionId: txId,\n amount,\n tokenSymbol: 'USDC',\n fromAddress: address || 'Your Wallet',\n toAddress: 'Exchange Account',\n networkName: selectedChain!,\n status: 'Completed',\n explorerUrl: getExplorerUrl(txId),\n };\n\n // Update state with transaction result\n setTransactionId(txId);\n setTransactionResult(result);\n logger.debug('Transaction completed successfully');\n transition(FlowState.DEPOSIT_SUCCESS, { transactionId: txId, hasNordAccount: true });\n } catch (depositError) {\n logger.warn('Error using deposit, falling back to mock implementation:', depositError);\n setIsDepositing(false);\n const errorMessage = depositError instanceof Error\n ? depositError.message\n : 'Failed to process deposit';\n\n transition(FlowState.AMOUNT_INPUT, {\n depositError: errorMessage\n });\n return; // Exit early\n }\n }, [\n isDepositing,\n selectedChain,\n amount,\n address,\n sessionMode,\n transition,\n handleError,\n nord,\n signMessageWithWalletKey,\n signMessageWithSessionKey,\n nordUser,\n ]);\n\n /**\n * Complete the deposit process and move to the next screen\n */\n const completeDeposit = useCallback(() => {\n // Check if user has an active session to determine the next state\n if (context.hasActiveSession) {\n // If user has an active session, go directly to FINAL_SUCCESS\n transition(FlowState.FINAL_SUCCESS, { hasNordAccount: true, hasActiveSession: true });\n } else {\n // Check if there's a sessionId stored in localStorage\n const sessionIdKey = `n1_sessionId_${address}`;\n const storedSessionId = localStorage.getItem(sessionIdKey);\n\n if (storedSessionId !== null) {\n // If we have a sessionId in localStorage (even if it's 0), go directly to FINAL_SUCCESS\n transition(FlowState.FINAL_SUCCESS, { hasNordAccount: true, hasActiveSession: true });\n } else {\n // If user doesn't have an active session and no sessionId in localStorage, go to NORD_AUTH\n transition(FlowState.AUTH_LOADING, { hasNordAccount: true });\n }\n }\n }, [context.hasActiveSession, transition, address]);\n\n\n\n\n\n // Create the context value\n const contextValue: DepositContextValue = {\n amount,\n isDepositing,\n transactionId,\n transactionResult,\n authStatus,\n authErrorMessage,\n authStatusMessage,\n updateAmount,\n startDeposit,\n completeDeposit,\n performAuth,\n };\n\n\n /**\n * Update state based on context changes\n */\n useEffect(() => {\n const prevContext = prevContextRef.current;\n\n // Only update state if the relevant context values have actually changed\n if (context.selectedChain !== prevContext.selectedChain) {\n setSelectedChain(context.selectedChain);\n }\n\n if (context.amount !== prevContext.amount) {\n setAmount(context.amount);\n }\n\n if (context.transactionId !== prevContext.transactionId) {\n setTransactionId(context.transactionId);\n }\n\n // Update the ref to the current context\n prevContextRef.current = context;\n }, [context]);\n\n\n\n return (\n <DepositContext.Provider value={contextValue}>\n {children}\n </DepositContext.Provider>\n );\n};\n\n/**\n * Hook to use the deposit context\n */\nexport const useDepositContext = (): DepositContextValue => {\n const context = useContext(DepositContext);\n if (context === undefined) {\n throw new Error('useDepositContext must be used within a DepositProvider');\n }\n return context;\n}; "]}
|
|
1
|
+
{"version":3,"file":"DepositContext.js","sourceRoot":"","sources":["../../../../src/Modal/NordFlow/context/DepositContext.tsx"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,OAAc,EAAE,aAAa,EAAE,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Y,cAAA;QACZ,YAAY,cAAA;QACZ,eAAe,iBAAA;QACf,WAAW,aAAA;KACZ,CAAC;IAGF;;OAEG;IACH,SAAS,CAAC;QACR,IAAM,WAAW,GAAG,cAAc,CAAC,OAAO,CAAC;QAE3C,yEAAyE;QACzE,IAAI,OAAO,CAAC,aAAa,KAAK,WAAW,CAAC,aAAa,EAAE,CAAC;YACxD,gBAAgB,CAAC,OAAO,CAAC,aAAa,CAAC,CAAC;QAC1C,CAAC;QAED,IAAI,OAAO,CAAC,MAAM,KAAK,WAAW,CAAC,MAAM,EAAE,CAAC;YAC1C,SAAS,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC;QAC5B,CAAC;QAED,IAAI,OAAO,CAAC,aAAa,KAAK,WAAW,CAAC,aAAa,EAAE,CAAC;YACxD,gBAAgB,CAAC,OAAO,CAAC,aAAa,CAAC,CAAC;QAC1C,CAAC;QAED,wCAAwC;QACxC,cAAc,CAAC,OAAO,GAAG,OAAO,CAAC;IACnC,CAAC,EAAE,CAAC,OAAO,CAAC,CAAC,CAAC;IAId,OAAO,CACL,KAAC,cAAc,CAAC,QAAQ,IAAC,KAAK,EAAE,YAAY,YACzC,QAAQ,GACe,CAC3B,CAAC;AACJ,CAAC,CAAC;AAEF;;GAEG;AACH,MAAM,CAAC,IAAM,iBAAiB,GAAG;IAC/B,IAAM,OAAO,GAAG,UAAU,CAAC,cAAc,CAAC,CAAC;IAC3C,IAAI,OAAO,KAAK,SAAS,EAAE,CAAC;QAC1B,MAAM,IAAI,KAAK,CAAC,yDAAyD,CAAC,CAAC;IAC7E,CAAC;IACD,OAAO,OAAO,CAAC;AACjB,CAAC,CAAC","sourcesContent":["import React, { createContext, useCallback, useContext, useEffect, useRef, useState } from 'react';\nimport {\n getExplorerUrl,\n TransactionResult,\n} from '../../../Logic/transactionManager';\nimport {\n useN1WalletContext,\n useN1WalletInternalContext,\n} from '../../../Provider/hooks';\nimport { N1SessionMode } from '../../../Provider/types';\nimport { logger } from '../../../utils/logger';\nimport { AVAILABLE_CHAINS } from '../constants';\nimport { FlowState } from '../types';\nimport { isNordConfigured } from '../utils/nordUtils';\nimport { useFlowStateContext } from './FlowContext';\n\n// Define the shape of the deposit context value\nexport interface DepositContextValue {\n amount: string;\n isDepositing: boolean;\n transactionId: string | null;\n transactionResult: TransactionResult | null;\n authStatus: 'loading' | 'success' | 'error';\n authErrorMessage: string | null;\n authStatusMessage: string | null;\n updateAmount: (newAmount: string) => void;\n startDeposit: () => Promise<void>;\n completeDeposit: () => void;\n performAuth: () => Promise<void>;\n}\n\n// Create the context with a default value\nconst DepositContext = createContext<DepositContextValue | undefined>(undefined);\n\n// Props for the provider component\ninterface DepositProviderProps {\n children: React.ReactNode;\n}\n\n/**\n * Provider component for the deposit context\n */\nexport const DepositProvider: React.FC<DepositProviderProps> = ({\n children,\n}) => {\n // Get flow state context\n const {\n state,\n context,\n transition,\n updateContext,\n } = useFlowStateContext();\n\n // Get wallet context\n const {\n address,\n nord,\n signMessageWithWalletKey,\n signMessageWithSessionKey,\n nordUser,\n } = useN1WalletContext();\n const { sessionMode } = useN1WalletInternalContext();\n\n // chain\n const [selectedChain, setSelectedChain] = useState<string | null>(\n context.selectedChain\n );\n\n // transaction & deposit\n const [amount, setAmount] = useState(context.amount);\n const [isDepositing, setIsDepositing] = useState(false);\n const [transactionId, setTransactionId] = useState<string | null>(context.transactionId);\n const [transactionResult, setTransactionResult] = useState<TransactionResult | null>(null);\n\n\n // auth\n const [authStatus, setAuthStatus] = useState<'loading' | 'success' | 'error'>('loading');\n const [authErrorMessage, setAuthErrorMessage] = useState<string | null>(null);\n const [authStatusMessage, setAuthStatusMessage] = useState<string | null>(null);\n\n // Use refs to track previous values\n const prevContextRef = useRef(context);\n\n\n /**\n * Handle an error by transitioning to error state\n */\n const handleError = useCallback(\n (error: Error) => {\n logger.error('Flow error:', error);\n transition(FlowState.ERROR, { error });\n },\n [transition]\n );\n\n /**\n * Authenticate session\n */\n const performAuth = useCallback(async () => {\n try {\n // Step 1: Tell user to sign transaction\n setAuthStatusMessage(\n 'Please sign the transaction to authenticate your session'\n );\n\n if (!nordUser) {\n throw new Error('Nord user is not initialized');\n }\n\n // Step 2: Call nordUser.refreshSession and get sessionId\n setAuthStatusMessage('Session is being authenticated...');\n\n // Get the session public key from the nordUser\n const sessionPubKey = nordUser.sessionPubKey;\n if (!sessionPubKey) {\n throw new Error('Session public key is not available');\n }\n\n // Refresh the session\n await nordUser.refreshSession(sessionPubKey);\n await nordUser.updateAccountId();\n\n // Get the sessionId after refresh\n const sessionId = nordUser.sessionId;\n if (!sessionId) {\n throw new Error('Failed to get session ID after refresh');\n }\n\n logger.debug('Session refreshed successfully', {\n sessionId: sessionId.toString(),\n });\n\n // Step 3: Store sessionId in localStorage\n if (address) {\n const sessionIdKey = `n1_sessionId_${address}`;\n localStorage.setItem(sessionIdKey, sessionId.toString());\n logger.debug('Stored sessionId in localStorage', { key: sessionIdKey });\n }\n\n // Step 4: Update status to success\n setAuthStatus('success');\n\n // updateContext({ hasActiveSession: true });\n setTimeout(() => {\n transition(FlowState.FINAL_SUCCESS, { hasActiveSession: true, hasNordAccount: true });\n }, 100);\n\n } catch (error) {\n console.error('Authentication error:', error);\n setAuthStatus('error');\n setAuthErrorMessage(\n error instanceof Error ? error.message : 'Unknown error occurred'\n );\n }\n }, [updateContext, transition, address, nordUser]);\n\n /**\n * Update amount for deposit\n */\n const updateAmount = useCallback(\n (newAmount: string) => {\n setAmount(newAmount);\n if (state === FlowState.AMOUNT_INPUT) {\n updateContext({ amount: newAmount });\n } else {\n transition(state, { amount: newAmount });\n }\n },\n [state, transition, updateContext]\n );\n\n /**\n * Start deposit process\n */\n const startDeposit = useCallback(async () => {\n if (isDepositing) return;\n\n logger.debug('Starting deposit process');\n\n if (!amount || parseFloat(amount) <= 0) {\n handleError(new Error('Invalid amount'));\n return;\n }\n\n setIsDepositing(true);\n transition(FlowState.DEPOSIT_PROGRESS);\n\n try {\n const usdcToken = nord!.tokens.find((t: any) => t.symbol === 'USDC');\n\n const txId = await nordUser.depositSpl(\n parseFloat(amount),\n usdcToken!.tokenId\n );\n\n let accountInitialized = false;\n for (let i = 0; i < 70; i++) {\n const exists = await nord?.getUser({ pubkey: address });\n if (exists) {\n accountInitialized = true;\n break;\n }\n await new Promise((resolve) => setTimeout(resolve, 5000));\n }\n\n if (!accountInitialized) {\n throw new Error('Account failed to intialize on N1.');\n }\n\n logger.debug('Deposit successful using Nord-TS', txId);\n\n // Create transaction result object immediately after successful deposit\n const result: TransactionResult = {\n success: true,\n transactionId: txId,\n amount,\n tokenSymbol: 'USDC',\n fromAddress: address || 'Your Wallet',\n toAddress: 'Exchange Account',\n networkName: selectedChain!,\n status: 'Completed',\n explorerUrl: getExplorerUrl(txId),\n };\n\n // Update state with transaction result\n setTransactionId(txId);\n setTransactionResult(result);\n logger.debug('Transaction completed successfully');\n transition(FlowState.DEPOSIT_SUCCESS, { transactionId: txId, hasNordAccount: true });\n } catch (depositError) {\n logger.warn('Error using depositSpl, falling back to mock implementation:', depositError);\n setIsDepositing(false);\n const errorMessage = depositError instanceof Error\n ? depositError.message\n : 'Failed to process deposit';\n\n transition(FlowState.AMOUNT_INPUT, {\n depositError: errorMessage\n });\n return; // Exit early\n }\n }, [\n isDepositing,\n selectedChain,\n amount,\n address,\n sessionMode,\n transition,\n handleError,\n nord,\n signMessageWithWalletKey,\n signMessageWithSessionKey,\n nordUser,\n ]);\n\n /**\n * Complete the deposit process and move to the next screen\n */\n const completeDeposit = useCallback(() => {\n // Check if user has an active session to determine the next state\n if (context.hasActiveSession) {\n // If user has an active session, go directly to FINAL_SUCCESS\n transition(FlowState.FINAL_SUCCESS, { hasNordAccount: true, hasActiveSession: true });\n } else {\n // Check if there's a sessionId stored in localStorage\n const sessionIdKey = `n1_sessionId_${address}`;\n const storedSessionId = localStorage.getItem(sessionIdKey);\n\n if (storedSessionId !== null) {\n // If we have a sessionId in localStorage (even if it's 0), go directly to FINAL_SUCCESS\n transition(FlowState.FINAL_SUCCESS, { hasNordAccount: true, hasActiveSession: true });\n } else {\n // If user doesn't have an active session and no sessionId in localStorage, go to NORD_AUTH\n transition(FlowState.AUTH_LOADING, { hasNordAccount: true });\n }\n }\n }, [context.hasActiveSession, transition, address]);\n\n\n\n\n\n // Create the context value\n const contextValue: DepositContextValue = {\n amount,\n isDepositing,\n transactionId,\n transactionResult,\n authStatus,\n authErrorMessage,\n authStatusMessage,\n updateAmount,\n startDeposit,\n completeDeposit,\n performAuth,\n };\n\n\n /**\n * Update state based on context changes\n */\n useEffect(() => {\n const prevContext = prevContextRef.current;\n\n // Only update state if the relevant context values have actually changed\n if (context.selectedChain !== prevContext.selectedChain) {\n setSelectedChain(context.selectedChain);\n }\n\n if (context.amount !== prevContext.amount) {\n setAmount(context.amount);\n }\n\n if (context.transactionId !== prevContext.transactionId) {\n setTransactionId(context.transactionId);\n }\n\n // Update the ref to the current context\n prevContextRef.current = context;\n }, [context]);\n\n\n\n return (\n <DepositContext.Provider value={contextValue}>\n {children}\n </DepositContext.Provider>\n );\n};\n\n/**\n * Hook to use the deposit context\n */\nexport const useDepositContext = (): DepositContextValue => {\n const context = useContext(DepositContext);\n if (context === undefined) {\n throw new Error('useDepositContext must be used within a DepositProvider');\n }\n return context;\n}; "]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@n1xyz/wallet-widget",
|
|
3
|
-
"version": "0.0.
|
|
3
|
+
"version": "0.0.27",
|
|
4
4
|
"description": "React wallet widget component for N1 applications",
|
|
5
5
|
"main": "dist/index.js",
|
|
6
6
|
"module": "dist/index.mjs",
|
|
@@ -11,15 +11,6 @@
|
|
|
11
11
|
"LICENSE",
|
|
12
12
|
"package.json"
|
|
13
13
|
],
|
|
14
|
-
"scripts": {
|
|
15
|
-
"build": "pnpm run build:css && pnpm run embed-css && tsc",
|
|
16
|
-
"build:css": "npx tailwindcss -i ./src/main.css -o ./dist/main.css --minify",
|
|
17
|
-
"embed-css": "node scripts/embed-css.js",
|
|
18
|
-
"dev": "nodemon -L -e ts,json,tsx --watch src/ --ignore src/embedded-main-css.ts --ignore dist/ --exec pnpm run build",
|
|
19
|
-
"clean": "rm -rf dist",
|
|
20
|
-
"lint": "eslint src --ext .ts,.tsx",
|
|
21
|
-
"lint:fix": "eslint src --ext .ts,.tsx --fix"
|
|
22
|
-
},
|
|
23
14
|
"author": "N1 Labs",
|
|
24
15
|
"license": "SEE LICENSE IN LICENSE",
|
|
25
16
|
"peerDependencies": {
|
|
@@ -36,7 +27,8 @@
|
|
|
36
27
|
"pino-pretty": "^13.0.0",
|
|
37
28
|
"postcss": "^8.4.31",
|
|
38
29
|
"tailwindcss": "^3.3.5",
|
|
39
|
-
"typescript": "^5.0.0"
|
|
30
|
+
"typescript": "^5.0.0",
|
|
31
|
+
"nodemon": "^3.1"
|
|
40
32
|
},
|
|
41
33
|
"dependencies": {
|
|
42
34
|
"@dynamic-labs/ethereum": "3.5.0",
|
|
@@ -44,7 +36,7 @@
|
|
|
44
36
|
"@dynamic-labs/solana": "3.5.0",
|
|
45
37
|
"@n1xyz/nts-sdk": "0.0.38",
|
|
46
38
|
"@solana/web3.js": "^1.98.1",
|
|
47
|
-
"@n1xyz/nord-ts": "0.
|
|
39
|
+
"@n1xyz/nord-ts": "0.1.3",
|
|
48
40
|
"@tailwindcss/container-queries": "^0.1.1",
|
|
49
41
|
"blockies-react-svg": "^0.0.13",
|
|
50
42
|
"lucide-react": "^0.344.0",
|
|
@@ -53,5 +45,14 @@
|
|
|
53
45
|
},
|
|
54
46
|
"publishConfig": {
|
|
55
47
|
"access": "public"
|
|
48
|
+
},
|
|
49
|
+
"scripts": {
|
|
50
|
+
"build": "pnpm run build:css && pnpm run embed-css && tsc",
|
|
51
|
+
"build:css": "npx tailwindcss -i ./src/main.css -o ./dist/main.css --minify",
|
|
52
|
+
"embed-css": "node scripts/embed-css.js",
|
|
53
|
+
"dev": "nodemon -L -e ts,json,tsx --watch src/ --ignore src/embedded-main-css.ts --ignore dist/ --exec pnpm run build",
|
|
54
|
+
"clean": "rm -rf dist",
|
|
55
|
+
"lint": "eslint src --ext .ts,.tsx",
|
|
56
|
+
"lint:fix": "eslint src --ext .ts,.tsx --fix"
|
|
56
57
|
}
|
|
57
|
-
}
|
|
58
|
+
}
|