@n1xyz/wallet-widget 0.0.16 → 0.0.17

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.
@@ -2,13 +2,15 @@ import { generateSessionKeyPair, generateRandomUint8Array } from '@n1xyz/nts-sdk
2
2
  export { generateSessionKeyPair, generateRandomUint8Array };
3
3
  export declare function arrayBufferToBase64(buffer: Uint8Array): string;
4
4
  export declare function base64ToUint8Array(base64String: string): Uint8Array<ArrayBuffer>;
5
- export declare function storeSessionKeysInLocalStorage({ privKey, walletPublicKey, chainName, }: {
5
+ export declare function storeSessionKeysInLocalStorage({ privKey, publicKey, walletPublicKey, chainName, }: {
6
6
  privKey: Uint8Array;
7
+ publicKey: Uint8Array;
7
8
  walletPublicKey: string;
8
9
  chainName: string;
9
10
  }): void;
10
11
  export declare function getSessionKeysFromLocalStorage(walletPublicKey: string): {
11
12
  ed25519PrivateKey: Uint8Array;
13
+ ed25519PublicKey: Uint8Array | null;
12
14
  walletPublicKey: string;
13
15
  chainName: string;
14
16
  createdAt: string;
@@ -57,17 +57,18 @@ export function base64ToUint8Array(base64String) {
57
57
  }
58
58
  // Function to store keys with a custom ID format in local storage, including private key
59
59
  export function storeSessionKeysInLocalStorage(_a) {
60
- var privKey = _a.privKey, walletPublicKey = _a.walletPublicKey, chainName = _a.chainName;
60
+ var privKey = _a.privKey, publicKey = _a.publicKey, walletPublicKey = _a.walletPublicKey, chainName = _a.chainName;
61
61
  var storageKey = "n1_sessionKey_".concat(walletPublicKey);
62
62
  var data = {
63
63
  ed25519PrivateKey: arrayBufferToBase64(privKey),
64
+ ed25519PublicKey: arrayBufferToBase64(publicKey),
64
65
  walletPublicKey: walletPublicKey,
65
66
  chainName: chainName,
66
67
  createdAt: new Date().toISOString(),
67
68
  };
68
69
  localStorage.setItem(storageKey, JSON.stringify(data));
69
70
  }
70
- // Retrieve data from local storage by wallet key and convert the private key back to Uint8Array
71
+ // Retrieve data from local storage by wallet key and convert the private and public key back to Uint8Array
71
72
  export function getSessionKeysFromLocalStorage(walletPublicKey) {
72
73
  var storageKey = "n1_sessionKey_".concat(walletPublicKey);
73
74
  var data = localStorage.getItem(storageKey);
@@ -76,6 +77,19 @@ export function getSessionKeysFromLocalStorage(walletPublicKey) {
76
77
  if (parsedData.ed25519PrivateKey) {
77
78
  parsedData.ed25519PrivateKey = base64ToUint8Array(parsedData.ed25519PrivateKey);
78
79
  }
80
+ else {
81
+ throw new Error('Missing ed25519PrivateKey in session storage');
82
+ }
83
+ if (parsedData.ed25519PublicKey) {
84
+ parsedData.ed25519PublicKey = base64ToUint8Array(parsedData.ed25519PublicKey);
85
+ }
86
+ else {
87
+ throw new Error('Missing ed25519PublicKey in session storage');
88
+ }
89
+ // Validate keys: check that public key is present and is Uint8Array of length 32
90
+ if (!parsedData.ed25519PublicKey || !(parsedData.ed25519PublicKey instanceof Uint8Array) || parsedData.ed25519PublicKey.length !== 32) {
91
+ throw new Error('Invalid public key in session storage');
92
+ }
79
93
  return parsedData;
80
94
  }
81
95
  return null;
@@ -1 +1 @@
1
- {"version":3,"file":"utils.js","sourceRoot":"","sources":["../../src/Logic/utils.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,OAAO,EACL,sBAAsB,EACtB,wBAAwB,GACzB,MAAM,gBAAgB,CAAC;AACxB,OAAO,EAAE,MAAM,EAAE,MAAM,iBAAiB,CAAC;AAEzC,OAAO,EAAE,sBAAsB,EAAE,wBAAwB,EAAE,CAAC;AAE5D,MAAM,UAAU,mBAAmB,CAAC,MAAkB;IACpD,IAAI,MAAM,GAAG,EAAE,CAAC;IAChB,IAAM,KAAK,GAAG,IAAI,UAAU,CAAC,MAAM,CAAC,CAAC;IACrC,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,KAAK,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE,CAAC;QACtC,MAAM,IAAI,MAAM,CAAC,YAAY,CAAC,KAAK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4BACP,cAAc,EAAE,kBAAkB;yBACnC;qBACF,CACF,EAAA;;oBARK,QAAQ,GAAG,SAQhB;yBAEG,CAAA,QAAQ,CAAC,MAAM,KAAK,GAAG,CAAA,EAAvB,wBAAuB;oBACZ,qBAAM,QAAQ,CAAC,IAAI,EAAE,EAAA;;oBAA5B,IAAI,GAAG,SAAqB;oBAClC,sBAAO,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,UAAC,IAAS;4BAC7B,OAAO;gCACL,IAAI,EAAE,IAAI,CAAC,QAAQ,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC;gCACjC,OAAO,EAAE,IAAI,CAAC,KAAK;gCACnB,KAAK,EAAE,IAAI,CAAC,MAAM;gCAClB,MAAM,EAAE,IAAI,CAAC,MAAM;6BACpB,CAAC;wBACJ,CAAC,CAAC,EAAC;wBAEL,sBAAO,IAAI,EAAC;;;;CACb","sourcesContent":["import {\n generateSessionKeyPair,\n generateRandomUint8Array,\n} from '@n1xyz/nts-sdk';\nimport { logger } from '../utils/logger';\n\nexport { generateSessionKeyPair, generateRandomUint8Array };\n\nexport function arrayBufferToBase64(buffer: Uint8Array) {\n let binary = '';\n const bytes = new Uint8Array(buffer);\n for (let i = 0; i < bytes.length; i++) {\n binary += String.fromCharCode(bytes[i]);\n }\n return btoa(binary);\n}\n\n// Convert Base64 string back to Uint8Array\nexport function base64ToUint8Array(base64String: string) {\n const binaryString = atob(base64String);\n const length = binaryString.length;\n const bytes = new Uint8Array(length);\n for (let i = 0; i < length; i++) {\n bytes[i] = binaryString.charCodeAt(i);\n }\n return bytes;\n}\n\n// Function to store keys with a custom ID format in local storage, including private key\nexport function storeSessionKeysInLocalStorage({\n privKey,\n walletPublicKey,\n chainName,\n}: {\n privKey: Uint8Array;\n walletPublicKey: string;\n chainName: string;\n}) {\n const storageKey = `n1_sessionKey_${walletPublicKey}`;\n\n const data = {\n ed25519PrivateKey: arrayBufferToBase64(privKey),\n walletPublicKey,\n chainName,\n createdAt: new Date().toISOString(),\n };\n\n localStorage.setItem(storageKey, JSON.stringify(data));\n}\n\n// Retrieve data from local storage by wallet key and convert the private key back to Uint8Array\nexport function getSessionKeysFromLocalStorage(walletPublicKey: string): {\n ed25519PrivateKey: Uint8Array;\n walletPublicKey: string;\n chainName: string;\n createdAt: string;\n} | null {\n const storageKey = `n1_sessionKey_${walletPublicKey}`;\n\n const data = localStorage.getItem(storageKey);\n if (data) {\n const parsedData = JSON.parse(data);\n if (parsedData.ed25519PrivateKey) {\n parsedData.ed25519PrivateKey = base64ToUint8Array(\n parsedData.ed25519PrivateKey\n );\n }\n return parsedData;\n }\n return null;\n}\n\n// Function to remove data from local storage by wallet key\nexport function removeKeysFromLocalStorage(walletPublicKey: string) {\n const storageKey = `n1_sessionKey_${walletPublicKey}`;\n\n localStorage.removeItem(storageKey);\n}\n\nexport function hexToUint8Array(hex: string) {\n if (hex.length % 2 !== 0) {\n throw new Error('Invalid hex string');\n }\n const array = new Uint8Array(hex.length / 2);\n for (let i = 0; i < hex.length; i += 2) {\n array[i / 2] = parseInt(hex.substr(i, 2), 16);\n }\n return array;\n}\n\nfunction getMsgBytes(timestamp: number) {\n const hex = 'LoginSigning : ' + timestamp;\n const array = new Uint8Array(hex.length / 2);\n for (let i = 0; i < hex.length; i += 2) {\n array[i / 2] = parseInt(hex.substr(i, 2), 16);\n }\n return array;\n}\n\nexport async function createWebSession(\n signMessageWithSessionKey: any,\n sessionPubKey: any,\n walletPubKey: any\n) {\n logger.debug('Creating web session...');\n const timestamp = new Date().getTime();\n const msg = getMsgBytes(timestamp);\n const signature = await signMessageWithSessionKey(msg);\n if (process.env.SKIP_ARGUS) {\n return;\n }\n const response = await fetch(`${process.env.ARGUS_URL}/api/auth/login`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({\n sessionKey: Array.from(sessionPubKey),\n timestamp: timestamp,\n msg: Array.from(msg),\n signature: Array.from(signature),\n publicKey: Array.from(walletPubKey),\n }),\n credentials: 'include', // Include cookies in requests\n });\n if (response.status != 200) {\n throw new Error('failed to create a session!');\n }\n}\n\nexport async function createUser(username: any) {\n const response = await fetch(\n `${process.env.ARGUS_URL}/api/db/createUser?name=${username}`,\n {\n method: 'GET',\n headers: {\n 'Content-Type': 'application/json',\n },\n credentials: 'include',\n }\n );\n if (response.status != 200) {\n throw new Error('failed to create a user!');\n }\n}\n\nexport async function getUser() {\n if (process.env.SKIP_ARGUS) {\n return { name: 'test' };\n }\n try {\n const response = await fetch(`${process.env.ARGUS_URL}/api/db/getUser`, {\n method: 'GET',\n headers: {\n 'Content-Type': 'application/json',\n },\n credentials: 'include', // Include cookies in requests\n });\n if (response.status === 200) {\n return await response.json();\n } else if (response.status === 404) {\n return null;\n }\n } catch (error) {\n throw new Error('failed to get user!');\n }\n}\n\nexport async function getUserBalances(address: string) {\n const response = await fetch(\n `https://n1ts.n1.xyz/app/data?tag=user_balance_${address.toLowerCase()}`,\n {\n method: 'GET',\n headers: {\n 'Content-Type': 'application/json',\n },\n }\n );\n\n if (response.status === 200) {\n const data = await response.json();\n return data.data.map((item: any) => {\n return {\n mint: item.field_id.split('_')[2],\n balance: item.value,\n appId: item.app_id,\n symbol: item.symbol,\n };\n });\n }\n return null;\n}\n"]}
1
+ {"version":3,"file":"utils.js","sourceRoot":"","sources":["../../src/Logic/utils.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,OAAO,EACL,sBAAsB,EACtB,wBAAwB,GACzB,MAAM,gBAAgB,CAAC;AACxB,OAAO,EAAE,MAAM,EAAE,MAAM,iBAAiB,CAAC;AAGzC,OAAO,EAAE,sBAAsB,EAAE,wBAAwB,EAAE,CAAC;AAE5D,MAAM,UAAU,mBAAmB,CAAC,MAAkB;IACpD,IAAI,MAAM,GAAG,EAAE,CAAC;IAChB,IAAM,KAAK,GAAG,IAAI,UAAU,CAAC,MAAM,CAAC,CAAC;IACrC,KAAK,IAAI,CAAC,GAA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C;wBAEL,sBAAO,IAAI,EAAC;;;;CACb","sourcesContent":["import {\n generateSessionKeyPair,\n generateRandomUint8Array,\n} from '@n1xyz/nts-sdk';\nimport { logger } from '../utils/logger';\nimport nacl from 'tweetnacl';\n\nexport { generateSessionKeyPair, generateRandomUint8Array };\n\nexport function arrayBufferToBase64(buffer: Uint8Array) {\n let binary = '';\n const bytes = new Uint8Array(buffer);\n for (let i = 0; i < bytes.length; i++) {\n binary += String.fromCharCode(bytes[i]);\n }\n return btoa(binary);\n}\n\n// Convert Base64 string back to Uint8Array\nexport function base64ToUint8Array(base64String: string) {\n const binaryString = atob(base64String);\n const length = binaryString.length;\n const bytes = new Uint8Array(length);\n for (let i = 0; i < length; i++) {\n bytes[i] = binaryString.charCodeAt(i);\n }\n return bytes;\n}\n\n// Function to store keys with a custom ID format in local storage, including private key\nexport function storeSessionKeysInLocalStorage({\n privKey,\n publicKey,\n walletPublicKey,\n chainName,\n}: {\n privKey: Uint8Array;\n publicKey: Uint8Array;\n walletPublicKey: string;\n chainName: string;\n}) {\n const storageKey = `n1_sessionKey_${walletPublicKey}`;\n\n const data = {\n ed25519PrivateKey: arrayBufferToBase64(privKey),\n ed25519PublicKey: arrayBufferToBase64(publicKey),\n walletPublicKey,\n chainName,\n createdAt: new Date().toISOString(),\n };\n\n localStorage.setItem(storageKey, JSON.stringify(data));\n}\n\n// Retrieve data from local storage by wallet key and convert the private and public key back to Uint8Array\nexport function getSessionKeysFromLocalStorage(walletPublicKey: string): {\n ed25519PrivateKey: Uint8Array;\n ed25519PublicKey: Uint8Array | null;\n walletPublicKey: string;\n chainName: string;\n createdAt: string;\n} | null {\n const storageKey = `n1_sessionKey_${walletPublicKey}`;\n\n const data = localStorage.getItem(storageKey);\n if (data) {\n const parsedData = JSON.parse(data);\n if (parsedData.ed25519PrivateKey) {\n parsedData.ed25519PrivateKey = base64ToUint8Array(\n parsedData.ed25519PrivateKey\n );\n } else {\n throw new Error('Missing ed25519PrivateKey in session storage');\n }\n if (parsedData.ed25519PublicKey) {\n parsedData.ed25519PublicKey = base64ToUint8Array(\n parsedData.ed25519PublicKey\n );\n } else {\n throw new Error('Missing ed25519PublicKey in session storage');\n }\n // Validate keys: check that public key is present and is Uint8Array of length 32\n if (!parsedData.ed25519PublicKey || !(parsedData.ed25519PublicKey instanceof Uint8Array) || parsedData.ed25519PublicKey.length !== 32) {\n throw new Error('Invalid public key in session storage');\n }\n return parsedData;\n }\n return null;\n}\n\n// Function to remove data from local storage by wallet key\nexport function removeKeysFromLocalStorage(walletPublicKey: string) {\n const storageKey = `n1_sessionKey_${walletPublicKey}`;\n\n localStorage.removeItem(storageKey);\n}\n\nexport function hexToUint8Array(hex: string) {\n if (hex.length % 2 !== 0) {\n throw new Error('Invalid hex string');\n }\n const array = new Uint8Array(hex.length / 2);\n for (let i = 0; i < hex.length; i += 2) {\n array[i / 2] = parseInt(hex.substr(i, 2), 16);\n }\n return array;\n}\n\nfunction getMsgBytes(timestamp: number) {\n const hex = 'LoginSigning : ' + timestamp;\n const array = new Uint8Array(hex.length / 2);\n for (let i = 0; i < hex.length; i += 2) {\n array[i / 2] = parseInt(hex.substr(i, 2), 16);\n }\n return array;\n}\n\nexport async function createWebSession(\n signMessageWithSessionKey: any,\n sessionPubKey: any,\n walletPubKey: any\n) {\n logger.debug('Creating web session...');\n const timestamp = new Date().getTime();\n const msg = getMsgBytes(timestamp);\n const signature = await signMessageWithSessionKey(msg);\n if (process.env.SKIP_ARGUS) {\n return;\n }\n const response = await fetch(`${process.env.ARGUS_URL}/api/auth/login`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({\n sessionKey: Array.from(sessionPubKey),\n timestamp: timestamp,\n msg: Array.from(msg),\n signature: Array.from(signature),\n publicKey: Array.from(walletPubKey),\n }),\n credentials: 'include', // Include cookies in requests\n });\n if (response.status != 200) {\n throw new Error('failed to create a session!');\n }\n}\n\nexport async function createUser(username: any) {\n const response = await fetch(\n `${process.env.ARGUS_URL}/api/db/createUser?name=${username}`,\n {\n method: 'GET',\n headers: {\n 'Content-Type': 'application/json',\n },\n credentials: 'include',\n }\n );\n if (response.status != 200) {\n throw new Error('failed to create a user!');\n }\n}\n\nexport async function getUser() {\n if (process.env.SKIP_ARGUS) {\n return { name: 'test' };\n }\n try {\n const response = await fetch(`${process.env.ARGUS_URL}/api/db/getUser`, {\n method: 'GET',\n headers: {\n 'Content-Type': 'application/json',\n },\n credentials: 'include', // Include cookies in requests\n });\n if (response.status === 200) {\n return await response.json();\n } else if (response.status === 404) {\n return null;\n }\n } catch (error) {\n throw new Error('failed to get user!');\n }\n}\n\nexport async function getUserBalances(address: string) {\n const response = await fetch(\n `https://n1ts.n1.xyz/app/data?tag=user_balance_${address.toLowerCase()}`,\n {\n method: 'GET',\n headers: {\n 'Content-Type': 'application/json',\n },\n }\n );\n\n if (response.status === 200) {\n const data = await response.json();\n return data.data.map((item: any) => {\n return {\n mint: item.field_id.split('_')[2],\n balance: item.value,\n appId: item.app_id,\n symbol: item.symbol,\n };\n });\n }\n return null;\n}\n"]}
@@ -182,6 +182,7 @@ export function CreateSessionView() {
182
182
  logger.debug('Storing session keys');
183
183
  storeSessionKeysInLocalStorage({
184
184
  privKey: keyPair.privateKey,
185
+ publicKey: keyPair.publicKey,
185
186
  walletPublicKey: address,
186
187
  chainName: dynamicWallet.chain,
187
188
  });
@@ -1 +1 @@
1
- {"version":3,"file":"CreateSessionView.js","sourceRoot":"","sources":["../../../../src/Modal/NTSFlow/views/CreateSessionView.tsx"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,OAAO,EAAE,SAAS,EAAE,QAAQ,EAAE,MAAM,OAAO,CAAC;AAC5C,OAAO,EAAE,cAAc,EAAE,MAAM,0BAA0B,CAAC;AAC1D,OAAO,EAAE,WAAW,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;AACrE,OAAO,EACL,gBAAgB,EAChB,sBAAsB,EACtB,OAAO,EACP,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D,IACE,GACF,IACF,CACP,CAAC;AACJ,CAAC","sourcesContent":["import { useEffect, useState } from 'react';\nimport { ANIMATION_EASE } from '../../NordFlow/constants';\nimport { WalletError, WalletErrorCode } from '../../../errors/types';\nimport {\n createWebSession,\n generateSessionKeyPair,\n getUser,\n storeSessionKeysInLocalStorage,\n} from '../../../Logic/utils';\nimport {\n useN1WalletContext,\n useN1WalletInternalContext,\n} from '../../../Provider/hooks';\nimport { N1ModalViewMode } from '../../../Provider/types';\nimport { logger } from '../../../utils/logger';\nimport { BackButton } from '../components/BackButton';\nimport { ModalHeader } from '../components/ModalHeader';\nimport { signEd25519 } from '@n1xyz/nts-sdk';\n\nexport function CreateSessionView() {\n const [isHovered, setIsHovered] = useState(false);\n const [isPressed, setIsPressed] = useState(false);\n\n const [NTSComponents, setNTSComponents] = useState<any>(null);\n const [keyPair, setKeyPair] = useState<{\n publicKey: Uint8Array;\n privateKey: Uint8Array;\n } | null>(null);\n\n const {\n setViewMode,\n setUsername,\n setStartClosingLogin,\n setIsConnected,\n dynamicWallet,\n handleError,\n setSessionPubKey,\n setSignMessageWithSessionKey,\n dynamicHandleLogOut,\n setDynamicWallet,\n setAddress,\n setSignMessageWithWalletKey,\n } = useN1WalletInternalContext();\n\n const { ntsInterface, walletPubKey, address } = useN1WalletContext();\n\n // Initialize NTS SDK and generate key pair\n useEffect(() => {\n const loadNTSSDK = async () => {\n try {\n const { Transaction, AdminAction, CoreApps } = await import(\n '@n1xyz/nts-sdk'\n );\n setNTSComponents({ Transaction, AdminAction, CoreApps });\n const newKeyPair = await generateSessionKeyPair();\n setKeyPair(newKeyPair);\n } catch (error) {\n handleError(\n new WalletError(\n WalletErrorCode.CONNECTION_FAILED,\n 'Failed to initialize NTS SDK',\n { originalError: error }\n )\n );\n }\n };\n loadNTSSDK();\n }, [handleError]);\n\n const signWithWallet = async (msg: string): Promise<Uint8Array> => {\n try {\n if (!dynamicWallet) {\n throw new WalletError(\n WalletErrorCode.WALLET_NOT_FOUND,\n 'Wallet not found for signing'\n );\n }\n\n if (dynamicWallet.chain === 'SOL') {\n const signature = await dynamicWallet.signMessage(msg);\n const binaryString = atob(signature);\n const signatureUint8Array = new Uint8Array(binaryString.length);\n for (let i = 0; i < binaryString.length; i++) {\n signatureUint8Array[i] = binaryString.charCodeAt(i);\n }\n return signatureUint8Array;\n }\n\n const sig = (await dynamicWallet.signMessage(msg)) as string;\n logger.debug('Wallet signature received', { signature: sig });\n return Uint8Array.from(Buffer.from(sig.slice(2), 'hex'));\n } catch (error) {\n throw new WalletError(\n WalletErrorCode.USER_REJECTED,\n 'Failed to sign message with wallet',\n { originalError: error }\n );\n }\n };\n\n const handleSign = async () => {\n logger.debug('handleSign');\n\n if (!NTSComponents || !keyPair) {\n logger.warn('Required components not initialized');\n return;\n }\n\n setViewMode(N1ModalViewMode.Signing);\n\n try {\n const sessionKeyHex = Buffer.from(keyPair.publicKey).toString('hex');\n logger.debug('Generated session key', { sessionKey: sessionKeyHex });\n\n // Create and sign transaction that registers the session key with Core\n const transactionData = {\n appId: NTSComponents.CoreApps.Admin,\n action: NTSComponents.AdminAction.addSessionKey,\n framework: 'ts',\n data: [\n {\n sessionKey: sessionKeyHex,\n appId: 'hub',\n },\n ],\n };\n\n setSignMessageWithWalletKey(signWithWallet);\n const tx = new NTSComponents.Transaction(transactionData, walletPubKey!);\n await tx.signWithWalletFunction(signWithWallet);\n try {\n const txRes = await ntsInterface.sendTransaction(\n tx,\n tx.signature!,\n walletPubKey\n );\n if (txRes.success) {\n logger.debug('txRes', txRes);\n } else {\n logger.debug('txRes', txRes);\n throw new WalletError(\n WalletErrorCode.TRANSACTION_FAILED,\n 'Transaction failed'\n );\n }\n } catch (_) {\n throw new WalletError(\n WalletErrorCode.TRANSACTION_FAILED,\n 'Transaction did not succeed'\n );\n }\n\n // Create session signing function\n const signFn = async (message: Uint8Array) => {\n try {\n return await signEd25519(message, keyPair.privateKey as Uint8Array);\n } catch (_) {\n logger.error('Error signing with Ed25519:', _);\n throw _;\n }\n };\n\n // Store session keys\n logger.debug('Storing session keys');\n storeSessionKeysInLocalStorage({\n privKey: keyPair.privateKey as Uint8Array,\n walletPublicKey: address,\n chainName: dynamicWallet!.chain,\n });\n setSessionPubKey(keyPair.publicKey);\n setSignMessageWithSessionKey(() => signFn);\n\n // Initialize web session with Argus who verifies that the session is\n // registered with Core, and if so, grants you access to its user metadata db\n await createWebSession(signFn, keyPair.publicKey, walletPubKey);\n\n // Check for existing user\n // TODO: handle case for auth.users, currently user.name is a wallet_only_users namespacing\n const user = await getUser();\n if (user?.name) {\n logger.info('Existing user found, completing login');\n setUsername(user.name);\n localStorage.setItem(`n1_${address}_username`, user.name);\n setStartClosingLogin(true);\n setIsConnected(true);\n } else {\n logger.info('No user found, transitioning to user creation');\n setViewMode(N1ModalViewMode.CreatingUser);\n }\n } catch (error: any) {\n logger.error('Session creation failed:', error);\n if (error.name === 'WalletError') {\n handleError(error);\n } else {\n handleError(\n new WalletError(\n WalletErrorCode.CONNECTION_FAILED,\n 'Failed to create session',\n { originalError: JSON.stringify(error) }\n )\n );\n }\n\n setViewMode(N1ModalViewMode.CreateSession);\n }\n };\n\n return (\n <div className=\"bg-n1-ww-gray-50 dark:bg-n1-ww-gray-950 relative border border-n1-ww-gray-200 dark:border-n1-ww-gray-800 rounded-md transition-[max-width,transform,opacity] duration-[3000ms] ease-[cubic-bezier(0.16,1,0.3,1)] w-full max-w-sm m-4 origin-center will-change-[max-width,transform,opacity]\">\n <div className=\"p-6 border-b border-n1-ww-gray-200 dark:border-n1-ww-gray-800\">\n <ModalHeader />\n </div>\n\n <div className=\"p-6 overflow-hidden relative\">\n <div className=\"space-y-4\">\n <div className=\"text-center\">\n <h3 className=\"text-xl font-medium text-n1-ww-gray-900 dark:text-white mb-2\">\n Create Session\n </h3>\n <p className=\"text-n1-ww-gray-500 dark:text-n1-ww-gray-400\">\n Please authenticate to create a new session.\n </p>\n </div>\n\n <button\n onClick={handleSign}\n onMouseEnter={() => setIsHovered(true)}\n onMouseLeave={() => {\n setIsHovered(false);\n setIsPressed(false);\n }}\n onMouseDown={() => setIsPressed(true)}\n onMouseUp={() => setIsPressed(false)}\n disabled={!NTSComponents || !keyPair}\n className={`\n group relative w-full overflow-hidden rounded-md border-2 bg-n1-ww-gray-100 dark:bg-neutral-950 py-4 text-left\n transition-all duration-300 ${ANIMATION_EASE}\n ${\n !NTSComponents || !keyPair\n ? 'cursor-not-allowed border-n1-ww-gray-200 dark:border-n1-ww-gray-800 opacity-50'\n : 'cursor-pointer border-n1-ww-gray-200 dark:border-n1-ww-gray-800 hover:border-n1-ww-gray-400 dark:hover:border-white/60'\n }\n `}\n style={{\n transform:\n isPressed && (!NTSComponents || !keyPair)\n ? 'scale(0.98)'\n : isHovered && (!NTSComponents || !keyPair)\n ? 'scale(0.99)'\n : 'scale(1)',\n }}\n >\n <div className=\"relative z-[200] pl-4 isolate\">\n <div className=\"flex items-center justify-start\">\n <span\n className={`\n text-base font-medium tracking-wide transition-colors duration-300 ${ANIMATION_EASE}\n text-n1-ww-gray-500 dark:text-neutral-400 group-hover:text-n1-ww-gray-900 dark:group-hover:text-white\n `}\n >\n Authenticate\n </span>\n </div>\n </div>\n </button>\n\n <BackButton\n onClick={() => {\n logger.debug('BackButton clicked');\n setDynamicWallet(null);\n setAddress('');\n dynamicHandleLogOut();\n setViewMode(N1ModalViewMode.Connect);\n }}\n />\n </div>\n </div>\n </div>\n );\n}\n"]}
1
+ {"version":3,"file":"CreateSessionView.js","sourceRoot":"","sources":["../../../../src/Modal/NTSFlow/views/CreateSessionView.tsx"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,OAAO,EAAE,SAAS,EAAE,QAAQ,EAAE,MAAM,OAAO,CAAC;AAC5C,OAAO,EAAE,cAAc,EAAE,MAAM,0BAA0B,CAAC;AAC1D,OAAO,EAAE,WAAW,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;AACrE,OAAO,EACL,gBAAgB,EA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C;gCACtB,WAAW,CAAC,eAAe,CAAC,OAAO,CAAC,CAAC;4BACvC,CAAC,GACD,IACE,GACF,IACF,CACP,CAAC;AACJ,CAAC","sourcesContent":["import { useEffect, useState } from 'react';\nimport { ANIMATION_EASE } from '../../NordFlow/constants';\nimport { WalletError, WalletErrorCode } from '../../../errors/types';\nimport {\n createWebSession,\n generateSessionKeyPair,\n getUser,\n storeSessionKeysInLocalStorage,\n} from '../../../Logic/utils';\nimport {\n useN1WalletContext,\n useN1WalletInternalContext,\n} from '../../../Provider/hooks';\nimport { N1ModalViewMode } from '../../../Provider/types';\nimport { logger } from '../../../utils/logger';\nimport { BackButton } from '../components/BackButton';\nimport { ModalHeader } from '../components/ModalHeader';\nimport { signEd25519 } from '@n1xyz/nts-sdk';\n\nexport function CreateSessionView() {\n const [isHovered, setIsHovered] = useState(false);\n const [isPressed, setIsPressed] = useState(false);\n\n const [NTSComponents, setNTSComponents] = useState<any>(null);\n const [keyPair, setKeyPair] = useState<{\n publicKey: Uint8Array;\n privateKey: Uint8Array;\n } | null>(null);\n\n const {\n setViewMode,\n setUsername,\n setStartClosingLogin,\n setIsConnected,\n dynamicWallet,\n handleError,\n setSessionPubKey,\n setSignMessageWithSessionKey,\n dynamicHandleLogOut,\n setDynamicWallet,\n setAddress,\n setSignMessageWithWalletKey,\n } = useN1WalletInternalContext();\n\n const { ntsInterface, walletPubKey, address } = useN1WalletContext();\n\n // Initialize NTS SDK and generate key pair\n useEffect(() => {\n const loadNTSSDK = async () => {\n try {\n const { Transaction, AdminAction, CoreApps } = await import(\n '@n1xyz/nts-sdk'\n );\n setNTSComponents({ Transaction, AdminAction, CoreApps });\n const newKeyPair = await generateSessionKeyPair();\n setKeyPair(newKeyPair);\n } catch (error) {\n handleError(\n new WalletError(\n WalletErrorCode.CONNECTION_FAILED,\n 'Failed to initialize NTS SDK',\n { originalError: error }\n )\n );\n }\n };\n loadNTSSDK();\n }, [handleError]);\n\n const signWithWallet = async (msg: string): Promise<Uint8Array> => {\n try {\n if (!dynamicWallet) {\n throw new WalletError(\n WalletErrorCode.WALLET_NOT_FOUND,\n 'Wallet not found for signing'\n );\n }\n\n if (dynamicWallet.chain === 'SOL') {\n const signature = await dynamicWallet.signMessage(msg);\n const binaryString = atob(signature);\n const signatureUint8Array = new Uint8Array(binaryString.length);\n for (let i = 0; i < binaryString.length; i++) {\n signatureUint8Array[i] = binaryString.charCodeAt(i);\n }\n return signatureUint8Array;\n }\n\n const sig = (await dynamicWallet.signMessage(msg)) as string;\n logger.debug('Wallet signature received', { signature: sig });\n return Uint8Array.from(Buffer.from(sig.slice(2), 'hex'));\n } catch (error) {\n throw new WalletError(\n WalletErrorCode.USER_REJECTED,\n 'Failed to sign message with wallet',\n { originalError: error }\n );\n }\n };\n\n const handleSign = async () => {\n logger.debug('handleSign');\n\n if (!NTSComponents || !keyPair) {\n logger.warn('Required components not initialized');\n return;\n }\n\n setViewMode(N1ModalViewMode.Signing);\n\n try {\n const sessionKeyHex = Buffer.from(keyPair.publicKey).toString('hex');\n logger.debug('Generated session key', { sessionKey: sessionKeyHex });\n\n // Create and sign transaction that registers the session key with Core\n const transactionData = {\n appId: NTSComponents.CoreApps.Admin,\n action: NTSComponents.AdminAction.addSessionKey,\n framework: 'ts',\n data: [\n {\n sessionKey: sessionKeyHex,\n appId: 'hub',\n },\n ],\n };\n\n setSignMessageWithWalletKey(signWithWallet);\n const tx = new NTSComponents.Transaction(transactionData, walletPubKey!);\n await tx.signWithWalletFunction(signWithWallet);\n try {\n const txRes = await ntsInterface.sendTransaction(\n tx,\n tx.signature!,\n walletPubKey\n );\n if (txRes.success) {\n logger.debug('txRes', txRes);\n } else {\n logger.debug('txRes', txRes);\n throw new WalletError(\n WalletErrorCode.TRANSACTION_FAILED,\n 'Transaction failed'\n );\n }\n } catch (_) {\n throw new WalletError(\n WalletErrorCode.TRANSACTION_FAILED,\n 'Transaction did not succeed'\n );\n }\n\n // Create session signing function\n const signFn = async (message: Uint8Array) => {\n try {\n return await signEd25519(message, keyPair.privateKey as Uint8Array);\n } catch (_) {\n logger.error('Error signing with Ed25519:', _);\n throw _;\n }\n };\n\n // Store session keys\n logger.debug('Storing session keys');\n storeSessionKeysInLocalStorage({\n privKey: keyPair.privateKey as Uint8Array,\n publicKey: keyPair.publicKey as Uint8Array,\n walletPublicKey: address,\n chainName: dynamicWallet!.chain,\n });\n setSessionPubKey(keyPair.publicKey);\n setSignMessageWithSessionKey(() => signFn);\n\n // Initialize web session with Argus who verifies that the session is\n // registered with Core, and if so, grants you access to its user metadata db\n await createWebSession(signFn, keyPair.publicKey, walletPubKey);\n\n // Check for existing user\n // TODO: handle case for auth.users, currently user.name is a wallet_only_users namespacing\n const user = await getUser();\n if (user?.name) {\n logger.info('Existing user found, completing login');\n setUsername(user.name);\n localStorage.setItem(`n1_${address}_username`, user.name);\n setStartClosingLogin(true);\n setIsConnected(true);\n } else {\n logger.info('No user found, transitioning to user creation');\n setViewMode(N1ModalViewMode.CreatingUser);\n }\n } catch (error: any) {\n logger.error('Session creation failed:', error);\n if (error.name === 'WalletError') {\n handleError(error);\n } else {\n handleError(\n new WalletError(\n WalletErrorCode.CONNECTION_FAILED,\n 'Failed to create session',\n { originalError: JSON.stringify(error) }\n )\n );\n }\n\n setViewMode(N1ModalViewMode.CreateSession);\n }\n };\n\n return (\n <div className=\"bg-n1-ww-gray-50 dark:bg-n1-ww-gray-950 relative border border-n1-ww-gray-200 dark:border-n1-ww-gray-800 rounded-md transition-[max-width,transform,opacity] duration-[3000ms] ease-[cubic-bezier(0.16,1,0.3,1)] w-full max-w-sm m-4 origin-center will-change-[max-width,transform,opacity]\">\n <div className=\"p-6 border-b border-n1-ww-gray-200 dark:border-n1-ww-gray-800\">\n <ModalHeader />\n </div>\n\n <div className=\"p-6 overflow-hidden relative\">\n <div className=\"space-y-4\">\n <div className=\"text-center\">\n <h3 className=\"text-xl font-medium text-n1-ww-gray-900 dark:text-white mb-2\">\n Create Session\n </h3>\n <p className=\"text-n1-ww-gray-500 dark:text-n1-ww-gray-400\">\n Please authenticate to create a new session.\n </p>\n </div>\n\n <button\n onClick={handleSign}\n onMouseEnter={() => setIsHovered(true)}\n onMouseLeave={() => {\n setIsHovered(false);\n setIsPressed(false);\n }}\n onMouseDown={() => setIsPressed(true)}\n onMouseUp={() => setIsPressed(false)}\n disabled={!NTSComponents || !keyPair}\n className={`\n group relative w-full overflow-hidden rounded-md border-2 bg-n1-ww-gray-100 dark:bg-neutral-950 py-4 text-left\n transition-all duration-300 ${ANIMATION_EASE}\n ${\n !NTSComponents || !keyPair\n ? 'cursor-not-allowed border-n1-ww-gray-200 dark:border-n1-ww-gray-800 opacity-50'\n : 'cursor-pointer border-n1-ww-gray-200 dark:border-n1-ww-gray-800 hover:border-n1-ww-gray-400 dark:hover:border-white/60'\n }\n `}\n style={{\n transform:\n isPressed && (!NTSComponents || !keyPair)\n ? 'scale(0.98)'\n : isHovered && (!NTSComponents || !keyPair)\n ? 'scale(0.99)'\n : 'scale(1)',\n }}\n >\n <div className=\"relative z-[200] pl-4 isolate\">\n <div className=\"flex items-center justify-start\">\n <span\n className={`\n text-base font-medium tracking-wide transition-colors duration-300 ${ANIMATION_EASE}\n text-n1-ww-gray-500 dark:text-neutral-400 group-hover:text-n1-ww-gray-900 dark:group-hover:text-white\n `}\n >\n Authenticate\n </span>\n </div>\n </div>\n </button>\n\n <BackButton\n onClick={() => {\n logger.debug('BackButton clicked');\n setDynamicWallet(null);\n setAddress('');\n dynamicHandleLogOut();\n setViewMode(N1ModalViewMode.Connect);\n }}\n />\n </div>\n </div>\n </div>\n );\n}\n"]}
@@ -186,7 +186,7 @@ export function AmountInputScreen() {
186
186
  }, [balance, hardcodedMinDeposit]);
187
187
  // Format the balance with the appropriate number of decimal places
188
188
  var formattedBalance = formatAmount(balance, tokenDecimals);
189
- return (_jsxs("div", { className: "overflow-hidden relative", children: [showFaucetOverlay && (_jsx("div", { className: "absolute inset-0 z-10 bg-white/70 dark:bg-neutral-900/80 backdrop-blur-md flex flex-col items-center justify-center p-6", children: isFaucetLoading ? (_jsxs(_Fragment, { children: [_jsx(LoadingSquares, {}), _jsxs("div", { className: "space-y-2 text-center mt-4", children: [_jsx("h3", { className: "text-xl text-n1-ww-gray-800 dark:text-white font-semibold", children: "Obtaining Testnet Tokens" }), _jsx("p", { className: "text-sm text-n1-ww-gray-500 dark:text-neutral-400", children: "Please wait while we request testnet tokens for your wallet..." })] })] })) : showFaucetSuccess ? (_jsxs(_Fragment, { children: [_jsx("div", { className: "text-green-500 text-5xl mb-4 n1-ww-animate-fade-up", children: "\u2713" }), _jsxs("div", { className: "space-y-2 text-center", children: [_jsx("h3", { className: "text-xl text-n1-ww-gray-800 dark:text-white font-semibold", children: "Tokens Obtained Successfully" }), _jsx("p", { className: "text-sm text-green-500 dark:text-green-400", children: "Your wallet has been funded with testnet tokens." }), _jsx("p", { className: "text-sm text-n1-ww-gray-500 dark:text-neutral-400 mt-2", children: "Please wait while your balance updates..." })] })] })) : faucetError ? (_jsxs(_Fragment, { children: [_jsx("div", { className: "text-red-500 text-5xl mb-4 n1-ww-animate-fade-up", children: "\u26A0\uFE0F" }), _jsxs("div", { className: "space-y-2 text-center", children: [_jsx("h3", { className: "text-xl text-n1-ww-gray-800 dark:text-white font-semibold", children: "Failed to Get Tokens" }), _jsx("p", { className: "text-sm text-red-500 dark:text-red-400", children: faucetError }), _jsx("button", { onClick: requestTestnetTokens, className: "mt-4 px-4 py-2 bg-n1-ww-main text-white rounded-sm hover:bg-n1-ww-main/90 transition-colors", children: "Try Again" })] })] })) : null })), _jsx("h2", { className: "text-xl text-n1-ww-gray-800 dark:text-white font-semibold mb-6 text-center", children: "Enter Amount" }), _jsxs("div", { className: "space-y-6", children: [_jsxs("div", { className: "relative border-2 border-n1-ww-gray-200 dark:border-n1-ww-gray-800 bg-n1-ww-gray-100 dark:bg-n1-ww-gray-900 rounded-sm p-0 overflow-hidden n1-ww-animate-fade-up", style: { animationDelay: '0.1s' }, children: [_jsxs("div", { className: "flex items-center justify-between p-4 border-b border-n1-ww-gray-200 dark:border-n1-ww-gray-800 bg-white/30 dark:bg-black/10", children: [_jsxs("div", { className: "flex items-center space-x-3", children: [_jsx("div", { className: "w-8 h-8 rounded-full overflow-hidden bg-white dark:bg-n1-ww-gray-800 flex items-center justify-center shadow-sm", children: _jsx(ImageWithFallback, { src: tokenLogo, alt: tokenSymbol, width: 24, height: 24, fallbackText: tokenSymbol.charAt(0), fallbackClassName: "w-6 h-6 rounded-full flex items-center justify-center", fallbackBgColor: "bg-blue-100 dark:bg-blue-900", fallbackTextColor: "text-blue-500 dark:text-blue-300" }) }), _jsx("span", { className: "text-n1-ww-gray-800 dark:text-white font-medium", children: tokenSymbol })] }), _jsx("div", { className: "text-xs rounded-sm bg-n1-ww-gray-200 dark:bg-n1-ww-gray-800 px-2 py-1 text-n1-ww-gray-600 dark:text-n1-ww-gray-300", children: "Fixed Amount" })] }), _jsxs("div", { className: "relative p-6 flex flex-col items-center", children: [_jsxs("div", { className: "relative flex items-baseline justify-center w-full", children: [_jsx("span", { className: "text-4xl font-bold text-n1-ww-gray-800 dark:text-white mr-1 n1-ww-animate-fade-up", style: { animationDelay: '0.2s' }, children: amount }), _jsx("span", { className: "text-xl text-n1-ww-gray-500 dark:text-neutral-400 ml-1 n1-ww-animate-fade-up", style: { animationDelay: '0.3s' }, children: tokenSymbol })] }), _jsx("div", { className: "w-16 h-1 bg-n1-ww-gray-200 dark:bg-n1-ww-gray-800 rounded-full mt-4 mb-2" }), _jsx("div", { className: "flex justify-center items-center text-sm mt-2 w-full n1-ww-animate-fade-up", style: { animationDelay: '0.4s' }, children: _jsxs("span", { className: "text-n1-ww-gray-500 dark:text-neutral-400", children: ["Balance: ", formattedBalance, " ", tokenSymbol] }) })] })] }), context.depositError && (_jsx("div", { className: "bg-red-100 dark:bg-red-900/30 text-red-600 dark:text-red-400 p-3 rounded-sm text-sm border border-red-200 dark:border-red-800 n1-ww-animate-fade-up", style: { animationDelay: '0.5s' }, children: context.depositError })), _jsx("button", { onClick: startDeposit, disabled: !isValidAmount, onMouseEnter: function () { return setIsHovered(true); }, onMouseLeave: function () { return setIsHovered(false); }, className: "\n group relative w-full overflow-hidden rounded-sm border-2 bg-n1-ww-gray-100 dark:bg-neutral-950 py-4 text-center\n transition-all duration-300 ".concat(ANIMATION_EASE, " n1-ww-animate-fade-up\n ").concat(isValidAmount
189
+ return (_jsxs("div", { className: "overflow-hidden relative", children: [showFaucetOverlay && (_jsx("div", { className: "absolute inset-0 z-10 bg-white/70 dark:bg-neutral-900/80 backdrop-blur-md flex flex-col items-center justify-center p-6", children: isFaucetLoading ? (_jsxs(_Fragment, { children: [_jsx(LoadingSquares, {}), _jsxs("div", { className: "space-y-2 text-center mt-4", children: [_jsx("h3", { className: "text-xl text-n1-ww-gray-800 dark:text-white font-semibold", children: "Obtaining Testnet Tokens" }), _jsx("p", { className: "text-sm text-n1-ww-gray-500 dark:text-neutral-400", children: "Please wait while we request testnet tokens for your wallet..." })] })] })) : showFaucetSuccess ? (_jsxs(_Fragment, { children: [_jsx("div", { className: "text-green-500 text-5xl mb-4 n1-ww-animate-fade-up", children: "\u2713" }), _jsxs("div", { className: "space-y-2 text-center", children: [_jsx("h3", { className: "text-xl text-n1-ww-gray-800 dark:text-white font-semibold", children: "Tokens Obtained Successfully" }), _jsx("p", { className: "text-sm text-green-500 dark:text-green-400", children: "Your wallet has been funded with testnet tokens." }), _jsx("p", { className: "text-sm text-n1-ww-gray-500 dark:text-neutral-400 mt-2", children: "Please wait while your balance updates..." })] })] })) : faucetError ? (_jsxs(_Fragment, { children: [_jsx("div", { className: "text-red-500 text-5xl mb-4 n1-ww-animate-fade-up", children: "\u26A0\uFE0F" }), _jsxs("div", { className: "space-y-2 text-center", children: [_jsx("h3", { className: "text-xl text-n1-ww-gray-800 dark:text-white font-semibold", children: "Failed to Get Tokens" }), _jsx("p", { className: "text-sm text-red-500 dark:text-red-400", children: faucetError }), _jsx("button", { onClick: requestTestnetTokens, className: "mt-4 px-4 py-2 bg-n1-ww-main text-white rounded-sm hover:bg-n1-ww-main/90 transition-colors", children: "Try Again" })] })] })) : null })), _jsx("h2", { className: "text-xl text-n1-ww-gray-800 dark:text-white font-semibold mb-6 text-center", children: "Enter Amount" }), _jsxs("div", { className: "space-y-6", children: [_jsxs("div", { className: "relative border-2 border-n1-ww-gray-200 dark:border-n1-ww-gray-800 bg-n1-ww-gray-100 dark:bg-n1-ww-gray-900 rounded-sm p-0 overflow-hidden n1-ww-animate-fade-up", style: { animationDelay: '0.1s' }, children: [_jsxs("div", { className: "flex items-center justify-between p-4 border-b border-n1-ww-gray-200 dark:border-n1-ww-gray-800 bg-white/30 dark:bg-black/10", children: [_jsxs("div", { className: "flex items-center space-x-3", children: [_jsx("div", { className: "w-8 h-8 rounded-full overflow-hidden bg-white dark:bg-n1-ww-gray-800 flex items-center justify-center shadow-sm", children: _jsx(ImageWithFallback, { src: tokenLogo, alt: tokenSymbol, width: 24, height: 24, fallbackText: tokenSymbol.charAt(0), fallbackClassName: "w-6 h-6 rounded-full flex items-center justify-center", fallbackBgColor: "bg-blue-100 dark:bg-blue-900", fallbackTextColor: "text-blue-500 dark:text-blue-300" }) }), _jsx("span", { className: "text-n1-ww-gray-800 dark:text-white font-medium", children: tokenSymbol })] }), _jsx("div", { className: "text-xs rounded-sm bg-n1-ww-gray-200 dark:bg-n1-ww-gray-800 px-2 py-1 text-n1-ww-gray-600 dark:text-n1-ww-gray-300", children: "Fixed Amount" })] }), _jsx("div", { className: "mb-4 w-full flex items-center justify-center", children: _jsxs("div", { className: "bg-yellow-50 dark:bg-yellow-900/40 border border-yellow-200 dark:border-yellow-700 text-yellow-800 dark:text-yellow-200 rounded px-3 py-2 text-sm text-center max-w-xl mx-auto shadow-sm", children: [_jsx("span", { className: "font-semibold", children: "Testnet Only:" }), " Please make sure your wallet is set to ", _jsx("span", { className: "font-semibold", children: "testnet mode" }), " before proceeding. ", _jsx("a", { href: "https://docs.phantom.com/developer-powertools/testnet-mode", target: "_blank", rel: "noopener noreferrer", className: "underline text-yellow-700 dark:text-yellow-200 hover:text-yellow-900 dark:hover:text-yellow-100 transition-colors", children: "Learn how to switch to testnet" }), "."] }) }), _jsxs("div", { className: "relative p-6 flex flex-col items-center", children: [_jsxs("div", { className: "relative flex items-baseline justify-center w-full", children: [_jsx("span", { className: "text-4xl font-bold text-n1-ww-gray-800 dark:text-white mr-1 n1-ww-animate-fade-up", style: { animationDelay: '0.2s' }, children: amount }), _jsx("span", { className: "text-xl text-n1-ww-gray-500 dark:text-neutral-400 ml-1 n1-ww-animate-fade-up", style: { animationDelay: '0.3s' }, children: tokenSymbol })] }), _jsx("div", { className: "w-16 h-1 bg-n1-ww-gray-200 dark:bg-n1-ww-gray-800 rounded-full mt-4 mb-2" }), _jsx("div", { className: "flex justify-center items-center text-sm mt-2 w-full n1-ww-animate-fade-up", style: { animationDelay: '0.4s' }, children: _jsxs("span", { className: "text-n1-ww-gray-500 dark:text-neutral-400", children: ["Balance: ", formattedBalance, " ", tokenSymbol] }) })] })] }), context.depositError && (_jsx("div", { className: "bg-red-100 dark:bg-red-900/30 text-red-600 dark:text-red-400 p-3 rounded-sm text-sm border border-red-200 dark:border-red-800 n1-ww-animate-fade-up", style: { animationDelay: '0.5s' }, children: context.depositError })), _jsx("button", { onClick: startDeposit, disabled: !isValidAmount, onMouseEnter: function () { return setIsHovered(true); }, onMouseLeave: function () { return setIsHovered(false); }, className: "\n group relative w-full overflow-hidden rounded-sm border-2 bg-n1-ww-gray-100 dark:bg-neutral-950 py-4 text-center\n transition-all duration-300 ".concat(ANIMATION_EASE, " n1-ww-animate-fade-up\n ").concat(isValidAmount
190
190
  ? 'cursor-pointer border-n1-ww-gray-200 dark:border-n1-ww-gray-800 hover:border-n1-ww-gray-400 dark:hover:border-white/60'
191
191
  : 'cursor-not-allowed border-n1-gray-200 dark:border-n1-gray-800 opacity-50', "\n "), style: {
192
192
  transform: isHovered && isValidAmount ? 'scale(0.99)' : 'scale(1)',
@@ -1 +1 @@
1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,EACxB,YAAY,EAAE,cAAM,OAAA,YAAY,CAAC,IAAI,CAAC,EAAlB,CAAkB,EACtC,YAAY,EAAE,cAAM,OAAA,YAAY,CAAC,KAAK,CAAC,EAAnB,CAAmB,EACvC,SAAS,EAAE,kLAEqB,cAAc,iDAC1C,aAAa;4BACb,CAAC,CAAC,wHAAwH;4BAC1H,CAAC,CAAC,0EAA0E,iBAE/E,EACD,KAAK,EAAE;4BACL,SAAS,EAAE,SAAS,IAAI,aAAa,CAAC,CAAC,CAAC,aAAa,CAAC,CAAC,CAAC,UAAU;4BAClE,cAAc,EAAE,MAAM;yBACvB,YAED,eACE,SAAS,EAAE,6FAC4D,cAAc,6BACjF,aAAa;gCACb,CAAC,CAAC,0GAA0G;gCAC5G,CAAC,CAAC,8CAA8C,mBAEnD,yBAGI,GACA,IACL,IACF,CACP,CAAC;AACJ,CAAC","sourcesContent":["import { useCallback, useEffect, useRef, useState } from 'react';\nimport {\n useN1WalletContext,\n useN1WalletInternalContext,\n} from '../../../Provider/hooks';\nimport { ImageWithFallback } from '../components';\nimport { ANIMATION_EASE } from '../constants';\nimport { formatAmount, isNordConfigured } from '../utils/nordUtils';\nimport { useDepositContext } from '../context/DepositContext';\nimport { useFlowStateContext } from '../context/FlowContext';\nimport { LoadingSquares } from '../components/LoadingSquares';\n\nexport function AmountInputScreen() {\n const { context } = useFlowStateContext();\n const { updateAmount, startDeposit } = useDepositContext();\n const { address, nord } = useN1WalletContext();\n const { faucetUrl: contextFaucetUrl } = useN1WalletInternalContext();\n\n // Hard code amount to 100\n const amount = '100';\n // Hard code balance to 0 to allow faucet to trigger\n const balance = 100;\n\n // Force the amount to be 100 on component mount only, not on every render\n useEffect(() => {\n updateAmount('100');\n // Empty dependency array ensures this only runs once on mount\n }, [updateAmount]);\n\n const [isHovered, setIsHovered] = useState(false);\n const [isFaucetLoading, setIsFaucetLoading] = useState(false);\n const [faucetError, setFaucetError] = useState<string | null>(null);\n const [tokensObtained, setTokensObtained] = useState(false);\n const [showFaucetSuccess, setShowFaucetSuccess] = useState(false);\n const prevBalanceRef = useRef(balance);\n\n const faucetUrl = contextFaucetUrl;\n\n // Get token information from Nord if available\n const [tokenSymbol, setTokenSymbol] = useState('USDC');\n const [tokenLogo, setTokenLogo] = useState('/images/tokens/usdc.svg');\n const [tokenDecimals, setTokenDecimals] = useState(6);\n\n // Try to get token information from Nord\n useEffect(() => {\n if (nord && isNordConfigured(nord)) {\n try {\n // Find the USDC token or the first token\n const usdcToken =\n nord.tokens.find((t: any) => t.symbol === 'USDC') || nord.tokens[0];\n if (usdcToken) {\n setTokenSymbol(usdcToken.symbol);\n // Use a default logo if not available\n setTokenLogo(`/images/tokens/${usdcToken.symbol.toLowerCase()}.svg`);\n setTokenDecimals(usdcToken.decimals);\n }\n } catch (error) {\n console.warn('Error getting token information from Nord:', error);\n }\n }\n }, [nord]);\n\n // Removed handleAmountChange since we don't want user to edit the amount\n\n // todo:fix\n const isValidAmount = true;\n\n const hardcodedMinDeposit = 100;\n\n // Check if faucet is enabled and balance is low\n const shouldShowFaucet = faucetUrl && !tokensObtained;\n\n // Determine if we should show the faucet overlay\n const showFaucetOverlay =\n (shouldShowFaucet && (isFaucetLoading || faucetError)) || showFaucetSuccess;\n\n // Function to refresh balances\n const refreshBalance = useCallback(async () => {\n // \n }, [nord]);\n\n // Function to request tokens from faucet\n const requestTestnetTokens = useCallback(async () => {\n if (!faucetUrl || !address) return;\n\n try {\n setIsFaucetLoading(true);\n setFaucetError(null);\n setShowFaucetSuccess(false);\n\n const response = await fetch(faucetUrl, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({ address }),\n });\n\n if (!response.ok) {\n const errorData = await response\n .json()\n .catch(() => ({ error: 'Failed to request tokens' }));\n throw new Error(errorData.error || 'Failed to request tokens');\n }\n\n await response.json();\n\n // Mark tokens as obtained to prevent further requests\n setTokensObtained(true);\n\n // Show success message\n setShowFaucetSuccess(true);\n\n // Refresh balance\n await refreshBalance();\n\n setShowFaucetSuccess(false);\n } catch (error) {\n console.error('Faucet error:', error);\n setFaucetError(\n error instanceof Error ? error.message : 'Failed to request tokens'\n );\n } finally {\n setIsFaucetLoading(false);\n }\n }, [faucetUrl, address, refreshBalance]);\n\n // Request tokens automatically when faucet is enabled and balance is low\n useEffect(() => {\n if (\n shouldShowFaucet &&\n !isFaucetLoading &&\n !faucetError &&\n !showFaucetSuccess &&\n context.depositError == null\n ) {\n requestTestnetTokens();\n }\n }, [\n shouldShowFaucet,\n isFaucetLoading,\n faucetError,\n showFaucetSuccess,\n requestTestnetTokens,\n context.depositError\n ]);\n\n // Reset tokensObtained state if balance changes to a higher value\n useEffect(() => {\n // If balance has increased and is now sufficient, reset the tokensObtained flag\n if (balance > prevBalanceRef.current && balance >= hardcodedMinDeposit) {\n setTokensObtained(false);\n setShowFaucetSuccess(false);\n }\n\n // Update the previous balance reference\n prevBalanceRef.current = balance;\n }, [balance, hardcodedMinDeposit]);\n\n // Format the balance with the appropriate number of decimal places\n const formattedBalance = formatAmount(balance, tokenDecimals);\n\n return (\n <div className=\"overflow-hidden relative\">\n {/* Faucet Overlay */}\n {showFaucetOverlay && (\n <div className=\"absolute inset-0 z-10 bg-white/70 dark:bg-neutral-900/80 backdrop-blur-md flex flex-col items-center justify-center p-6\">\n {isFaucetLoading ? (\n <>\n <LoadingSquares />\n <div className=\"space-y-2 text-center mt-4\">\n <h3 className=\"text-xl text-n1-ww-gray-800 dark:text-white font-semibold\">\n Obtaining Testnet Tokens\n </h3>\n <p className=\"text-sm text-n1-ww-gray-500 dark:text-neutral-400\">\n Please wait while we request testnet tokens for your wallet...\n </p>\n </div>\n </>\n ) : showFaucetSuccess ? (\n <>\n <div className=\"text-green-500 text-5xl mb-4 n1-ww-animate-fade-up\">✓</div>\n <div className=\"space-y-2 text-center\">\n <h3 className=\"text-xl text-n1-ww-gray-800 dark:text-white font-semibold\">\n Tokens Obtained Successfully\n </h3>\n <p className=\"text-sm text-green-500 dark:text-green-400\">\n Your wallet has been funded with testnet tokens.\n </p>\n <p className=\"text-sm text-n1-ww-gray-500 dark:text-neutral-400 mt-2\">\n Please wait while your balance updates...\n </p>\n </div>\n </>\n ) : faucetError ? (\n <>\n <div className=\"text-red-500 text-5xl mb-4 n1-ww-animate-fade-up\">⚠️</div>\n <div className=\"space-y-2 text-center\">\n <h3 className=\"text-xl text-n1-ww-gray-800 dark:text-white font-semibold\">\n Failed to Get Tokens\n </h3>\n <p className=\"text-sm text-red-500 dark:text-red-400\">\n {faucetError}\n </p>\n <button\n onClick={requestTestnetTokens}\n className=\"mt-4 px-4 py-2 bg-n1-ww-main text-white rounded-sm hover:bg-n1-ww-main/90 transition-colors\"\n >\n Try Again\n </button>\n </div>\n </>\n ) : null}\n </div>\n )}\n\n <h2 className=\"text-xl text-n1-ww-gray-800 dark:text-white font-semibold mb-6 text-center\">\n Enter Amount\n </h2>\n\n {/* Amount Input */}\n <div className=\"space-y-6\">\n {/* Token Selection and Amount Input */}\n <div className=\"relative border-2 border-n1-ww-gray-200 dark:border-n1-ww-gray-800 bg-n1-ww-gray-100 dark:bg-n1-ww-gray-900 rounded-sm p-0 overflow-hidden n1-ww-animate-fade-up\" style={{ animationDelay: '0.1s' }}>\n {/* Token Selection Header */}\n <div className=\"flex items-center justify-between p-4 border-b border-n1-ww-gray-200 dark:border-n1-ww-gray-800 bg-white/30 dark:bg-black/10\">\n <div className=\"flex items-center space-x-3\">\n <div className=\"w-8 h-8 rounded-full overflow-hidden bg-white dark:bg-n1-ww-gray-800 flex items-center justify-center shadow-sm\">\n <ImageWithFallback\n src={tokenLogo}\n alt={tokenSymbol}\n width={24}\n height={24}\n fallbackText={tokenSymbol.charAt(0)}\n fallbackClassName=\"w-6 h-6 rounded-full flex items-center justify-center\"\n fallbackBgColor=\"bg-blue-100 dark:bg-blue-900\"\n fallbackTextColor=\"text-blue-500 dark:text-blue-300\"\n />\n </div>\n <span className=\"text-n1-ww-gray-800 dark:text-white font-medium\">\n {tokenSymbol}\n </span>\n </div>\n <div className=\"text-xs rounded-sm bg-n1-ww-gray-200 dark:bg-n1-ww-gray-800 px-2 py-1 text-n1-ww-gray-600 dark:text-n1-ww-gray-300\">\n Fixed Amount\n </div>\n </div>\n\n {/* Amount Input - Hardcoded to 100 */}\n <div className=\"relative p-6 flex flex-col items-center\">\n <div className=\"relative flex items-baseline justify-center w-full\">\n <span className=\"text-4xl font-bold text-n1-ww-gray-800 dark:text-white mr-1 n1-ww-animate-fade-up\" style={{ animationDelay: '0.2s' }}>\n {amount}\n </span>\n <span className=\"text-xl text-n1-ww-gray-500 dark:text-neutral-400 ml-1 n1-ww-animate-fade-up\" style={{ animationDelay: '0.3s' }}>\n {tokenSymbol}\n </span>\n </div>\n\n {/* Decorative element */}\n <div className=\"w-16 h-1 bg-n1-ww-gray-200 dark:bg-n1-ww-gray-800 rounded-full mt-4 mb-2\"></div>\n\n {/* Balance Display */}\n <div className=\"flex justify-center items-center text-sm mt-2 w-full n1-ww-animate-fade-up\" style={{ animationDelay: '0.4s' }}>\n <span className=\"text-n1-ww-gray-500 dark:text-neutral-400\">\n Balance: {formattedBalance} {tokenSymbol}\n </span>\n </div>\n </div>\n </div>\n\n {/* Error Message */}\n {context.depositError && (\n <div className=\"bg-red-100 dark:bg-red-900/30 text-red-600 dark:text-red-400 p-3 rounded-sm text-sm border border-red-200 dark:border-red-800 n1-ww-animate-fade-up\" style={{ animationDelay: '0.5s' }}>\n {context.depositError}\n </div>\n )}\n\n {/* Continue Button */}\n <button\n onClick={startDeposit}\n disabled={!isValidAmount}\n onMouseEnter={() => setIsHovered(true)}\n onMouseLeave={() => setIsHovered(false)}\n className={`\n group relative w-full overflow-hidden rounded-sm border-2 bg-n1-ww-gray-100 dark:bg-neutral-950 py-4 text-center\n transition-all duration-300 ${ANIMATION_EASE} n1-ww-animate-fade-up\n ${isValidAmount\n ? 'cursor-pointer border-n1-ww-gray-200 dark:border-n1-ww-gray-800 hover:border-n1-ww-gray-400 dark:hover:border-white/60'\n : 'cursor-not-allowed border-n1-gray-200 dark:border-n1-gray-800 opacity-50'\n }\n `}\n style={{\n transform: isHovered && isValidAmount ? 'scale(0.99)' : 'scale(1)',\n animationDelay: '0.6s'\n }}\n >\n <span\n className={`\n text-base font-medium tracking-wide transition-colors duration-300 ${ANIMATION_EASE}\n ${isValidAmount\n ? 'text-n1-ww-gray-700 dark:text-n1-ww-gray-300 group-hover:text-n1-ww-gray-900 dark:group-hover:text-white'\n : 'text-n1-ww-gray-400 dark:text-n1-ww-gray-600'\n }\n `}\n >\n Continue\n </span>\n </button>\n </div>\n </div>\n );\n}\n"]}
1
+ {"version":3,"file":"04-AmountInputScreen.js","sourceRoot":"","sources":["../../../../src/Modal/NordFlow/screens/04-AmountInputScreen.tsx"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,OAAO,EAAE,WAAW,EAAE,SAAS,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,OAAO,CAAC;AACjE,OAAO,EACL,kBAAkB,EAClB,0BAA0B,GAC3B,MAAM,yBAAyB,CAAC;AACjC,OAAO,EAAE,iBAAiB,EAAE,MAAM,eAAe,CAAC;AAClD,OAAO,EAAE,cAAc,EAAE,MAAM,cAAc,CAAC;AAC9C,OAAO,EAAE,YAAY,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AACpE,OAAO,EAAE,iBAAiB,EAAE,MAAM,2BAA2B,CAAC;AAC9D,OAAO,EAAE,mBAAmB,EAAE,MAAM,wBAAwB,CAAC;AAC7D,OAAO,EAAE,cAAc,EAAE,MAAM,8BAA8B,CAAC;AAE9D,MAAM,UAAU,iBAAiB;IAAjC,iBAmTC;IAlTS,IAAA,OAAO,GAAK,mBAAmB,EAAE,QAA1B,CAA2B;IACpC,IAAA,KAAiC,iBAAiB,EAAE,EAAlD,YAAY,kBAAA,EAAE,YAAY,kBAAwB,CAAC;IACrD,IAAA,KAAoB,kBAAkB,EAAE,EAAtC,OAAO,aAAA,EAAE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';\nimport {\n useN1WalletContext,\n useN1WalletInternalContext,\n} from '../../../Provider/hooks';\nimport { ImageWithFallback } from '../components';\nimport { ANIMATION_EASE } from '../constants';\nimport { formatAmount, isNordConfigured } from '../utils/nordUtils';\nimport { useDepositContext } from '../context/DepositContext';\nimport { useFlowStateContext } from '../context/FlowContext';\nimport { LoadingSquares } from '../components/LoadingSquares';\n\nexport function AmountInputScreen() {\n const { context } = useFlowStateContext();\n const { updateAmount, startDeposit } = useDepositContext();\n const { address, nord } = useN1WalletContext();\n const { faucetUrl: contextFaucetUrl } = useN1WalletInternalContext();\n\n // Hard code amount to 100\n const amount = '100';\n // Hard code balance to 0 to allow faucet to trigger\n const balance = 100;\n\n // Force the amount to be 100 on component mount only, not on every render\n useEffect(() => {\n updateAmount('100');\n // Empty dependency array ensures this only runs once on mount\n }, [updateAmount]);\n\n const [isHovered, setIsHovered] = useState(false);\n const [isFaucetLoading, setIsFaucetLoading] = useState(false);\n const [faucetError, setFaucetError] = useState<string | null>(null);\n const [tokensObtained, setTokensObtained] = useState(false);\n const [showFaucetSuccess, setShowFaucetSuccess] = useState(false);\n const prevBalanceRef = useRef(balance);\n\n const faucetUrl = contextFaucetUrl;\n\n // Get token information from Nord if available\n const [tokenSymbol, setTokenSymbol] = useState('USDC');\n const [tokenLogo, setTokenLogo] = useState('/images/tokens/usdc.svg');\n const [tokenDecimals, setTokenDecimals] = useState(6);\n\n // Try to get token information from Nord\n useEffect(() => {\n if (nord && isNordConfigured(nord)) {\n try {\n // Find the USDC token or the first token\n const usdcToken =\n nord.tokens.find((t: any) => t.symbol === 'USDC') || nord.tokens[0];\n if (usdcToken) {\n setTokenSymbol(usdcToken.symbol);\n // Use a default logo if not available\n setTokenLogo(`/images/tokens/${usdcToken.symbol.toLowerCase()}.svg`);\n setTokenDecimals(usdcToken.decimals);\n }\n } catch (error) {\n console.warn('Error getting token information from Nord:', error);\n }\n }\n }, [nord]);\n\n // Removed handleAmountChange since we don't want user to edit the amount\n\n // todo:fix\n const isValidAmount = true;\n\n const hardcodedMinDeposit = 100;\n\n // Check if faucet is enabled and balance is low\n const shouldShowFaucet = faucetUrl && !tokensObtained;\n\n // Determine if we should show the faucet overlay\n const showFaucetOverlay =\n (shouldShowFaucet && (isFaucetLoading || faucetError)) || showFaucetSuccess;\n\n // Function to refresh balances\n const refreshBalance = useCallback(async () => {\n // \n }, [nord]);\n\n // Function to request tokens from faucet\n const requestTestnetTokens = useCallback(async () => {\n if (!faucetUrl || !address) return;\n\n try {\n setIsFaucetLoading(true);\n setFaucetError(null);\n setShowFaucetSuccess(false);\n\n const response = await fetch(faucetUrl, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({ address }),\n });\n\n if (!response.ok) {\n const errorData = await response\n .json()\n .catch(() => ({ error: 'Failed to request tokens' }));\n throw new Error(errorData.error || 'Failed to request tokens');\n }\n\n await response.json();\n\n // Mark tokens as obtained to prevent further requests\n setTokensObtained(true);\n\n // Show success message\n setShowFaucetSuccess(true);\n\n // Refresh balance\n await refreshBalance();\n\n setShowFaucetSuccess(false);\n } catch (error) {\n console.error('Faucet error:', error);\n setFaucetError(\n error instanceof Error ? error.message : 'Failed to request tokens'\n );\n } finally {\n setIsFaucetLoading(false);\n }\n }, [faucetUrl, address, refreshBalance]);\n\n // Request tokens automatically when faucet is enabled and balance is low\n useEffect(() => {\n if (\n shouldShowFaucet &&\n !isFaucetLoading &&\n !faucetError &&\n !showFaucetSuccess &&\n context.depositError == null\n ) {\n requestTestnetTokens();\n }\n }, [\n shouldShowFaucet,\n isFaucetLoading,\n faucetError,\n showFaucetSuccess,\n requestTestnetTokens,\n context.depositError\n ]);\n\n // Reset tokensObtained state if balance changes to a higher value\n useEffect(() => {\n // If balance has increased and is now sufficient, reset the tokensObtained flag\n if (balance > prevBalanceRef.current && balance >= hardcodedMinDeposit) {\n setTokensObtained(false);\n setShowFaucetSuccess(false);\n }\n\n // Update the previous balance reference\n prevBalanceRef.current = balance;\n }, [balance, hardcodedMinDeposit]);\n\n // Format the balance with the appropriate number of decimal places\n const formattedBalance = formatAmount(balance, tokenDecimals);\n\n return (\n <div className=\"overflow-hidden relative\">\n {/* Faucet Overlay */}\n {showFaucetOverlay && (\n <div className=\"absolute inset-0 z-10 bg-white/70 dark:bg-neutral-900/80 backdrop-blur-md flex flex-col items-center justify-center p-6\">\n {isFaucetLoading ? (\n <>\n <LoadingSquares />\n <div className=\"space-y-2 text-center mt-4\">\n <h3 className=\"text-xl text-n1-ww-gray-800 dark:text-white font-semibold\">\n Obtaining Testnet Tokens\n </h3>\n <p className=\"text-sm text-n1-ww-gray-500 dark:text-neutral-400\">\n Please wait while we request testnet tokens for your wallet...\n </p>\n </div>\n </>\n ) : showFaucetSuccess ? (\n <>\n <div className=\"text-green-500 text-5xl mb-4 n1-ww-animate-fade-up\">✓</div>\n <div className=\"space-y-2 text-center\">\n <h3 className=\"text-xl text-n1-ww-gray-800 dark:text-white font-semibold\">\n Tokens Obtained Successfully\n </h3>\n <p className=\"text-sm text-green-500 dark:text-green-400\">\n Your wallet has been funded with testnet tokens.\n </p>\n <p className=\"text-sm text-n1-ww-gray-500 dark:text-neutral-400 mt-2\">\n Please wait while your balance updates...\n </p>\n </div>\n </>\n ) : faucetError ? (\n <>\n <div className=\"text-red-500 text-5xl mb-4 n1-ww-animate-fade-up\">⚠️</div>\n <div className=\"space-y-2 text-center\">\n <h3 className=\"text-xl text-n1-ww-gray-800 dark:text-white font-semibold\">\n Failed to Get Tokens\n </h3>\n <p className=\"text-sm text-red-500 dark:text-red-400\">\n {faucetError}\n </p>\n <button\n onClick={requestTestnetTokens}\n className=\"mt-4 px-4 py-2 bg-n1-ww-main text-white rounded-sm hover:bg-n1-ww-main/90 transition-colors\"\n >\n Try Again\n </button>\n </div>\n </>\n ) : null}\n </div>\n )}\n\n <h2 className=\"text-xl text-n1-ww-gray-800 dark:text-white font-semibold mb-6 text-center\">\n Enter Amount\n </h2>\n\n {/* Amount Input */}\n <div className=\"space-y-6\">\n {/* Token Selection and Amount Input */}\n <div className=\"relative border-2 border-n1-ww-gray-200 dark:border-n1-ww-gray-800 bg-n1-ww-gray-100 dark:bg-n1-ww-gray-900 rounded-sm p-0 overflow-hidden n1-ww-animate-fade-up\" style={{ animationDelay: '0.1s' }}>\n {/* Token Selection Header */}\n <div className=\"flex items-center justify-between p-4 border-b border-n1-ww-gray-200 dark:border-n1-ww-gray-800 bg-white/30 dark:bg-black/10\">\n <div className=\"flex items-center space-x-3\">\n <div className=\"w-8 h-8 rounded-full overflow-hidden bg-white dark:bg-n1-ww-gray-800 flex items-center justify-center shadow-sm\">\n <ImageWithFallback\n src={tokenLogo}\n alt={tokenSymbol}\n width={24}\n height={24}\n fallbackText={tokenSymbol.charAt(0)}\n fallbackClassName=\"w-6 h-6 rounded-full flex items-center justify-center\"\n fallbackBgColor=\"bg-blue-100 dark:bg-blue-900\"\n fallbackTextColor=\"text-blue-500 dark:text-blue-300\"\n />\n </div>\n <span className=\"text-n1-ww-gray-800 dark:text-white font-medium\">\n {tokenSymbol}\n </span>\n </div>\n <div className=\"text-xs rounded-sm bg-n1-ww-gray-200 dark:bg-n1-ww-gray-800 px-2 py-1 text-n1-ww-gray-600 dark:text-n1-ww-gray-300\">\n Fixed Amount\n </div>\n </div>\n\n {/* NOTE: Testnet Wallet Mode Reminder */}\n <div className=\"mb-4 w-full flex items-center justify-center\">\n <div className=\"bg-yellow-50 dark:bg-yellow-900/40 border border-yellow-200 dark:border-yellow-700 text-yellow-800 dark:text-yellow-200 rounded px-3 py-2 text-sm text-center max-w-xl mx-auto shadow-sm\">\n <span className=\"font-semibold\">Testnet Only:</span> Please make sure your wallet is set to <span className=\"font-semibold\">testnet mode</span> before proceeding. <a href=\"https://docs.phantom.com/developer-powertools/testnet-mode\" target=\"_blank\" rel=\"noopener noreferrer\" className=\"underline text-yellow-700 dark:text-yellow-200 hover:text-yellow-900 dark:hover:text-yellow-100 transition-colors\">Learn how to switch to testnet</a>.\n </div>\n </div>\n\n {/* Amount Input - Hardcoded to 100 */}\n <div className=\"relative p-6 flex flex-col items-center\">\n <div className=\"relative flex items-baseline justify-center w-full\">\n <span className=\"text-4xl font-bold text-n1-ww-gray-800 dark:text-white mr-1 n1-ww-animate-fade-up\" style={{ animationDelay: '0.2s' }}>\n {amount}\n </span>\n <span className=\"text-xl text-n1-ww-gray-500 dark:text-neutral-400 ml-1 n1-ww-animate-fade-up\" style={{ animationDelay: '0.3s' }}>\n {tokenSymbol}\n </span>\n </div>\n\n {/* Decorative element */}\n <div className=\"w-16 h-1 bg-n1-ww-gray-200 dark:bg-n1-ww-gray-800 rounded-full mt-4 mb-2\"></div>\n\n {/* Balance Display */}\n <div className=\"flex justify-center items-center text-sm mt-2 w-full n1-ww-animate-fade-up\" style={{ animationDelay: '0.4s' }}>\n <span className=\"text-n1-ww-gray-500 dark:text-neutral-400\">\n Balance: {formattedBalance} {tokenSymbol}\n </span>\n </div>\n </div>\n </div>\n\n {/* Error Message */}\n {context.depositError && (\n <div className=\"bg-red-100 dark:bg-red-900/30 text-red-600 dark:text-red-400 p-3 rounded-sm text-sm border border-red-200 dark:border-red-800 n1-ww-animate-fade-up\" style={{ animationDelay: '0.5s' }}>\n {context.depositError}\n </div>\n )}\n\n {/* Continue Button */}\n <button\n onClick={startDeposit}\n disabled={!isValidAmount}\n onMouseEnter={() => setIsHovered(true)}\n onMouseLeave={() => setIsHovered(false)}\n className={`\n group relative w-full overflow-hidden rounded-sm border-2 bg-n1-ww-gray-100 dark:bg-neutral-950 py-4 text-center\n transition-all duration-300 ${ANIMATION_EASE} n1-ww-animate-fade-up\n ${isValidAmount\n ? 'cursor-pointer border-n1-ww-gray-200 dark:border-n1-ww-gray-800 hover:border-n1-ww-gray-400 dark:hover:border-white/60'\n : 'cursor-not-allowed border-n1-gray-200 dark:border-n1-gray-800 opacity-50'\n }\n `}\n style={{\n transform: isHovered && isValidAmount ? 'scale(0.99)' : 'scale(1)',\n animationDelay: '0.6s'\n }}\n >\n <span\n className={`\n text-base font-medium tracking-wide transition-colors duration-300 ${ANIMATION_EASE}\n ${isValidAmount\n ? 'text-n1-ww-gray-700 dark:text-n1-ww-gray-300 group-hover:text-n1-ww-gray-900 dark:group-hover:text-white'\n : 'text-n1-ww-gray-400 dark:text-n1-ww-gray-600'\n }\n `}\n >\n Continue\n </span>\n </button>\n </div>\n </div>\n );\n}\n"]}
@@ -114,41 +114,36 @@ export function useNordUserInitialization() {
114
114
  return signTransactionWithWallet;
115
115
  };
116
116
  var createSession = function () { return __awaiter(_this, void 0, void 0, function () {
117
- var sessionKeyPair_1, storedKeys, tempKeyPair, error_3, signFn_1, error_4;
117
+ var sessionKeyPair_1, storedKeys, signFn_1, error_3;
118
118
  var _this = this;
119
119
  return __generator(this, function (_a) {
120
120
  switch (_a.label) {
121
121
  case 0:
122
- _a.trys.push([0, 7, , 8]);
122
+ _a.trys.push([0, 3, , 4]);
123
123
  sessionKeyPair_1 = null;
124
- if (!address) return [3 /*break*/, 4];
125
- storedKeys = getSessionKeysFromLocalStorage(address);
126
- if (!storedKeys) return [3 /*break*/, 4];
127
- _a.label = 1;
128
- case 1:
129
- _a.trys.push([1, 3, , 4]);
130
- return [4 /*yield*/, generateSessionKeyPair()];
131
- case 2:
132
- tempKeyPair = _a.sent();
133
- sessionKeyPair_1 = {
134
- privateKey: storedKeys.ed25519PrivateKey,
135
- publicKey: tempKeyPair.publicKey,
136
- };
137
- return [3 /*break*/, 4];
138
- case 3:
139
- error_3 = _a.sent();
140
- console.error('Error reconstructing key pair from stored keys:', error_3);
141
- sessionKeyPair_1 = null;
142
- return [3 /*break*/, 4];
143
- case 4:
144
- if (!!sessionKeyPair_1) return [3 /*break*/, 6];
124
+ if (address) {
125
+ try {
126
+ storedKeys = getSessionKeysFromLocalStorage(address);
127
+ if (storedKeys) {
128
+ sessionKeyPair_1 = {
129
+ privateKey: storedKeys.ed25519PrivateKey,
130
+ publicKey: storedKeys.ed25519PublicKey,
131
+ };
132
+ }
133
+ }
134
+ catch (error) {
135
+ console.error('Error reconstructing key pair from stored keys:', error);
136
+ sessionKeyPair_1 = null;
137
+ }
138
+ }
139
+ if (!!sessionKeyPair_1) return [3 /*break*/, 2];
145
140
  return [4 /*yield*/, generateSessionKeyPair()];
146
- case 5:
141
+ case 1:
147
142
  sessionKeyPair_1 = _a.sent();
148
- _a.label = 6;
149
- case 6:
143
+ _a.label = 2;
144
+ case 2:
150
145
  signFn_1 = function (message) { return __awaiter(_this, void 0, void 0, function () {
151
- var error_5;
146
+ var error_4;
152
147
  return __generator(this, function (_a) {
153
148
  switch (_a.label) {
154
149
  case 0:
@@ -156,26 +151,27 @@ export function useNordUserInitialization() {
156
151
  return [4 /*yield*/, signEd25519(message, sessionKeyPair_1.privateKey)];
157
152
  case 1: return [2 /*return*/, _a.sent()];
158
153
  case 2:
159
- error_5 = _a.sent();
160
- console.error('Error signing with session key:', error_5);
161
- throw error_5;
154
+ error_4 = _a.sent();
155
+ console.error('Error signing with session key:', error_4);
156
+ throw error_4;
162
157
  case 3: return [2 /*return*/];
163
158
  }
164
159
  });
165
160
  }); };
166
161
  storeSessionKeysInLocalStorage({
167
162
  privKey: sessionKeyPair_1.privateKey,
163
+ publicKey: sessionKeyPair_1.publicKey,
168
164
  walletPublicKey: address,
169
165
  chainName: (dynamicWallet === null || dynamicWallet === void 0 ? void 0 : dynamicWallet.chain) || 'ETH',
170
166
  });
171
167
  setSessionPubKey(sessionKeyPair_1.publicKey);
172
168
  setSignMessageWithSessionKey(function () { return signFn_1; });
173
169
  return [2 /*return*/, signFn_1];
174
- case 7:
175
- error_4 = _a.sent();
176
- console.error('Error creating session:', error_4);
170
+ case 3:
171
+ error_3 = _a.sent();
172
+ console.error('Error creating session:', error_3);
177
173
  return [2 /*return*/, null];
178
- case 8: return [2 /*return*/];
174
+ case 4: return [2 /*return*/];
179
175
  }
180
176
  });
181
177
  }); };
@@ -210,7 +206,7 @@ export function useNordUserInitialization() {
210
206
  return;
211
207
  }
212
208
  var createNordUser = function () { return __awaiter(_this, void 0, void 0, function () {
213
- var sessionId, sessionKeyData, sessionIdKey, storedSessionId, user, _1, error_6;
209
+ var sessionId, sessionKeyData, sessionIdKey, storedSessionId, user, _1, error_5;
214
210
  return __generator(this, function (_a) {
215
211
  switch (_a.label) {
216
212
  case 0:
@@ -261,8 +257,8 @@ export function useNordUserInitialization() {
261
257
  setNordUser(user);
262
258
  return [2 /*return*/, user];
263
259
  case 5:
264
- error_6 = _a.sent();
265
- console.error('Error creating NordUser:', error_6);
260
+ error_5 = _a.sent();
261
+ console.error('Error creating NordUser:', error_5);
266
262
  setNordUser(null);
267
263
  return [2 /*return*/, null];
268
264
  case 6: return [2 /*return*/];
@@ -1 +1 @@
1
- {"version":3,"file":"useNordUserInitialization.js","sourceRoot":"","sources":["../../../src/Provider/hooks/useNordUserInitialization.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,OAAO,CAAC;AAElC,OAAO,EAAE,QAAQ,EAAE,MAAM,gBAAgB,CAAC;AAC1C,OAAO,EAAE,sBAAsB,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAC;AACrE,OAAO,EAAE,SAAS,EAAE,WAAW,EAAE,MAAM,iBAAiB,CAAC;AACzD,OAAO,EAAE,8BAA8B,EAAE,8BAA8B,EAAE,MAAM,mBAAmB,CAAC;AACnG,OAAO,EAAE,WAAW,EAAE,eAAe,EAAE,MAAM,oBAAoB,CAAC;AAClE,OAAO,EAAE,MAAM,EAAE,MAAM,oBAAoB,CAAC;AAC5C,OAAO,EAAE,aAAa,EAAE,MAAM,UAAU,CAAC;AACzC,OAAO,EAAE,kBAAkB,EAAE,0BAA0B,EAAE,MAAM,UAAU,CAAC;AAG1E,MAAM,UAAU,yBAAyB;IAAzC,iBAkOC;IAjOS,IAAA,KAA+I,0BAA0B,EAAE,EAAzK,WAAW,iBAAA,EAAE,gBAAgB,sBAAA,EAAE,4BAA4B,kCAAA,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CAAC;wBACL,CAAC;wBAEK,IAAI,GAAG,IAAI,QAAQ,CAAC;4BACtB,IAAI,EAAE,IAAI;4BACV,OAAO,SAAA;4BACP,YAAY,EAAE,wBAAwB;4BACtC,aAAa,EAAE,yBAAyB;4BACxC,iBAAiB,EAAE,4BAA4B;4BAC/C,SAAS,WAAA;4BACT,aAAa,EAAE,aAAa;4BAC5B,SAAS,EAAE,IAAI,SAAS,CAAC,OAAO,CAAC;yBACpC,CAAC,CAAC;;;;wBAGC,qBAAM,IAAI,CAAC,eAAe,EAAE,EAAA;;wBAA5B,SAA4B,CAAC;;;;;;wBAGjC,WAAW,CAAC,IAAI,CAAC,CAAC;wBAClB,sBAAO,IAAI,EAAC;;;wBAEZ,OAAO,CAAC,KAAK,CAAC,0BAA0B,EAAE,OAAK,CAAC,CAAC;wBACjD,WAAW,CAAC,IAAI,CAAC,CAAC;wBAClB,sBAAO,IAAI,EAAC;;;;aAEnB,CAAC;QAEF,gFAAgF;QAChF,IACI,wBAAwB;YACxB,yBAAyB;YACzB,4BAA4B;YAC5B,aAAa;YACb,QAAQ,KAAK,IAAI,EACnB,CAAC;YACC,MAAM,CAAC,KAAK,CAAC,+CAA+C,CAAC,CAAC;YAC9D,cAAc,EAAE,CAAC;QACrB,CAAC;IACL,CAAC,EAAE;QACC,WAAW;QACX,IAAI;QACJ,OAAO;QACP,yBAAyB;QACzB,wBAAwB;QACxB,4BAA4B;QAC5B,aAAa;QACb,QAAQ;QACR,WAAW;KACd,CAAC,CAAC;AACP,CAAC","sourcesContent":["import { useEffect } from 'react';\nimport React from 'react';\nimport { NordUser } from '@n1xyz/nord-ts';\nimport { generateSessionKeyPair, signEd25519 } from '@n1xyz/nts-sdk';\nimport { PublicKey, Transaction } from '@solana/web3.js';\nimport { getSessionKeysFromLocalStorage, storeSessionKeysInLocalStorage } from '../../Logic/utils';\nimport { WalletError, WalletErrorCode } from '../../errors/types';\nimport { logger } from '../../utils/logger';\nimport { N1SessionMode } from '../types';\nimport { useN1WalletContext, useN1WalletInternalContext } from '../hooks';\n\n\nexport function useNordUserInitialization() {\n const { setNordUser, setSessionPubKey, setSignMessageWithSessionKey, setSignMessageWithWalletKey, setSignTransactionWithWalletKey, dynamicWallet } = useN1WalletInternalContext();\n\n const { address, nordUser, sessionMode, nord, signMessageWithSessionKey, signMessageWithWalletKey, signTransactionWithWalletKey, sessionPubKey } = useN1WalletContext();\n // First useEffect: Initialize signing functions\n useEffect(() => {\n if (sessionMode !== N1SessionMode.Nord || address === null || address === '') {\n return;\n }\n\n const createWalletSignFunction = () => {\n if (!dynamicWallet) {\n return null;\n }\n\n const signWithWallet = async (msg: Uint8Array): Promise<Uint8Array> => {\n try {\n const hexMsg = Buffer.from(msg).toString('hex');\n const signature = await dynamicWallet.signMessage(hexMsg);\n const binaryString = atob(signature);\n const signatureUint8Array = new Uint8Array(binaryString.length);\n for (let i = 0; i < binaryString.length; i++) {\n signatureUint8Array[i] = binaryString.charCodeAt(i);\n }\n return signatureUint8Array;\n } catch (error) {\n console.error('Error signing with wallet:', error);\n throw new WalletError(\n WalletErrorCode.USER_REJECTED,\n 'Failed to sign message with wallet',\n { originalError: error }\n );\n }\n };\n\n setSignMessageWithWalletKey(() => signWithWallet);\n return signWithWallet;\n };\n\n const createTransactionSignFunction = () => {\n if (!dynamicWallet) {\n return null;\n }\n\n const signTransactionWithWallet = async (\n transaction: any\n ): Promise<any> => {\n try {\n if (dynamicWallet.chain === 'SOL') {\n const signedTransaction = await (\n await dynamicWallet.getSigner()\n ).signTransaction(transaction);\n logger.debug('Solana transaction signature received');\n\n const serializedTx = signedTransaction.serialize();\n return Transaction.from(serializedTx);\n }\n\n throw new WalletError(\n WalletErrorCode.USER_REJECTED,\n 'Unsupported chain',\n { originalError: new Error('Unsupported chain') }\n );\n } catch (error) {\n console.error('Error signing transaction with wallet:', error);\n throw new WalletError(\n WalletErrorCode.USER_REJECTED,\n 'Failed to sign transaction with wallet',\n { originalError: error }\n );\n }\n };\n\n setSignTransactionWithWalletKey(() => signTransactionWithWallet);\n return signTransactionWithWallet;\n };\n\n const createSession = async () => {\n try {\n let sessionKeyPair = null;\n if (address) {\n const storedKeys = getSessionKeysFromLocalStorage(address);\n if (storedKeys) {\n try {\n const tempKeyPair = await generateSessionKeyPair();\n sessionKeyPair = {\n privateKey: storedKeys.ed25519PrivateKey,\n publicKey: tempKeyPair.publicKey,\n };\n } catch (error) {\n console.error(\n 'Error reconstructing key pair from stored keys:',\n error\n );\n sessionKeyPair = null;\n }\n }\n }\n\n if (!sessionKeyPair) {\n sessionKeyPair = await generateSessionKeyPair();\n }\n\n const signFn = async (message: any): Promise<any> => {\n try {\n return await signEd25519(message, sessionKeyPair.privateKey);\n } catch (error) {\n console.error('Error signing with session key:', error);\n throw error;\n }\n };\n\n\n storeSessionKeysInLocalStorage({\n privKey: sessionKeyPair.privateKey,\n walletPublicKey: address,\n chainName: dynamicWallet?.chain || 'ETH',\n });\n\n setSessionPubKey(sessionKeyPair.publicKey);\n setSignMessageWithSessionKey(() => signFn);\n return signFn;\n } catch (error) {\n console.error('Error creating session:', error);\n return null;\n }\n };\n\n // Initialize signing functions if needed\n const initSigningFunctions = async () => {\n if (!signMessageWithWalletKey && dynamicWallet) {\n createWalletSignFunction();\n }\n\n if (!signTransactionWithWalletKey && dynamicWallet) {\n createTransactionSignFunction();\n }\n\n if (!signMessageWithSessionKey) {\n await createSession();\n }\n };\n\n initSigningFunctions();\n }, [\n dynamicWallet,\n address,\n ]);\n\n // Second useEffect: Initialize NordUser\n useEffect(() => {\n if (sessionMode !== N1SessionMode.Nord) {\n return;\n }\n\n const createNordUser = async () => {\n try {\n if (!nord || !address || !sessionPubKey || !signMessageWithWalletKey || !signMessageWithSessionKey || !signTransactionWithWalletKey) {\n return null;\n }\n\n let sessionId = undefined;\n if (address) {\n try {\n const sessionKeyData = getSessionKeysFromLocalStorage(address);\n if (sessionKeyData) {\n const sessionIdKey = `n1_sessionId_${address}`;\n const storedSessionId = localStorage.getItem(sessionIdKey);\n if (storedSessionId !== null) {\n sessionId = BigInt(storedSessionId);\n logger.debug('Found existing sessionId in localStorage', {\n sessionId: storedSessionId,\n });\n }\n }\n } catch (error) {\n console.error('Error retrieving sessionId from localStorage:', error);\n }\n }\n\n const user = new NordUser({\n nord: nord,\n address,\n walletSignFn: signMessageWithWalletKey,\n sessionSignFn: signMessageWithSessionKey,\n transactionSignFn: signTransactionWithWalletKey,\n sessionId,\n sessionPubKey: sessionPubKey,\n publicKey: new PublicKey(address),\n });\n\n try {\n await user.updateAccountId();\n } catch (_) { }\n\n setNordUser(user);\n return user;\n } catch (error) {\n console.error('Error creating NordUser:', error);\n setNordUser(null);\n return null;\n }\n };\n\n // Only create NordUser when all dependencies are available and nordUser is null\n if (\n signMessageWithWalletKey &&\n signMessageWithSessionKey &&\n signTransactionWithWalletKey &&\n sessionPubKey &&\n nordUser === null\n ) {\n logger.debug('Dependencies available, initializing NordUser');\n createNordUser();\n }\n }, [\n sessionMode,\n nord,\n address,\n signMessageWithSessionKey,\n signMessageWithWalletKey,\n signTransactionWithWalletKey,\n sessionPubKey,\n nordUser,\n setNordUser\n ]);\n} "]}
1
+ {"version":3,"file":"useNordUserInitialization.js","sourceRoot":"","sources":["../../../src/Provider/hooks/useNordUserInitialization.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,OAAO,CAAC;AAElC,OAAO,EAAE,QAAQ,EAAE,MAAM,gBAAgB,CAAC;AAC1C,OAAO,EAAE,sBAAsB,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAC;AACrE,OAAO,EAAE,SAAS,EAAE,WAAW,EAAE,MAAM,iBAAiB,CAAC;AACzD,OAAO,EAAE,8BAA8B,EAAE,8BAA8B,EAAE,MAAM,mBAAmB,CAAC;AACnG,OAAO,EAAE,WAAW,EAAE,eAAe,EAAE,MAAM,oBAAoB,CAAC;AAClE,OAAO,EAAE,MAAM,EAAE,MAAM,o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aAAa;QACb,QAAQ;QACR,WAAW;KACd,CAAC,CAAC;AACP,CAAC","sourcesContent":["import { useEffect } from 'react';\nimport React from 'react';\nimport { NordUser } from '@n1xyz/nord-ts';\nimport { generateSessionKeyPair, signEd25519 } from '@n1xyz/nts-sdk';\nimport { PublicKey, Transaction } from '@solana/web3.js';\nimport { getSessionKeysFromLocalStorage, storeSessionKeysInLocalStorage } from '../../Logic/utils';\nimport { WalletError, WalletErrorCode } from '../../errors/types';\nimport { logger } from '../../utils/logger';\nimport { N1SessionMode } from '../types';\nimport { useN1WalletContext, useN1WalletInternalContext } from '../hooks';\n\n\nexport function useNordUserInitialization() {\n const { setNordUser, setSessionPubKey, setSignMessageWithSessionKey, setSignMessageWithWalletKey, setSignTransactionWithWalletKey, dynamicWallet } = useN1WalletInternalContext();\n\n const { address, nordUser, sessionMode, nord, signMessageWithSessionKey, signMessageWithWalletKey, signTransactionWithWalletKey, sessionPubKey } = useN1WalletContext();\n // First useEffect: Initialize signing functions\n useEffect(() => {\n if (sessionMode !== N1SessionMode.Nord || address === null || address === '') {\n return;\n }\n\n const createWalletSignFunction = () => {\n if (!dynamicWallet) {\n return null;\n }\n\n const signWithWallet = async (msg: Uint8Array): Promise<Uint8Array> => {\n try {\n const hexMsg = Buffer.from(msg).toString('hex');\n const signature = await dynamicWallet.signMessage(hexMsg);\n const binaryString = atob(signature);\n const signatureUint8Array = new Uint8Array(binaryString.length);\n for (let i = 0; i < binaryString.length; i++) {\n signatureUint8Array[i] = binaryString.charCodeAt(i);\n }\n return signatureUint8Array;\n } catch (error) {\n console.error('Error signing with wallet:', error);\n throw new WalletError(\n WalletErrorCode.USER_REJECTED,\n 'Failed to sign message with wallet',\n { originalError: error }\n );\n }\n };\n\n setSignMessageWithWalletKey(() => signWithWallet);\n return signWithWallet;\n };\n\n const createTransactionSignFunction = () => {\n if (!dynamicWallet) {\n return null;\n }\n\n const signTransactionWithWallet = async (\n transaction: any\n ): Promise<any> => {\n try {\n if (dynamicWallet.chain === 'SOL') {\n const signedTransaction = await (\n await dynamicWallet.getSigner()\n ).signTransaction(transaction);\n logger.debug('Solana transaction signature received');\n\n const serializedTx = signedTransaction.serialize();\n return Transaction.from(serializedTx);\n }\n\n throw new WalletError(\n WalletErrorCode.USER_REJECTED,\n 'Unsupported chain',\n { originalError: new Error('Unsupported chain') }\n );\n } catch (error) {\n console.error('Error signing transaction with wallet:', error);\n throw new WalletError(\n WalletErrorCode.USER_REJECTED,\n 'Failed to sign transaction with wallet',\n { originalError: error }\n );\n }\n };\n\n setSignTransactionWithWalletKey(() => signTransactionWithWallet);\n return signTransactionWithWallet;\n };\n\n const createSession = async () => {\n try {\n let sessionKeyPair = null;\n if (address) {\n try {\n const storedKeys = getSessionKeysFromLocalStorage(address);\n if (storedKeys) {\n sessionKeyPair = {\n privateKey: storedKeys.ed25519PrivateKey,\n publicKey: storedKeys.ed25519PublicKey,\n };\n }\n } catch (error) {\n console.error(\n 'Error reconstructing key pair from stored keys:',\n error\n );\n sessionKeyPair = null;\n }\n }\n\n if (!sessionKeyPair) {\n sessionKeyPair = await generateSessionKeyPair();\n }\n\n const signFn = async (message: any): Promise<any> => {\n try {\n return await signEd25519(message, sessionKeyPair.privateKey);\n } catch (error) {\n console.error('Error signing with session key:', error);\n throw error;\n }\n };\n\n\n storeSessionKeysInLocalStorage({\n privKey: sessionKeyPair.privateKey,\n publicKey: sessionKeyPair.publicKey!,\n walletPublicKey: address,\n chainName: dynamicWallet?.chain || 'ETH',\n });\n\n setSessionPubKey(sessionKeyPair.publicKey!);\n setSignMessageWithSessionKey(() => signFn);\n return signFn;\n } catch (error) {\n console.error('Error creating session:', error);\n return null;\n }\n };\n\n // Initialize signing functions if needed\n const initSigningFunctions = async () => {\n if (!signMessageWithWalletKey && dynamicWallet) {\n createWalletSignFunction();\n }\n\n if (!signTransactionWithWalletKey && dynamicWallet) {\n createTransactionSignFunction();\n }\n\n if (!signMessageWithSessionKey) {\n await createSession();\n }\n };\n\n initSigningFunctions();\n }, [\n dynamicWallet,\n address,\n ]);\n\n // Second useEffect: Initialize NordUser\n useEffect(() => {\n if (sessionMode !== N1SessionMode.Nord) {\n return;\n }\n\n const createNordUser = async () => {\n try {\n if (!nord || !address || !sessionPubKey || !signMessageWithWalletKey || !signMessageWithSessionKey || !signTransactionWithWalletKey) {\n return null;\n }\n\n let sessionId = undefined;\n if (address) {\n try {\n const sessionKeyData = getSessionKeysFromLocalStorage(address);\n if (sessionKeyData) {\n const sessionIdKey = `n1_sessionId_${address}`;\n const storedSessionId = localStorage.getItem(sessionIdKey);\n if (storedSessionId !== null) {\n sessionId = BigInt(storedSessionId);\n logger.debug('Found existing sessionId in localStorage', {\n sessionId: storedSessionId,\n });\n }\n }\n } catch (error) {\n console.error('Error retrieving sessionId from localStorage:', error);\n }\n }\n\n const user = new NordUser({\n nord: nord,\n address,\n walletSignFn: signMessageWithWalletKey,\n sessionSignFn: signMessageWithSessionKey,\n transactionSignFn: signTransactionWithWalletKey,\n sessionId,\n sessionPubKey: sessionPubKey,\n publicKey: new PublicKey(address),\n });\n\n try {\n await user.updateAccountId();\n } catch (_) { }\n\n setNordUser(user);\n return user;\n } catch (error) {\n console.error('Error creating NordUser:', error);\n setNordUser(null);\n return null;\n }\n };\n\n // Only create NordUser when all dependencies are available and nordUser is null\n if (\n signMessageWithWalletKey &&\n signMessageWithSessionKey &&\n signTransactionWithWalletKey &&\n sessionPubKey &&\n nordUser === null\n ) {\n logger.debug('Dependencies available, initializing NordUser');\n createNordUser();\n }\n }, [\n sessionMode,\n nord,\n address,\n signMessageWithSessionKey,\n signMessageWithWalletKey,\n signTransactionWithWalletKey,\n sessionPubKey,\n nordUser,\n setNordUser\n ]);\n} "]}