@n1xyz/wallet-widget 0.0.27 → 0.0.28

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.
@@ -51,7 +51,7 @@ export function CreateSessionView() {
51
51
  var _b = useState(false), isPressed = _b[0], setIsPressed = _b[1];
52
52
  var _c = useState(null), NTSComponents = _c[0], setNTSComponents = _c[1];
53
53
  var _d = useState(null), keyPair = _d[0], setKeyPair = _d[1];
54
- var _e = useN1WalletInternalContext(), setViewMode = _e.setViewMode, setUsername = _e.setUsername, setStartClosingLogin = _e.setStartClosingLogin, setIsConnected = _e.setIsConnected, dynamicWallet = _e.dynamicWallet, handleError = _e.handleError, setSessionPubKey = _e.setSessionPubKey, setSignMessageWithSessionKey = _e.setSignMessageWithSessionKey, dynamicHandleLogOut = _e.dynamicHandleLogOut, setDynamicWallet = _e.setDynamicWallet, setAddress = _e.setAddress, setSignMessageWithWalletKey = _e.setSignMessageWithWalletKey;
54
+ var _e = useN1WalletInternalContext(), setViewMode = _e.setViewMode, setUsername = _e.setUsername, setStartClosingLogin = _e.setStartClosingLogin, setIsConnected = _e.setIsConnected, dynamicWallet = _e.dynamicWallet, handleError = _e.handleError, setSessionPubKey = _e.setSessionPubKey, setSignMessageWithSessionKey = _e.setSignMessageWithSessionKey, dynamicHandleLogOut = _e.dynamicHandleLogOut, setDynamicWallet = _e.setDynamicWallet, setAddress = _e.setAddress;
55
55
  var _f = useN1WalletContext(), ntsInterface = _f.ntsInterface, walletPubKey = _f.walletPubKey, address = _f.address;
56
56
  // Initialize NTS SDK and generate key pair
57
57
  useEffect(function () {
@@ -139,7 +139,6 @@ export function CreateSessionView() {
139
139
  },
140
140
  ],
141
141
  };
142
- setSignMessageWithWalletKey(function () { return signWithWallet; });
143
142
  tx = new NTSComponents.Transaction(transactionData, walletPubKey);
144
143
  return [4 /*yield*/, tx.signWithWalletFunction(signWithWallet)];
145
144
  case 2:
@@ -1 +1 @@
1
- {"version":3,"file":"CreateS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wCACf,CAAC,CAAC,UAAU;6BACnB,YAED,cAAK,SAAS,EAAC,+BAA+B,YAC5C,cAAK,SAAS,EAAC,iCAAiC,YAC9C,eACE,SAAS,EAAE,iGAC0D,cAAc,gJAEpF,6BAGM,GACH,GACF,GACC,EAET,KAAC,UAAU,IACT,OAAO,EAAE;gCACP,MAAM,CAAC,KAAK,CAAC,oBAAoB,CAAC,CAAC;gCACnC,gBAAgB,CAAC,IAAI,CAAC,CAAC;gCACvB,UAAU,CAAC,EAAE,CAAC,CAAC;gCACf,mBAAmB,EAAE,CAAC;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 ${!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,EAChB,sBAAsB,EACtB,OAAO,EACP,8BAA8B,GAC/B,MAAM,sBAAsB,CAAC;AAC9B,OAAO,EACL,kBAAkB,EAClB,0BAA0B,GAC3B,MAAM,yBAAyB,CAAC;AACjC,OAAO,EAAE,eAAe,EAAE,MAAM,yBAAyB,CAAC;AAC1D,OAAO,EAAE,MAAM,EAAE,MAAM,uBAAuB,CAAC;AAC/C,OAAO,EAAE,UAAU,EAAE,MAAM,0BAA0B,CAAC;AACtD,OAAO,EAAE,WAAW,EAAE,MAAM,2BAA2B,CAAC;AACxD,OAAO,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAC;AAE7C,MAAM,UAAU,iBAAiB;IAAjC,iBAkQC;IAjQO,IAAA,KAA4B,QAAQ,CAAC,KAAK,CAAC,EAA1C,SAAS,QAAA,EAAE,YAAY,QAAmB,CAAC;IAC5C,IAAA,KAA4B,QAAQ,CAAC,KAAK,CAAC,EAA1C,SAAS,QAAA,EAAE,YAAY,QAAmB,CAAC;IAE5C,IAAA,KAAoC,QAAQ,CAAM,IAAI,CAAC,EAAtD,aAAa,QAAA,EAAE,gBAAgB,QAAuB,CAAC;IACxD,IAAA,KAAwB,QAAQ,CAG5B,IAAI,CAAC,EAHR,OAAO,QAAA,EAAE,UAAU,QAGX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,OAAO,CAAC;wCACzC,CAAC,CAAC,aAAa;wCACf,CAAC,CAAC,UAAU;6BACnB,YAED,cAAK,SAAS,EAAC,+BAA+B,YAC5C,cAAK,SAAS,EAAC,iCAAiC,YAC9C,eACE,SAAS,EAAE,iGAC0D,cAAc,gJAEpF,6BAGM,GACH,GACF,GACC,EAET,KAAC,UAAU,IACT,OAAO,EAAE;gCACP,MAAM,CAAC,KAAK,CAAC,oBAAoB,CAAC,CAAC;gCACnC,gBAAgB,CAAC,IAAI,CAAC,CAAC;gCACvB,UAAU,CAAC,EAAE,CAAC,CAAC;gCACf,mBAAmB,EAAE,CAAC;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 } = 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 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 ${!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"]}
@@ -51,7 +51,7 @@ export var DepositProvider = function (_a) {
51
51
  // Get flow state context
52
52
  var _b = useFlowStateContext(), state = _b.state, context = _b.context, transition = _b.transition, updateContext = _b.updateContext;
53
53
  // Get wallet context
54
- var _c = useN1WalletContext(), address = _c.address, nord = _c.nord, signMessageWithWalletKey = _c.signMessageWithWalletKey, signMessageWithSessionKey = _c.signMessageWithSessionKey, nordUser = _c.nordUser;
54
+ var _c = useN1WalletContext(), address = _c.address, nord = _c.nord, signMessageWithSessionKey = _c.signMessageWithSessionKey, nordUser = _c.nordUser;
55
55
  var sessionMode = useN1WalletInternalContext().sessionMode;
56
56
  // chain
57
57
  var _d = useState(context.selectedChain), selectedChain = _d[0], setSelectedChain = _d[1];
@@ -231,7 +231,6 @@ export var DepositProvider = function (_a) {
231
231
  transition,
232
232
  handleError,
233
233
  nord,
234
- signMessageWithWalletKey,
235
234
  signMessageWithSessionKey,
236
235
  nordUser,
237
236
  ]);
@@ -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,IA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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}; "]}
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,KAKF,kBAAkB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C,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 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 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}; \n"]}
@@ -45,50 +45,19 @@ import { N1SessionMode } from '../types';
45
45
  import { useN1WalletContext, useN1WalletInternalContext } from '../hooks';
46
46
  export function useNordUserInitialization() {
47
47
  var _this = this;
48
- var _a = useN1WalletInternalContext(), setNordUser = _a.setNordUser, setSessionPubKey = _a.setSessionPubKey, setSignMessageWithSessionKey = _a.setSignMessageWithSessionKey, setSignMessageWithWalletKey = _a.setSignMessageWithWalletKey, setSignTransactionWithWalletKey = _a.setSignTransactionWithWalletKey, dynamicWallet = _a.dynamicWallet;
49
- var _b = useN1WalletContext(), address = _b.address, nordUser = _b.nordUser, sessionMode = _b.sessionMode, nord = _b.nord, signMessageWithSessionKey = _b.signMessageWithSessionKey, signMessageWithWalletKey = _b.signMessageWithWalletKey, signTransactionWithWalletKey = _b.signTransactionWithWalletKey, sessionPubKey = _b.sessionPubKey;
48
+ var _a = useN1WalletInternalContext(), setNordUser = _a.setNordUser, setSessionPubKey = _a.setSessionPubKey, setSignMessageWithSessionKey = _a.setSignMessageWithSessionKey, setSignTransactionWithWalletKey = _a.setSignTransactionWithWalletKey, dynamicWallet = _a.dynamicWallet;
49
+ var _b = useN1WalletContext(), address = _b.address, nordUser = _b.nordUser, sessionMode = _b.sessionMode, nord = _b.nord, signMessageWithSessionKey = _b.signMessageWithSessionKey, signTransactionWithWalletKey = _b.signTransactionWithWalletKey, sessionPubKey = _b.sessionPubKey;
50
50
  // First useEffect: Initialize signing functions
51
51
  useEffect(function () {
52
52
  if (sessionMode !== N1SessionMode.Nord || address === null || address === '') {
53
53
  return;
54
54
  }
55
- var createWalletSignFunction = function () {
56
- if (!dynamicWallet) {
57
- return null;
58
- }
59
- var signWithWallet = function (msg) { return __awaiter(_this, void 0, void 0, function () {
60
- var hexMsg, signature, binaryString, signatureUint8Array, i, error_1;
61
- return __generator(this, function (_a) {
62
- switch (_a.label) {
63
- case 0:
64
- _a.trys.push([0, 2, , 3]);
65
- hexMsg = Buffer.from(msg).toString('hex');
66
- return [4 /*yield*/, dynamicWallet.signMessage(hexMsg)];
67
- case 1:
68
- signature = _a.sent();
69
- binaryString = atob(signature);
70
- signatureUint8Array = new Uint8Array(binaryString.length);
71
- for (i = 0; i < binaryString.length; i++) {
72
- signatureUint8Array[i] = binaryString.charCodeAt(i);
73
- }
74
- return [2 /*return*/, signatureUint8Array];
75
- case 2:
76
- error_1 = _a.sent();
77
- console.error('Error signing with wallet:', error_1);
78
- throw new WalletError(WalletErrorCode.USER_REJECTED, 'Failed to sign message with wallet', { originalError: error_1 });
79
- case 3: return [2 /*return*/];
80
- }
81
- });
82
- }); };
83
- setSignMessageWithWalletKey(function () { return signWithWallet; });
84
- return signWithWallet;
85
- };
86
55
  var createTransactionSignFunction = function () {
87
56
  if (!dynamicWallet) {
88
57
  return null;
89
58
  }
90
59
  var signTransactionWithWallet = function (transaction) { return __awaiter(_this, void 0, void 0, function () {
91
- var signedTransaction, error_2;
60
+ var signedTransaction, error_1;
92
61
  return __generator(this, function (_a) {
93
62
  switch (_a.label) {
94
63
  case 0:
@@ -106,9 +75,9 @@ export function useNordUserInitialization() {
106
75
  return [2 /*return*/, signedTransaction];
107
76
  case 3: throw new WalletError(WalletErrorCode.USER_REJECTED, 'Unsupported chain', { originalError: new Error('Unsupported chain') });
108
77
  case 4:
109
- error_2 = _a.sent();
110
- console.error('Error signing transaction with wallet:', error_2);
111
- throw new WalletError(WalletErrorCode.USER_REJECTED, 'Failed to sign transaction with wallet', { originalError: error_2 });
78
+ error_1 = _a.sent();
79
+ console.error('Error signing transaction with wallet:', error_1);
80
+ throw new WalletError(WalletErrorCode.USER_REJECTED, 'Failed to sign transaction with wallet', { originalError: error_1 });
112
81
  case 5: return [2 /*return*/];
113
82
  }
114
83
  });
@@ -117,7 +86,7 @@ export function useNordUserInitialization() {
117
86
  return signTransactionWithWallet;
118
87
  };
119
88
  var createSession = function () { return __awaiter(_this, void 0, void 0, function () {
120
- var sessionKeyPair_1, storedKeys, signFn_1, error_3;
89
+ var sessionKeyPair_1, storedKeys, signFn_1, error_2;
121
90
  var _this = this;
122
91
  return __generator(this, function (_a) {
123
92
  switch (_a.label) {
@@ -146,7 +115,7 @@ export function useNordUserInitialization() {
146
115
  _a.label = 2;
147
116
  case 2:
148
117
  signFn_1 = function (message) { return __awaiter(_this, void 0, void 0, function () {
149
- var error_4;
118
+ var error_3;
150
119
  return __generator(this, function (_a) {
151
120
  switch (_a.label) {
152
121
  case 0:
@@ -154,9 +123,9 @@ export function useNordUserInitialization() {
154
123
  return [4 /*yield*/, signEd25519(message, sessionKeyPair_1.privateKey)];
155
124
  case 1: return [2 /*return*/, _a.sent()];
156
125
  case 2:
157
- error_4 = _a.sent();
158
- console.error('Error signing with session key:', error_4);
159
- throw error_4;
126
+ error_3 = _a.sent();
127
+ console.error('Error signing with session key:', error_3);
128
+ throw error_3;
160
129
  case 3: return [2 /*return*/];
161
130
  }
162
131
  });
@@ -171,8 +140,8 @@ export function useNordUserInitialization() {
171
140
  setSignMessageWithSessionKey(function () { return signFn_1; });
172
141
  return [2 /*return*/, signFn_1];
173
142
  case 3:
174
- error_3 = _a.sent();
175
- console.error('Error creating session:', error_3);
143
+ error_2 = _a.sent();
144
+ console.error('Error creating session:', error_2);
176
145
  return [2 /*return*/, null];
177
146
  case 4: return [2 /*return*/];
178
147
  }
@@ -183,9 +152,6 @@ export function useNordUserInitialization() {
183
152
  return __generator(this, function (_a) {
184
153
  switch (_a.label) {
185
154
  case 0:
186
- if (!signMessageWithWalletKey && dynamicWallet) {
187
- createWalletSignFunction();
188
- }
189
155
  if (!signTransactionWithWalletKey && dynamicWallet) {
190
156
  createTransactionSignFunction();
191
157
  }
@@ -209,12 +175,12 @@ export function useNordUserInitialization() {
209
175
  return;
210
176
  }
211
177
  var createNordUser = function () { return __awaiter(_this, void 0, void 0, function () {
212
- var sessionId, sessionKeyData, sessionIdKey, storedSessionId, user, _1, error_5;
178
+ var sessionId, sessionKeyData, sessionIdKey, storedSessionId, user, _1, error_4;
213
179
  return __generator(this, function (_a) {
214
180
  switch (_a.label) {
215
181
  case 0:
216
182
  _a.trys.push([0, 5, , 6]);
217
- if (!nord || !address || !sessionPubKey || !signMessageWithWalletKey || !signMessageWithSessionKey || !signTransactionWithWalletKey) {
183
+ if (!nord || !address || !sessionPubKey || !signMessageWithSessionKey || !signTransactionWithWalletKey) {
218
184
  return [2 /*return*/, null];
219
185
  }
220
186
  sessionId = undefined;
@@ -238,8 +204,6 @@ export function useNordUserInitialization() {
238
204
  }
239
205
  user = new NordUser({
240
206
  nord: nord,
241
- address: address,
242
- walletSignFn: signMessageWithWalletKey,
243
207
  sessionSignFn: signMessageWithSessionKey,
244
208
  transactionSignFn: signTransactionWithWalletKey,
245
209
  sessionId: sessionId,
@@ -260,8 +224,8 @@ export function useNordUserInitialization() {
260
224
  setNordUser(user);
261
225
  return [2 /*return*/, user];
262
226
  case 5:
263
- error_5 = _a.sent();
264
- console.error('Error creating NordUser:', error_5);
227
+ error_4 = _a.sent();
228
+ console.error('Error creating NordUser:', error_4);
265
229
  setNordUser(null);
266
230
  return [2 /*return*/, null];
267
231
  case 6: return [2 /*return*/];
@@ -269,8 +233,7 @@ export function useNordUserInitialization() {
269
233
  });
270
234
  }); };
271
235
  // Only create NordUser when all dependencies are available and nordUser is null
272
- if (signMessageWithWalletKey &&
273
- signMessageWithSessionKey &&
236
+ if (signMessageWithSessionKey &&
274
237
  signTransactionWithWalletKey &&
275
238
  sessionPubKey &&
276
239
  nordUser === null) {
@@ -282,7 +245,6 @@ export function useNordUserInitialization() {
282
245
  nord,
283
246
  address,
284
247
  signMessageWithSessionKey,
285
- signMessageWithWalletKey,
286
248
  signTransactionWithWalletKey,
287
249
  sessionPubKey,
288
250
  nordUser,
@@ -1 +1 @@
1
- {"version":3,"file":"useNordUserInitialization.js","sourceRoot":"","sources":["../../../src/Provider/hooks/useNordUserInitialization.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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,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 console.log('signedTransaction', signedTransaction.signatures);\n console.log('signedTransaction - 2', signedTransaction);\n return signedTransaction;\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} "]}
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,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,iBAgMC;IA/LS,IAAA,KAAkH,0BAA0B,EAAE,EAA5I,WAAW,iBAAA,EAAE,gBAAgB,sBAAA,EAAE,4BAA4B,kCAAA,EAAE,+BAA+B,qCAAA,EAAE,aAAa,mBAAiC,CAAC;IAE/I,IAAA,KAAmH,kBAAk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,CAAC,0CAA0C,EAAE;4CACrD,SAAS,EAAE,eAAe;yCAC7B,CAAC,CAAC;oCACP,CAAC;gCACL,CAAC;4BACL,CAAC;4BAAC,OAAO,KAAK,EAAE,CAAC;gCACb,OAAO,CAAC,KAAK,CAAC,+CAA+C,EAAE,KAAK,CAAC,CAAC;4BAC1E,CAAC;wBACL,CAAC;wBAEK,IAAI,GAAG,IAAI,QAAQ,CAAC;4BACtB,IAAI,EAAE,IAAI;4BACV,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,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,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, setSignTransactionWithWalletKey, dynamicWallet } = useN1WalletInternalContext();\n\n const { address, nordUser, sessionMode, nord, signMessageWithSessionKey, 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 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 console.log('signedTransaction', signedTransaction.signatures);\n console.log('signedTransaction - 2', signedTransaction);\n return signedTransaction;\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 (!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 || !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 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 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 signTransactionWithWalletKey,\n sessionPubKey,\n nordUser,\n setNordUser\n ]);\n} \n"]}
@@ -101,7 +101,6 @@ export interface N1WalletState {
101
101
  setShowLogin: (show: boolean) => void;
102
102
  showLogin: boolean;
103
103
  signMessageWithSessionKey: ((message: any) => Promise<any>) | null;
104
- signMessageWithWalletKey: ((message: any) => Promise<any>) | null;
105
104
  signTransactionWithWalletKey: ((transaction: any) => Promise<any>) | null;
106
105
  userChain: string | null;
107
106
  username: string;
@@ -131,7 +130,6 @@ export interface N1InternalWalletState {
131
130
  setSessionPubKey: (key: Uint8Array) => void;
132
131
  setShowSidebar: (show: boolean) => void;
133
132
  setSignMessageWithSessionKey: React.Dispatch<React.SetStateAction<((message: any) => Promise<any>) | null>>;
134
- setSignMessageWithWalletKey: React.Dispatch<React.SetStateAction<((message: any) => Promise<any>) | null>>;
135
133
  setSignTransactionWithWalletKey: React.Dispatch<React.SetStateAction<((transaction: any) => Promise<any>) | null>>;
136
134
  setStartClosingLogin: (closing: boolean) => void;
137
135
  setUsername: (username: string) => void;
@@ -1 +1 @@
1
- {"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/Provider/types.ts"],"names":[],"mappings":"AAGA,MAAM,CAAN,IAAY,eAOX;AAPD,WAAY,eAAe;IACzB,2DAAO,CAAA;IACP,uEAAa,CAAA;IACb,2DAAO,CAAA;IACP,qEAAY,CAAA;IACZ,2DAAO,CAAA;IACP,mEAAW,CAAA;AACb,CAAC,EAPW,eAAe,KAAf,eAAe,QAO1B;AAED,MAAM,CAAN,IAAY,aAGX;AAHD,WAAY,aAAa;IACvB,iDAAI,CAAA;IACJ,+CAAG,CAAA;AACL,CAAC,EAHW,aAAa,KAAb,aAAa,QAGxB","sourcesContent":["import type { WalletError } from '../errors/types';\nimport { Nord } from '@n1xyz/nord-ts';\n\nexport enum N1ModalViewMode {\n Connect,\n CreateSession,\n Signing,\n CreatingUser,\n Success,\n NoWhitelist,\n}\n\nexport enum N1SessionMode {\n Nord,\n NTS,\n}\n\nexport interface CssColorOverride {\n color: string; // Color to find in CSS (e.g. '#3b82f6')\n replacement: string; // Replacement color (e.g. '#afafaf')\n}\n\nexport interface N1WalletProviderProps {\n children: React.ReactNode;\n providedSessionMode: N1SessionMode;\n appId: string;\n darkMode?: boolean;\n onError?: (error: WalletError) => void;\n faucetUrl?: string;\n nord?: Nord;\n /**\n * Optional array of color overrides: [{color: '#original', replacement: '#new'}]\n */\n colorOverrides?: CssColorOverride[];\n /**\n * If true, skip the final success screen and immediately call onDone\n */\n skipFinalScreen?: boolean;\n}\n\nexport interface Balance {\n mint: string;\n balance: bigint;\n appId: string;\n appType: string;\n}\n\nexport interface N1NordFunctions {\n // Market information functions\n getMarkets: () => Promise<any[]>;\n getOrderbook: (symbol: string) => Promise<any>;\n getTrades: (params: any) => Promise<any>;\n getMarketsStats: () => Promise<any>;\n\n // Trading functions\n placeOrder: (params: {\n sessionId: bigint | string;\n marketId: number;\n side: 'BUY' | 'SELL';\n fillMode: 'GTC' | 'IOC' | 'FOK' | 'POST_ONLY';\n isReduceOnly: boolean;\n size?: number | string;\n price?: number | string;\n quoteSize?: number | string;\n clientOrderId?: bigint | string;\n }) => Promise<bigint | undefined>;\n\n cancelOrder: (params: {\n sessionId: bigint | string;\n orderId: bigint | string;\n }) => Promise<bigint>;\n\n // Account management\n createSession: (params: {\n userPubkey: Uint8Array;\n sessionPubkey: Uint8Array;\n expiryTimestamp?: bigint;\n }) => Promise<bigint>;\n\n revokeSession: (params: { sessionId: bigint | string }) => Promise<void>;\n\n withdraw: (params: {\n sessionId: bigint | string;\n tokenId: number;\n amount: number;\n }) => Promise<void>;\n\n transfer: (params: {\n sessionId: bigint | string;\n fromAccountId: number;\n toAccountId?: number;\n tokenId: number;\n tokenDecimals: number;\n amount: number | string;\n }) => Promise<number | undefined>;\n\n // Blockchain information\n getTimestamp: () => Promise<bigint>;\n getActionNonce: () => Promise<number>;\n\n // Block and action queries\n queryBlock: (query: any) => Promise<any>;\n queryLastNBlocks: () => Promise<any>;\n queryRecentBlocks: (last_n: number) => Promise<any>;\n queryAction: (query: any) => Promise<any>;\n queryRecentActions: (last_n: number) => Promise<any>;\n getActions: (fromActionId: number, toActionId: number) => Promise<any>;\n}\n\nexport interface N1WalletState {\n address: string;\n appId: string | null;\n balances: Balance[];\n chain: string;\n isConnected: boolean;\n ntsInterface: any;\n sessionMode: N1SessionMode | null;\n sessionPubKey: Uint8Array | null;\n setShowLogin: (show: boolean) => void;\n showLogin: boolean;\n signMessageWithSessionKey: ((message: any) => Promise<any>) | null;\n signMessageWithWalletKey: ((message: any) => Promise<any>) | null;\n signTransactionWithWalletKey: ((transaction: any) => Promise<any>) | null;\n userChain: string | null;\n username: string;\n viewMode: N1ModalViewMode;\n walletPubKey: Uint8Array | null;\n throwTestError: () => Promise<void>;\n nord?: Nord;\n faucetUrl?: string;\n nordUser?: any;\n}\n\nexport interface N1InternalWalletState {\n dynamicHandleLogOut: any;\n dynamicWallet: any;\n loading: boolean;\n dynamicSdkHasLoaded: any;\n handleError: (error: WalletError) => void;\n setDynamicSdkHasLoaded: (loaded: any) => void;\n setAddress: (address: string) => void;\n setBalances: (balances: Balance[]) => void;\n setChain: (chain: string) => void;\n setDynamicHandleLogOut: (handler: any) => void;\n setDynamicWallet: (wallet: any) => void;\n setIsConnected: (connected: boolean) => void;\n setLoading: (loading: boolean) => void;\n setNtsInterface: (nts: any) => void;\n setSessionMode: (mode: N1SessionMode | null) => void;\n setSessionPubKey: (key: Uint8Array) => void;\n setShowSidebar: (show: boolean) => void;\n setSignMessageWithSessionKey: React.Dispatch<\n React.SetStateAction<((message: any) => Promise<any>) | null>\n >;\n setSignMessageWithWalletKey: React.Dispatch<\n React.SetStateAction<((message: any) => Promise<any>) | null>\n >;\n setSignTransactionWithWalletKey: React.Dispatch<\n React.SetStateAction<((transaction: any) => Promise<any>) | null>\n >;\n setStartClosingLogin: (closing: boolean) => void;\n setUsername: (username: string) => void;\n setUserChain: (chain: string) => void;\n setViewMode: (mode: N1ModalViewMode) => void;\n setWalletPubKey: (key: Uint8Array) => void;\n setNordUser: (user: any) => void;\n showSidebar: boolean;\n startClosingLogin: boolean;\n showDynamicWidget: any;\n setShowDynamicWidget: (show: any) => void;\n darkMode: boolean;\n sessionMode: N1SessionMode | null;\n faucetUrl?: string;\n skipFinalScreen?: boolean;\n}\n"]}
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/Provider/types.ts"],"names":[],"mappings":"AAGA,MAAM,CAAN,IAAY,eAOX;AAPD,WAAY,eAAe;IACzB,2DAAO,CAAA;IACP,uEAAa,CAAA;IACb,2DAAO,CAAA;IACP,qEAAY,CAAA;IACZ,2DAAO,CAAA;IACP,mEAAW,CAAA;AACb,CAAC,EAPW,eAAe,KAAf,eAAe,QAO1B;AAED,MAAM,CAAN,IAAY,aAGX;AAHD,WAAY,aAAa;IACvB,iDAAI,CAAA;IACJ,+CAAG,CAAA;AACL,CAAC,EAHW,aAAa,KAAb,aAAa,QAGxB","sourcesContent":["import type { WalletError } from '../errors/types';\nimport { Nord } from '@n1xyz/nord-ts';\n\nexport enum N1ModalViewMode {\n Connect,\n CreateSession,\n Signing,\n CreatingUser,\n Success,\n NoWhitelist,\n}\n\nexport enum N1SessionMode {\n Nord,\n NTS,\n}\n\nexport interface CssColorOverride {\n color: string; // Color to find in CSS (e.g. '#3b82f6')\n replacement: string; // Replacement color (e.g. '#afafaf')\n}\n\nexport interface N1WalletProviderProps {\n children: React.ReactNode;\n providedSessionMode: N1SessionMode;\n appId: string;\n darkMode?: boolean;\n onError?: (error: WalletError) => void;\n faucetUrl?: string;\n nord?: Nord;\n /**\n * Optional array of color overrides: [{color: '#original', replacement: '#new'}]\n */\n colorOverrides?: CssColorOverride[];\n /**\n * If true, skip the final success screen and immediately call onDone\n */\n skipFinalScreen?: boolean;\n}\n\nexport interface Balance {\n mint: string;\n balance: bigint;\n appId: string;\n appType: string;\n}\n\nexport interface N1NordFunctions {\n // Market information functions\n getMarkets: () => Promise<any[]>;\n getOrderbook: (symbol: string) => Promise<any>;\n getTrades: (params: any) => Promise<any>;\n getMarketsStats: () => Promise<any>;\n\n // Trading functions\n placeOrder: (params: {\n sessionId: bigint | string;\n marketId: number;\n side: 'BUY' | 'SELL';\n fillMode: 'GTC' | 'IOC' | 'FOK' | 'POST_ONLY';\n isReduceOnly: boolean;\n size?: number | string;\n price?: number | string;\n quoteSize?: number | string;\n clientOrderId?: bigint | string;\n }) => Promise<bigint | undefined>;\n\n cancelOrder: (params: {\n sessionId: bigint | string;\n orderId: bigint | string;\n }) => Promise<bigint>;\n\n // Account management\n createSession: (params: {\n userPubkey: Uint8Array;\n sessionPubkey: Uint8Array;\n expiryTimestamp?: bigint;\n }) => Promise<bigint>;\n\n revokeSession: (params: { sessionId: bigint | string }) => Promise<void>;\n\n withdraw: (params: {\n sessionId: bigint | string;\n tokenId: number;\n amount: number;\n }) => Promise<void>;\n\n transfer: (params: {\n sessionId: bigint | string;\n fromAccountId: number;\n toAccountId?: number;\n tokenId: number;\n tokenDecimals: number;\n amount: number | string;\n }) => Promise<number | undefined>;\n\n // Blockchain information\n getTimestamp: () => Promise<bigint>;\n getActionNonce: () => Promise<number>;\n\n // Block and action queries\n queryBlock: (query: any) => Promise<any>;\n queryLastNBlocks: () => Promise<any>;\n queryRecentBlocks: (last_n: number) => Promise<any>;\n queryAction: (query: any) => Promise<any>;\n queryRecentActions: (last_n: number) => Promise<any>;\n getActions: (fromActionId: number, toActionId: number) => Promise<any>;\n}\n\nexport interface N1WalletState {\n address: string;\n appId: string | null;\n balances: Balance[];\n chain: string;\n isConnected: boolean;\n ntsInterface: any;\n sessionMode: N1SessionMode | null;\n sessionPubKey: Uint8Array | null;\n setShowLogin: (show: boolean) => void;\n showLogin: boolean;\n signMessageWithSessionKey: ((message: any) => Promise<any>) | null;\n signTransactionWithWalletKey: ((transaction: any) => Promise<any>) | null;\n userChain: string | null;\n username: string;\n viewMode: N1ModalViewMode;\n walletPubKey: Uint8Array | null;\n throwTestError: () => Promise<void>;\n nord?: Nord;\n faucetUrl?: string;\n nordUser?: any;\n}\n\nexport interface N1InternalWalletState {\n dynamicHandleLogOut: any;\n dynamicWallet: any;\n loading: boolean;\n dynamicSdkHasLoaded: any;\n handleError: (error: WalletError) => void;\n setDynamicSdkHasLoaded: (loaded: any) => void;\n setAddress: (address: string) => void;\n setBalances: (balances: Balance[]) => void;\n setChain: (chain: string) => void;\n setDynamicHandleLogOut: (handler: any) => void;\n setDynamicWallet: (wallet: any) => void;\n setIsConnected: (connected: boolean) => void;\n setLoading: (loading: boolean) => void;\n setNtsInterface: (nts: any) => void;\n setSessionMode: (mode: N1SessionMode | null) => void;\n setSessionPubKey: (key: Uint8Array) => void;\n setShowSidebar: (show: boolean) => void;\n setSignMessageWithSessionKey: React.Dispatch<\n React.SetStateAction<((message: any) => Promise<any>) | null>\n >;\n setSignTransactionWithWalletKey: React.Dispatch<\n React.SetStateAction<((transaction: any) => Promise<any>) | null>\n >;\n setStartClosingLogin: (closing: boolean) => void;\n setUsername: (username: string) => void;\n setUserChain: (chain: string) => void;\n setViewMode: (mode: N1ModalViewMode) => void;\n setWalletPubKey: (key: Uint8Array) => void;\n setNordUser: (user: any) => void;\n showSidebar: boolean;\n startClosingLogin: boolean;\n showDynamicWidget: any;\n setShowDynamicWidget: (show: any) => void;\n darkMode: boolean;\n sessionMode: N1SessionMode | null;\n faucetUrl?: string;\n skipFinalScreen?: boolean;\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@n1xyz/wallet-widget",
3
- "version": "0.0.27",
3
+ "version": "0.0.28",
4
4
  "description": "React wallet widget component for N1 applications",
5
5
  "main": "dist/index.js",
6
6
  "module": "dist/index.mjs",
@@ -11,6 +11,15 @@
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
+ },
14
23
  "author": "N1 Labs",
15
24
  "license": "SEE LICENSE IN LICENSE",
16
25
  "peerDependencies": {
@@ -36,7 +45,7 @@
36
45
  "@dynamic-labs/solana": "3.5.0",
37
46
  "@n1xyz/nts-sdk": "0.0.38",
38
47
  "@solana/web3.js": "^1.98.1",
39
- "@n1xyz/nord-ts": "0.1.3",
48
+ "@n1xyz/nord-ts": "0.1.8",
40
49
  "@tailwindcss/container-queries": "^0.1.1",
41
50
  "blockies-react-svg": "^0.0.13",
42
51
  "lucide-react": "^0.344.0",
@@ -45,14 +54,5 @@
45
54
  },
46
55
  "publishConfig": {
47
56
  "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"
57
57
  }
58
- }
58
+ }