From c9306493f066202dd9daa6ea9d123ff3fc6df912 Mon Sep 17 00:00:00 2001 From: PhilReact Date: Tue, 29 Oct 2024 15:57:27 +0200 Subject: [PATCH] temp replace storage --- index.html | 2 + package-lock.json | 420 ++++---- src/App.tsx | 141 +-- src/ExtStates/NotAuthenticated.tsx | 5 +- src/background-cases.ts | 66 +- src/background.ts | 928 ++++++----------- src/backgroundFunctions/encryption.ts | 18 +- src/components/Apps/AppRating.tsx | 92 +- .../Apps/useQortalMessageListener.tsx | 7 +- src/components/Group/Group.tsx | 70 +- src/components/Group/WebsocketActive.tsx | 2 +- src/components/Save/Save.tsx | 283 +++--- src/main.tsx | 4 +- src/messaging/messagesToBackground.tsx | 10 +- src/qdn/encryption/group-encryption.ts | 1 + src/qdn/publish/pubish.ts | 9 +- src/qortalRequests copy.ts | 428 ++++++++ src/qortalRequests.ts | 958 +++++++++++------- src/qortalRequests/get.ts | 26 +- src/utils/chromeStorage.ts | 72 +- 20 files changed, 1901 insertions(+), 1641 deletions(-) create mode 100644 src/qortalRequests copy.ts diff --git a/index.html b/index.html index 4745170..fe0ef55 100644 --- a/index.html +++ b/index.html @@ -5,6 +5,8 @@ + + Qortal Extension diff --git a/package-lock.json b/package-lock.json index ae9f611..4281ead 100644 --- a/package-lock.json +++ b/package-lock.json @@ -117,11 +117,12 @@ } }, "node_modules/@babel/code-frame": { - "version": "7.24.2", - "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.24.2.tgz", - "integrity": "sha512-y5+tLQyV8pg3fsiln67BVLD1P13Eg4lh5RW9mF0zUuvLrv9uIQ4MCL+CRT+FTsBlBjcIan6PGsLcBN0m3ClUyQ==", + "version": "7.26.0", + "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.26.0.tgz", + "integrity": "sha512-INCKxTtbXtcNbUZ3YXutwMpEleqttcswhAdee7dhuoVrD2cnuc3PqtERBtxkX5nziX9vnBL8WXmSGwv8CuPV6g==", "dependencies": { - "@babel/highlight": "^7.24.2", + "@babel/helper-validator-identifier": "^7.25.9", + "js-tokens": "^4.0.0", "picocolors": "^1.0.0" }, "engines": { @@ -129,30 +130,30 @@ } }, "node_modules/@babel/compat-data": { - "version": "7.24.1", - "resolved": "https://registry.npmjs.org/@babel/compat-data/-/compat-data-7.24.1.tgz", - "integrity": "sha512-Pc65opHDliVpRHuKfzI+gSA4zcgr65O4cl64fFJIWEEh8JoHIHh0Oez1Eo8Arz8zq/JhgKodQaxEwUPRtZylVA==", + "version": "7.26.0", + "resolved": "https://registry.npmjs.org/@babel/compat-data/-/compat-data-7.26.0.tgz", + "integrity": "sha512-qETICbZSLe7uXv9VE8T/RWOdIE5qqyTucOt4zLYMafj2MRO271VGgLd4RACJMeBO37UPWhXiKMBk7YlJ0fOzQA==", "dev": true, "engines": { "node": ">=6.9.0" } }, "node_modules/@babel/core": { - "version": "7.24.1", - "resolved": "https://registry.npmjs.org/@babel/core/-/core-7.24.1.tgz", - "integrity": "sha512-F82udohVyIgGAY2VVj/g34TpFUG606rumIHjTfVbssPg2zTR7PuuEpZcX8JA6sgBfIYmJrFtWgPvHQuJamVqZQ==", + "version": "7.26.0", + "resolved": "https://registry.npmjs.org/@babel/core/-/core-7.26.0.tgz", + "integrity": "sha512-i1SLeK+DzNnQ3LL/CswPCa/E5u4lh1k6IAEphON8F+cXt0t9euTshDru0q7/IqMa1PMPz5RnHuHscF8/ZJsStg==", "dev": true, "dependencies": { "@ampproject/remapping": "^2.2.0", - "@babel/code-frame": "^7.24.1", - "@babel/generator": "^7.24.1", - "@babel/helper-compilation-targets": "^7.23.6", - "@babel/helper-module-transforms": "^7.23.3", - "@babel/helpers": "^7.24.1", - "@babel/parser": "^7.24.1", - "@babel/template": "^7.24.0", - "@babel/traverse": "^7.24.1", - "@babel/types": "^7.24.0", + "@babel/code-frame": "^7.26.0", + "@babel/generator": "^7.26.0", + "@babel/helper-compilation-targets": "^7.25.9", + "@babel/helper-module-transforms": "^7.26.0", + "@babel/helpers": "^7.26.0", + "@babel/parser": "^7.26.0", + "@babel/template": "^7.25.9", + "@babel/traverse": "^7.25.9", + "@babel/types": "^7.26.0", "convert-source-map": "^2.0.0", "debug": "^4.1.0", "gensync": "^1.0.0-beta.2", @@ -177,29 +178,29 @@ } }, "node_modules/@babel/generator": { - "version": "7.24.1", - "resolved": "https://registry.npmjs.org/@babel/generator/-/generator-7.24.1.tgz", - "integrity": "sha512-DfCRfZsBcrPEHUfuBMgbJ1Ut01Y/itOs+hY2nFLgqsqXd52/iSiVq5TITtUasIUgm+IIKdY2/1I7auiQOEeC9A==", - "dev": true, + "version": "7.26.0", + "resolved": "https://registry.npmjs.org/@babel/generator/-/generator-7.26.0.tgz", + "integrity": "sha512-/AIkAmInnWwgEAJGQr9vY0c66Mj6kjkE2ZPB1PurTRaRAh3U+J45sAQMjQDJdh4WbR3l0x5xkimXBKyBXXAu2w==", "dependencies": { - "@babel/types": "^7.24.0", + "@babel/parser": "^7.26.0", + "@babel/types": "^7.26.0", "@jridgewell/gen-mapping": "^0.3.5", "@jridgewell/trace-mapping": "^0.3.25", - "jsesc": "^2.5.1" + "jsesc": "^3.0.2" }, "engines": { "node": ">=6.9.0" } }, "node_modules/@babel/helper-compilation-targets": { - "version": "7.23.6", - "resolved": "https://registry.npmjs.org/@babel/helper-compilation-targets/-/helper-compilation-targets-7.23.6.tgz", - "integrity": "sha512-9JB548GZoQVmzrFgp8o7KxdgkTGm6xs9DW0o/Pim72UDjzr5ObUQ6ZzYPqA+g9OTS2bBQoctLJrky0RDCAWRgQ==", + "version": "7.25.9", + "resolved": "https://registry.npmjs.org/@babel/helper-compilation-targets/-/helper-compilation-targets-7.25.9.tgz", + "integrity": "sha512-j9Db8Suy6yV/VHa4qzrj9yZfZxhLWQdVnRlXxmKLYlhWUVB1sB2G5sxuWYXk/whHD9iW76PmNzxZ4UCnTQTVEQ==", "dev": true, "dependencies": { - "@babel/compat-data": "^7.23.5", - "@babel/helper-validator-option": "^7.23.5", - "browserslist": "^4.22.2", + "@babel/compat-data": "^7.25.9", + "@babel/helper-validator-option": "^7.25.9", + "browserslist": "^4.24.0", "lru-cache": "^5.1.1", "semver": "^6.3.1" }, @@ -216,62 +217,27 @@ "semver": "bin/semver.js" } }, - "node_modules/@babel/helper-environment-visitor": { - "version": "7.22.20", - "resolved": "https://registry.npmjs.org/@babel/helper-environment-visitor/-/helper-environment-visitor-7.22.20.tgz", - "integrity": "sha512-zfedSIzFhat/gFhWfHtgWvlec0nqB9YEIVrpuwjruLlXfUSnA8cJB0miHKwqDnQ7d32aKo2xt88/xZptwxbfhA==", - "dev": true, - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@babel/helper-function-name": { - "version": "7.23.0", - "resolved": "https://registry.npmjs.org/@babel/helper-function-name/-/helper-function-name-7.23.0.tgz", - "integrity": "sha512-OErEqsrxjZTJciZ4Oo+eoZqeW9UIiOcuYKRJA4ZAgV9myA+pOXhhmpfNCKjEH/auVfEYVFJ6y1Tc4r0eIApqiw==", - "dev": true, - "dependencies": { - "@babel/template": "^7.22.15", - "@babel/types": "^7.23.0" - }, - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@babel/helper-hoist-variables": { - "version": "7.22.5", - "resolved": "https://registry.npmjs.org/@babel/helper-hoist-variables/-/helper-hoist-variables-7.22.5.tgz", - "integrity": "sha512-wGjk9QZVzvknA6yKIUURb8zY3grXCcOZt+/7Wcy8O2uctxhplmUPkOdlgoNhmdVee2c92JXbf1xpMtVNbfoxRw==", - "dev": true, - "dependencies": { - "@babel/types": "^7.22.5" - }, - "engines": { - "node": ">=6.9.0" - } - }, "node_modules/@babel/helper-module-imports": { - "version": "7.24.1", - "resolved": "https://registry.npmjs.org/@babel/helper-module-imports/-/helper-module-imports-7.24.1.tgz", - "integrity": "sha512-HfEWzysMyOa7xI5uQHc/OcZf67/jc+xe/RZlznWQHhbb8Pg1SkRdbK4yEi61aY8wxQA7PkSfoojtLQP/Kpe3og==", + "version": "7.25.9", + "resolved": "https://registry.npmjs.org/@babel/helper-module-imports/-/helper-module-imports-7.25.9.tgz", + "integrity": "sha512-tnUA4RsrmflIM6W6RFTLFSXITtl0wKjgpnLgXyowocVPrbYrLUXSBXDgTs8BlbmIzIdlBySRQjINYs2BAkiLtw==", "dependencies": { - "@babel/types": "^7.24.0" + "@babel/traverse": "^7.25.9", + "@babel/types": "^7.25.9" }, "engines": { "node": ">=6.9.0" } }, "node_modules/@babel/helper-module-transforms": { - "version": "7.23.3", - "resolved": "https://registry.npmjs.org/@babel/helper-module-transforms/-/helper-module-transforms-7.23.3.tgz", - "integrity": "sha512-7bBs4ED9OmswdfDzpz4MpWgSrV7FXlc3zIagvLFjS5H+Mk7Snr21vQ6QwrsoCGMfNC4e4LQPdoULEt4ykz0SRQ==", + "version": "7.26.0", + "resolved": "https://registry.npmjs.org/@babel/helper-module-transforms/-/helper-module-transforms-7.26.0.tgz", + "integrity": "sha512-xO+xu6B5K2czEnQye6BHA7DolFFmS3LB7stHZFaOLb1pAwO1HWLS8fXA+eh0A2yIvltPVmx3eNNDBJA2SLHXFw==", "dev": true, "dependencies": { - "@babel/helper-environment-visitor": "^7.22.20", - "@babel/helper-module-imports": "^7.22.15", - "@babel/helper-simple-access": "^7.22.5", - "@babel/helper-split-export-declaration": "^7.22.6", - "@babel/helper-validator-identifier": "^7.22.20" + "@babel/helper-module-imports": "^7.25.9", + "@babel/helper-validator-identifier": "^7.25.9", + "@babel/traverse": "^7.25.9" }, "engines": { "node": ">=6.9.0" @@ -281,96 +247,59 @@ } }, "node_modules/@babel/helper-plugin-utils": { - "version": "7.24.0", - "resolved": "https://registry.npmjs.org/@babel/helper-plugin-utils/-/helper-plugin-utils-7.24.0.tgz", - "integrity": "sha512-9cUznXMG0+FxRuJfvL82QlTqIzhVW9sL0KjMPHhAOOvpQGL8QtdxnBKILjBqxlHyliz0yCa1G903ZXI/FuHy2w==", + "version": "7.25.9", + "resolved": "https://registry.npmjs.org/@babel/helper-plugin-utils/-/helper-plugin-utils-7.25.9.tgz", + "integrity": "sha512-kSMlyUVdWe25rEsRGviIgOWnoT/nfABVWlqt9N19/dIPWViAOW2s9wznP5tURbs/IDuNk4gPy3YdYRgH3uxhBw==", "dev": true, "engines": { "node": ">=6.9.0" } }, - "node_modules/@babel/helper-simple-access": { - "version": "7.22.5", - "resolved": "https://registry.npmjs.org/@babel/helper-simple-access/-/helper-simple-access-7.22.5.tgz", - "integrity": "sha512-n0H99E/K+Bika3++WNL17POvo4rKWZ7lZEp1Q+fStVbUi8nxPQEBOlTmCOxW/0JsS56SKKQ+ojAe2pHKJHN35w==", - "dev": true, - "dependencies": { - "@babel/types": "^7.22.5" - }, - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@babel/helper-split-export-declaration": { - "version": "7.22.6", - "resolved": "https://registry.npmjs.org/@babel/helper-split-export-declaration/-/helper-split-export-declaration-7.22.6.tgz", - "integrity": "sha512-AsUnxuLhRYsisFiaJwvp1QF+I3KjD5FOxut14q/GzovUe6orHLesW2C7d754kRm53h5gqrz6sFl6sxc4BVtE/g==", - "dev": true, - "dependencies": { - "@babel/types": "^7.22.5" - }, - "engines": { - "node": ">=6.9.0" - } - }, "node_modules/@babel/helper-string-parser": { - "version": "7.24.1", - "resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.24.1.tgz", - "integrity": "sha512-2ofRCjnnA9y+wk8b9IAREroeUP02KHp431N2mhKniy2yKIDKpbrHv9eXwm8cBeWQYcJmzv5qKCu65P47eCF7CQ==", + "version": "7.25.9", + "resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.25.9.tgz", + "integrity": "sha512-4A/SCr/2KLd5jrtOMFzaKjVtAei3+2r/NChoBNoZ3EyP/+GlhoaEGoWOZUmFmoITP7zOJyHIMm+DYRd8o3PvHA==", "engines": { "node": ">=6.9.0" } }, "node_modules/@babel/helper-validator-identifier": { - "version": "7.22.20", - "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.22.20.tgz", - "integrity": "sha512-Y4OZ+ytlatR8AI+8KZfKuL5urKp7qey08ha31L8b3BwewJAoJamTzyvxPR/5D+KkdJCGPq/+8TukHBlY10FX9A==", + "version": "7.25.9", + "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.25.9.tgz", + "integrity": "sha512-Ed61U6XJc3CVRfkERJWDz4dJwKe7iLmmJsbOGu9wSloNSFttHV0I8g6UAgb7qnK5ly5bGLPd4oXZlxCdANBOWQ==", "engines": { "node": ">=6.9.0" } }, "node_modules/@babel/helper-validator-option": { - "version": "7.23.5", - "resolved": "https://registry.npmjs.org/@babel/helper-validator-option/-/helper-validator-option-7.23.5.tgz", - "integrity": "sha512-85ttAOMLsr53VgXkTbkx8oA6YTfT4q7/HzXSLEYmjcSTJPMPQtvq1BD79Byep5xMUYbGRzEpDsjUf3dyp54IKw==", + "version": "7.25.9", + "resolved": "https://registry.npmjs.org/@babel/helper-validator-option/-/helper-validator-option-7.25.9.tgz", + "integrity": "sha512-e/zv1co8pp55dNdEcCynfj9X7nyUKUXoUEwfXqaZt0omVOmDe9oOTdKStH4GmAw6zxMFs50ZayuMfHDKlO7Tfw==", "dev": true, "engines": { "node": ">=6.9.0" } }, "node_modules/@babel/helpers": { - "version": "7.24.1", - "resolved": "https://registry.npmjs.org/@babel/helpers/-/helpers-7.24.1.tgz", - "integrity": "sha512-BpU09QqEe6ZCHuIHFphEFgvNSrubve1FtyMton26ekZ85gRGi6LrTF7zArARp2YvyFxloeiRmtSCq5sjh1WqIg==", + "version": "7.26.0", + "resolved": "https://registry.npmjs.org/@babel/helpers/-/helpers-7.26.0.tgz", + "integrity": "sha512-tbhNuIxNcVb21pInl3ZSjksLCvgdZy9KwJ8brv993QtIVKJBBkYXz4q4ZbAv31GdnC+R90np23L5FbEBlthAEw==", "dev": true, "dependencies": { - "@babel/template": "^7.24.0", - "@babel/traverse": "^7.24.1", - "@babel/types": "^7.24.0" - }, - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@babel/highlight": { - "version": "7.24.2", - "resolved": "https://registry.npmjs.org/@babel/highlight/-/highlight-7.24.2.tgz", - "integrity": "sha512-Yac1ao4flkTxTteCDZLEvdxg2fZfz1v8M4QpaGypq/WPDqg3ijHYbDfs+LG5hvzSoqaSZ9/Z9lKSP3CjZjv+pA==", - "dependencies": { - "@babel/helper-validator-identifier": "^7.22.20", - "chalk": "^2.4.2", - "js-tokens": "^4.0.0", - "picocolors": "^1.0.0" + "@babel/template": "^7.25.9", + "@babel/types": "^7.26.0" }, "engines": { "node": ">=6.9.0" } }, "node_modules/@babel/parser": { - "version": "7.24.1", - "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.24.1.tgz", - "integrity": "sha512-Zo9c7N3xdOIQrNip7Lc9wvRPzlRtovHVE4lkz8WEDr7uYh/GMQhSiIgFxGIArRHYdJE5kxtZjAf8rT0xhdLCzg==", - "dev": true, + "version": "7.26.1", + "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.26.1.tgz", + "integrity": "sha512-reoQYNiAJreZNsJzyrDNzFQ+IQ5JFiIzAHJg9bn94S3l+4++J7RsIhNMoB+lgP/9tpmiAQqspv+xfdxTSzREOw==", + "dependencies": { + "@babel/types": "^7.26.0" + }, "bin": { "parser": "bin/babel-parser.js" }, @@ -420,33 +349,28 @@ } }, "node_modules/@babel/template": { - "version": "7.24.0", - "resolved": "https://registry.npmjs.org/@babel/template/-/template-7.24.0.tgz", - "integrity": "sha512-Bkf2q8lMB0AFpX0NFEqSbx1OkTHf0f+0j82mkw+ZpzBnkk7e9Ql0891vlfgi+kHwOk8tQjiQHpqh4LaSa0fKEA==", - "dev": true, + "version": "7.25.9", + "resolved": "https://registry.npmjs.org/@babel/template/-/template-7.25.9.tgz", + "integrity": "sha512-9DGttpmPvIxBb/2uwpVo3dqJ+O6RooAFOS+lB+xDqoE2PVCE8nfoHMdZLpfCQRLwvohzXISPZcgxt80xLfsuwg==", "dependencies": { - "@babel/code-frame": "^7.23.5", - "@babel/parser": "^7.24.0", - "@babel/types": "^7.24.0" + "@babel/code-frame": "^7.25.9", + "@babel/parser": "^7.25.9", + "@babel/types": "^7.25.9" }, "engines": { "node": ">=6.9.0" } }, "node_modules/@babel/traverse": { - "version": "7.24.1", - "resolved": "https://registry.npmjs.org/@babel/traverse/-/traverse-7.24.1.tgz", - "integrity": "sha512-xuU6o9m68KeqZbQuDt2TcKSxUw/mrsvavlEqQ1leZ/B+C9tk6E4sRWy97WaXgvq5E+nU3cXMxv3WKOCanVMCmQ==", - "dev": true, + "version": "7.25.9", + "resolved": "https://registry.npmjs.org/@babel/traverse/-/traverse-7.25.9.tgz", + "integrity": "sha512-ZCuvfwOwlz/bawvAuvcj8rrithP2/N55Tzz342AkTvq4qaWbGfmCk/tKhNaV2cthijKrPAA8SRJV5WWe7IBMJw==", "dependencies": { - "@babel/code-frame": "^7.24.1", - "@babel/generator": "^7.24.1", - "@babel/helper-environment-visitor": "^7.22.20", - "@babel/helper-function-name": "^7.23.0", - "@babel/helper-hoist-variables": "^7.22.5", - "@babel/helper-split-export-declaration": "^7.22.6", - "@babel/parser": "^7.24.1", - "@babel/types": "^7.24.0", + "@babel/code-frame": "^7.25.9", + "@babel/generator": "^7.25.9", + "@babel/parser": "^7.25.9", + "@babel/template": "^7.25.9", + "@babel/types": "^7.25.9", "debug": "^4.3.1", "globals": "^11.1.0" }, @@ -455,13 +379,12 @@ } }, "node_modules/@babel/types": { - "version": "7.24.0", - "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.24.0.tgz", - "integrity": "sha512-+j7a5c253RfKh8iABBhywc8NSfP5LURe7Uh4qpsh6jc+aLJguvmIUBdjSdEMQv2bENrCR5MfRdjGo7vzS/ob7w==", + "version": "7.26.0", + "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.26.0.tgz", + "integrity": "sha512-Z/yiTPj+lDVnF7lWeKCIJzaIkI0vYO87dMpZ4bg4TDrFe4XXLFWL1TbXU27gBP3QccxV9mZICCrnjnYlJjXHOA==", "dependencies": { - "@babel/helper-string-parser": "^7.23.4", - "@babel/helper-validator-identifier": "^7.22.20", - "to-fast-properties": "^2.0.0" + "@babel/helper-string-parser": "^7.25.9", + "@babel/helper-validator-identifier": "^7.25.9" }, "engines": { "node": ">=6.9.0" @@ -1764,7 +1687,6 @@ "version": "0.3.5", "resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.5.tgz", "integrity": "sha512-IzL8ZoEDIBRWEzlCcRhOaCupYyN5gdIK+Q6fbFdPDg6HqX6jpkItn7DFIpW9LQzXG6Df9sA7+OKnq0qlz/GaQg==", - "dev": true, "dependencies": { "@jridgewell/set-array": "^1.2.1", "@jridgewell/sourcemap-codec": "^1.4.10", @@ -1778,7 +1700,6 @@ "version": "3.1.2", "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.2.tgz", "integrity": "sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==", - "dev": true, "engines": { "node": ">=6.0.0" } @@ -1787,22 +1708,31 @@ "version": "1.2.1", "resolved": "https://registry.npmjs.org/@jridgewell/set-array/-/set-array-1.2.1.tgz", "integrity": "sha512-R8gLRTZeyp03ymzP/6Lil/28tGeGEzhx1q2k703KGWRAI1VdvPIXdG70VJc2pAMw3NA6JKL5hhFu1sJX0Mnn/A==", - "dev": true, "engines": { "node": ">=6.0.0" } }, + "node_modules/@jridgewell/source-map": { + "version": "0.3.6", + "resolved": "https://registry.npmjs.org/@jridgewell/source-map/-/source-map-0.3.6.tgz", + "integrity": "sha512-1ZJTZebgqllO79ue2bm3rIGud/bOe0pP5BjSRCRxxYkEZS8STV7zN84UBbiYu7jy+eCKSnVIUgoWWE/tt+shMQ==", + "dev": true, + "optional": true, + "peer": true, + "dependencies": { + "@jridgewell/gen-mapping": "^0.3.5", + "@jridgewell/trace-mapping": "^0.3.25" + } + }, "node_modules/@jridgewell/sourcemap-codec": { "version": "1.4.15", "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.4.15.tgz", - "integrity": "sha512-eF2rxCRulEKXHTRiDrDy6erMYWqNw4LPdQ8UQA4huuxaQsVeRPFl2oM8oDGxMFhJUWZf9McpLtJasDDZb/Bpeg==", - "devOptional": true + "integrity": "sha512-eF2rxCRulEKXHTRiDrDy6erMYWqNw4LPdQ8UQA4huuxaQsVeRPFl2oM8oDGxMFhJUWZf9McpLtJasDDZb/Bpeg==" }, "node_modules/@jridgewell/trace-mapping": { "version": "0.3.25", "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.25.tgz", "integrity": "sha512-vNk6aEwybGtawWmy/PzwnGDOjCkLWSD2wqvjGGAgOAwCGWySYXfYoxt00IJkTF+8Lb57DwOb3Aa0o9CApepiYQ==", - "dev": true, "dependencies": { "@jridgewell/resolve-uri": "^3.1.0", "@jridgewell/sourcemap-codec": "^1.4.14" @@ -3729,6 +3659,7 @@ "version": "3.2.1", "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-3.2.1.tgz", "integrity": "sha512-VT0ZI6kZRdTh8YyJw3SMbYm/u+NqfsAxEpWO0Pf9sq8/e94WxxOpPKx9FR1FlyCtOVDNOQ+8ntlqFxiRc+r5qA==", + "dev": true, "dependencies": { "color-convert": "^1.9.0" }, @@ -3937,9 +3868,9 @@ } }, "node_modules/browserslist": { - "version": "4.23.0", - "resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.23.0.tgz", - "integrity": "sha512-QW8HiM1shhT2GuzkvklfjcKDiWFXHOeFCIA/huJPwHsslwcydgk7X+z2zXpEijP98UCY7HbubZt5J2Zgvf0CaQ==", + "version": "4.24.2", + "resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.24.2.tgz", + "integrity": "sha512-ZIc+Q62revdMcqC6aChtW4jz3My3klmCO1fEmINZY/8J3EpBg5/A/D0AKmBveUh6pgoeycoMkVMko84tuYS+Gg==", "dev": true, "funding": [ { @@ -3956,10 +3887,10 @@ } ], "dependencies": { - "caniuse-lite": "^1.0.30001587", - "electron-to-chromium": "^1.4.668", - "node-releases": "^2.0.14", - "update-browserslist-db": "^1.0.13" + "caniuse-lite": "^1.0.30001669", + "electron-to-chromium": "^1.5.41", + "node-releases": "^2.0.18", + "update-browserslist-db": "^1.1.1" }, "bin": { "browserslist": "cli.js" @@ -3999,6 +3930,14 @@ "node": "*" } }, + "node_modules/buffer-from": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/buffer-from/-/buffer-from-1.1.2.tgz", + "integrity": "sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ==", + "dev": true, + "optional": true, + "peer": true + }, "node_modules/cac": { "version": "6.7.14", "resolved": "https://registry.npmjs.org/cac/-/cac-6.7.14.tgz", @@ -4045,9 +3984,9 @@ } }, "node_modules/caniuse-lite": { - "version": "1.0.30001599", - "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001599.tgz", - "integrity": "sha512-LRAQHZ4yT1+f9LemSMeqdMpMxZcc4RMWdj4tiFe3G8tNkWK+E58g+/tzotb5cU6TbcVJLr4fySiAW7XmxQvZQA==", + "version": "1.0.30001674", + "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001674.tgz", + "integrity": "sha512-jOsKlZVRnzfhLojb+Ykb+gyUSp9Xb57So+fAiFlLzzTKpqg8xxSav0e40c8/4F/v9N8QSvrRRaLeVzQbLqomYw==", "dev": true, "funding": [ { @@ -4097,6 +4036,7 @@ "version": "2.4.2", "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz", "integrity": "sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==", + "dev": true, "dependencies": { "ansi-styles": "^3.2.1", "escape-string-regexp": "^1.0.5", @@ -4387,6 +4327,7 @@ "version": "1.9.3", "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-1.9.3.tgz", "integrity": "sha512-QfAUtd+vFdAtFQcC8CCyYt1fYWxSqAiK2cSD6zDB8N3cpsEBAvRxp9zOGg6G/SHHJYAT88/az/IuDGALsNVbGg==", + "dev": true, "dependencies": { "color-name": "1.1.3" } @@ -4394,7 +4335,8 @@ "node_modules/color-name": { "version": "1.1.3", "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.3.tgz", - "integrity": "sha512-72fSenhMw2HZMTVHeCA9KCmpEIbzWiQsjN+BHcBbS9vr1mtt+vJjPdksIBNUmKAW8TFUDPJK5SUU3QhE9NEXDw==" + "integrity": "sha512-72fSenhMw2HZMTVHeCA9KCmpEIbzWiQsjN+BHcBbS9vr1mtt+vJjPdksIBNUmKAW8TFUDPJK5SUU3QhE9NEXDw==", + "dev": true }, "node_modules/combined-stream": { "version": "1.0.8", @@ -4554,11 +4496,11 @@ } }, "node_modules/debug": { - "version": "4.3.4", - "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.4.tgz", - "integrity": "sha512-PRWFHuSU3eDtQJPvnNY7Jcket1j0t5OuOsFzPPzsekD52Zl8qUfFIPEiswXqIvHWGVHOgX+7G/vCNNhehwxfkQ==", + "version": "4.3.7", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.7.tgz", + "integrity": "sha512-Er2nc/H7RrMXZBFCEim6TCmMk02Z8vLC2Rbi1KEBggpo0fS6l0S1nnapwmIi3yW/+GOJap1Krg4w0Hg80oCqgQ==", "dependencies": { - "ms": "2.1.2" + "ms": "^2.1.3" }, "engines": { "node": ">=6.0" @@ -4753,9 +4695,9 @@ "integrity": "sha512-cTOAhc36AalkjtBpfG6O8JimdTMWNXjiePT2xQH/ppBGi/4uIpmj8eKyIkMJErXWARyINV/sB38yf8JCLF5pbQ==" }, "node_modules/electron-to-chromium": { - "version": "1.4.710", - "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.4.710.tgz", - "integrity": "sha512-w+9yAVHoHhysCa+gln7AzbO9CdjFcL/wN/5dd+XW/Msl2d/4+WisEaCF1nty0xbAKaxdaJfgLB2296U7zZB7BA==", + "version": "1.5.49", + "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.5.49.tgz", + "integrity": "sha512-ZXfs1Of8fDb6z7WEYZjXpgIRF6MEu8JdeGA0A40aZq6OQbS+eJpnnV49epZRna2DU/YsEjSQuGtQPPtvt6J65A==", "dev": true }, "node_modules/elementtree": { @@ -4892,9 +4834,9 @@ } }, "node_modules/escalade": { - "version": "3.1.2", - "resolved": "https://registry.npmjs.org/escalade/-/escalade-3.1.2.tgz", - "integrity": "sha512-ErCHMCae19vR8vQGe50xIsVomy19rg6gFu3+r3jkEO46suLMWBksvVyoGgQV+jOfl84ZSOSlmv6Gxa89PmTGmA==", + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/escalade/-/escalade-3.2.0.tgz", + "integrity": "sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA==", "dev": true, "engines": { "node": ">=6" @@ -4904,6 +4846,7 @@ "version": "1.0.5", "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz", "integrity": "sha512-vbRorB5FUQWvla16U8R/qgaFIya2qGzwDrNmCZuYKrbdSUMG6I1ZCGQRefkRVhuOkIGVne7BQ35DSfo1qvJqFg==", + "dev": true, "engines": { "node": ">=0.8.0" } @@ -5648,7 +5591,6 @@ "version": "11.12.0", "resolved": "https://registry.npmjs.org/globals/-/globals-11.12.0.tgz", "integrity": "sha512-WOBp/EEGUiIsJSp7wcv/y6MO+lV9UoncWqxuFfm8eBwzWNgyfBd6Gz+IeKQ9jCmyhoH99g15M3T+QaVHFjizVA==", - "dev": true, "engines": { "node": ">=4" } @@ -5704,6 +5646,7 @@ "version": "3.0.0", "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz", "integrity": "sha512-sKJf1+ceQBr4SMkvQnBDNDtf4TXpVhVGateu0t918bl30FnbE2m4vNLX+VWe/dpjlb+HugGYzW7uQXH98HPEYw==", + "dev": true, "engines": { "node": ">=4" } @@ -6371,15 +6314,14 @@ } }, "node_modules/jsesc": { - "version": "2.5.2", - "resolved": "https://registry.npmjs.org/jsesc/-/jsesc-2.5.2.tgz", - "integrity": "sha512-OYu7XEzjkCQ3C5Ps3QIZsQfNpqoJyZZA99wd9aWd05NCtC5pWOkShK2mkL6HXQR6/Cy2lbNdPlZBpuQHXE63gA==", - "dev": true, + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/jsesc/-/jsesc-3.0.2.tgz", + "integrity": "sha512-xKqzzWXDttJuOcawBt4KnKHHIf5oQ/Cxax+0PWFG+DFDgHNAdi+TXECADI+RYiFUMmx8792xsMbbgXj4CwnP4g==", "bin": { "jsesc": "bin/jsesc" }, "engines": { - "node": ">=4" + "node": ">=6" } }, "node_modules/json-buffer": { @@ -6805,9 +6747,9 @@ } }, "node_modules/ms": { - "version": "2.1.2", - "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz", - "integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==" + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==" }, "node_modules/mute-stream": { "version": "0.0.8", @@ -6876,9 +6818,9 @@ "dev": true }, "node_modules/node-releases": { - "version": "2.0.14", - "resolved": "https://registry.npmjs.org/node-releases/-/node-releases-2.0.14.tgz", - "integrity": "sha512-y10wOWt8yZpqXmOgRo77WaHEmhYQYGNA6y421PKsKYWEK8aW+cqAphborZDhqfyKrbZEN92CN1X2KbafY2s7Yw==", + "version": "2.0.18", + "resolved": "https://registry.npmjs.org/node-releases/-/node-releases-2.0.18.tgz", + "integrity": "sha512-d9VeXT4SJ7ZeOqGX6R5EM022wpL+eWPooLI+5UpWn2jCT1aosUQEhQP214x33Wkwx3JQMvIm+tIoVOdodFS40g==", "dev": true }, "node_modules/npm": { @@ -9574,9 +9516,9 @@ "integrity": "sha512-F3asv42UuXchdzt+xXqfW1OGlVBe+mxa2mqI0pg5yAHZPvFmY3Y6drSf/GQ1A86WgWEN9Kzh/WrgKa6iGcHXLg==" }, "node_modules/picocolors": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.0.0.tgz", - "integrity": "sha512-1fygroTLlHu66zi26VoTDv8yRgm0Fccecssto+MhsZ0D/DGW2sm8E8AjW7NU5VVTRt5GxbeZ5qBuJr+HyLYkjQ==" + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", + "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==" }, "node_modules/picomatch": { "version": "2.3.1", @@ -10953,6 +10895,29 @@ "node": ">=0.10.0" } }, + "node_modules/source-map-support": { + "version": "0.5.21", + "resolved": "https://registry.npmjs.org/source-map-support/-/source-map-support-0.5.21.tgz", + "integrity": "sha512-uBHU3L3czsIyYXKX88fdrGovxdSCoTGDRZ6SYXtSRxLZUzHg5P/66Ht6uoUlHu9EZod+inXhKo3qQgwXUT/y1w==", + "dev": true, + "optional": true, + "peer": true, + "dependencies": { + "buffer-from": "^1.0.0", + "source-map": "^0.6.0" + } + }, + "node_modules/source-map-support/node_modules/source-map": { + "version": "0.6.1", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz", + "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==", + "dev": true, + "optional": true, + "peer": true, + "engines": { + "node": ">=0.10.0" + } + }, "node_modules/split2": { "version": "4.2.0", "resolved": "https://registry.npmjs.org/split2/-/split2-4.2.0.tgz", @@ -11104,6 +11069,7 @@ "version": "5.5.0", "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.5.0.tgz", "integrity": "sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow==", + "dev": true, "dependencies": { "has-flag": "^3.0.0" }, @@ -11152,6 +11118,34 @@ "resolved": "https://registry.npmjs.org/yallist/-/yallist-4.0.0.tgz", "integrity": "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==" }, + "node_modules/terser": { + "version": "5.36.0", + "resolved": "https://registry.npmjs.org/terser/-/terser-5.36.0.tgz", + "integrity": "sha512-IYV9eNMuFAV4THUspIRXkLakHnV6XO7FEdtKjf/mDyrnqUg9LnlOn6/RwRvM9SZjR4GUq8Nk8zj67FzVARr74w==", + "dev": true, + "optional": true, + "peer": true, + "dependencies": { + "@jridgewell/source-map": "^0.3.3", + "acorn": "^8.8.2", + "commander": "^2.20.0", + "source-map-support": "~0.5.20" + }, + "bin": { + "terser": "bin/terser" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/terser/node_modules/commander": { + "version": "2.20.3", + "resolved": "https://registry.npmjs.org/commander/-/commander-2.20.3.tgz", + "integrity": "sha512-GpVkmM8vF2vQUkj2LvZmD35JxeJOLCwJ9cUkugyk2nuhbv3+mJvpLYYt+0+USMxE+oj+ey/lJEnhZw75x/OMcQ==", + "dev": true, + "optional": true, + "peer": true + }, "node_modules/text-table": { "version": "0.2.0", "resolved": "https://registry.npmjs.org/text-table/-/text-table-0.2.0.tgz", @@ -11239,14 +11233,6 @@ "node": ">=0.6.0" } }, - "node_modules/to-fast-properties": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/to-fast-properties/-/to-fast-properties-2.0.0.tgz", - "integrity": "sha512-/OaKK0xYrs3DmxRYqL/yDc+FxFUVYhDlXMhRmv3z915w2HF1tnN1omB354j8VUGO/hbRzyD6Y3sA7v7GS/ceog==", - "engines": { - "node": ">=4" - } - }, "node_modules/to-regex-range": { "version": "5.0.1", "resolved": "https://registry.npmjs.org/to-regex-range/-/to-regex-range-5.0.1.tgz", @@ -11505,9 +11491,9 @@ } }, "node_modules/update-browserslist-db": { - "version": "1.0.13", - "resolved": "https://registry.npmjs.org/update-browserslist-db/-/update-browserslist-db-1.0.13.tgz", - "integrity": "sha512-xebP81SNcPuNpPP3uzeW1NYXxI3rxyJzF3pD6sH4jE7o/IX+WtSpwnVU+qIsDPyk0d3hmFQ7mjqc6AtV604hbg==", + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/update-browserslist-db/-/update-browserslist-db-1.1.1.tgz", + "integrity": "sha512-R8UzCaa9Az+38REPiJ1tXlImTJXlVfgHZsglwBD/k6nj76ctsH1E3q4doGrukiLQd3sGQYu56r5+lo5r94l29A==", "dev": true, "funding": [ { @@ -11524,8 +11510,8 @@ } ], "dependencies": { - "escalade": "^3.1.1", - "picocolors": "^1.0.0" + "escalade": "^3.2.0", + "picocolors": "^1.1.0" }, "bin": { "update-browserslist-db": "cli.js" diff --git a/src/App.tsx b/src/App.tsx index 1e560cb..07ea067 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -260,7 +260,7 @@ export const getBaseApiReactSocket = (customApi?: string) => { return groupApiSocket; } }; -export const isMainWindow = window?.location?.href?.includes("?main=true"); +export const isMainWindow = true function App() { const [extState, setExtstate] = useState("not-authenticated"); const [desktopViewMode, setDesktopViewMode] = useState('home') @@ -287,7 +287,7 @@ function App() { const [walletToBeDownloadedPassword, setWalletToBeDownloadedPassword] = useState(""); const [isMain, setIsMain] = useState( - window?.location?.href?.includes("?main=true") + true ); const isMainRef = useRef(false); const [authenticatePassword, setAuthenticatePassword] = useState(""); @@ -495,7 +495,6 @@ function App() { for (const field of requiredFields) { if (!(field in pf)) throw new Error(field + " not found in JSON"); } - // storeWalletInfo(pf); setRawWallet(pf); // setExtstate("authenticated"); setExtstate("wallet-dropped"); @@ -529,26 +528,7 @@ function App() { }; }; - const storeWalletInfo = (wallet: any) => { - chrome?.runtime?.sendMessage( - { action: "storeWalletInfo", wallet }, - (response) => { - if (response) { - } - } - ); - - chrome.tabs.query( - { active: true, currentWindow: true }, - function (tabs: any[]) { - chrome.tabs.sendMessage( - tabs[0].id, - { from: "popup", subject: "anySubject" }, - function (response) {} - ); - } - ); - }; + const getBalanceFunc = () => { setQortBalanceLoading(true); @@ -755,126 +735,29 @@ function App() { //param = isDecline const confirmPayment = (isDecline: boolean) => { - if (isDecline) { - chrome?.runtime?.sendMessage( - { - action: "sendQortConfirmation", - payload: { - amount: sendqortState?.amount, - receiver: sendqortState?.address, - password: paymentPassword, - interactionId: sendqortState?.interactionId, - isDecline: true, - }, - }, - (response) => { - if (response) { - setSendPaymentSuccess("Payment successfully sent"); - } else { - window.close(); - } - } - ); - return; - } - - setIsLoading(true); - chrome?.runtime?.sendMessage( - { - action: "sendQortConfirmation", - payload: { - amount: sendqortState.amount, - receiver: sendqortState.address, - password: paymentPassword, - interactionId: sendqortState.interactionId, - isDecline: false, - }, - }, - (response) => { - if (response === true) { - setExtstate("transfer-success-request"); - setCountdown(null); - } else { - setSendPaymentError( - response?.error || "Unable to perform payment. Please try again." - ); - } - setIsLoading(false); - } - ); + // REMOVED FOR MOBILE APP }; const confirmBuyOrder = (isDecline: boolean) => { - if (isDecline) { - chrome?.runtime?.sendMessage( - { - action: "buyOrderConfirmation", - payload: { - crosschainAtInfo: requestBuyOrder?.crosschainAtInfo, - interactionId: requestBuyOrder?.interactionId, - isDecline: true, - useLocal: requestBuyOrder?.useLocal, - }, - }, - (response) => { - window.close(); - } - ); - return; - } + // REMOVED FOR MOBILE APP - setIsLoading(true); - chrome?.runtime?.sendMessage( - { - action: "buyOrderConfirmation", - payload: { - crosschainAtInfo: requestBuyOrder?.crosschainAtInfo, - interactionId: requestBuyOrder?.interactionId, - isDecline: false, - useLocal: requestBuyOrder?.useLocal, - }, - }, - (response) => { - if (response === true) { - setExtstate("buy-order-submitted"); - setCountdown(null); - } else { - setSendPaymentError( - response?.error || "Unable to perform payment. Please try again." - ); - } - setIsLoading(false); - } - ); }; const responseToConnectionRequest = ( isOkay: boolean, hostname: string, interactionId: string ) => { - chrome?.runtime?.sendMessage( - { - action: "responseToConnectionRequest", - payload: { isOkay, hostname, interactionId }, - }, - (response) => { - if (response === false || response === true) { - window.close(); - } - } - ); + // REMOVED FOR MOBILE APP }; - // const rawWalletRef = useRef(null) - - // useEffect(()=> { - // rawWalletRef.current = rawWallet - // }, [rawWallet]) useEffect(() => { try { setIsLoading(true); - chrome?.runtime?.sendMessage({ action: "getWalletInfo" }, (response) => { + + window.sendMessage("getWalletInfo") + .then((response) => { + console.log('getwalll', response) if (response && response?.walletInfo) { setRawWallet(response?.walletInfo); if ( @@ -886,6 +769,9 @@ function App() { setExtstate("authenticated"); } + }) + .catch((error) => { + console.error("Failed to get wallet info:", error); }); } catch (error) { } finally { @@ -1120,6 +1006,7 @@ function App() { wallet: rawWallet, }) .then((response) => { + console.log('response2', response) if (response && !response.error) { setAuthenticatePassword(""); setExtstate("authenticated"); diff --git a/src/ExtStates/NotAuthenticated.tsx b/src/ExtStates/NotAuthenticated.tsx index 81a44b8..5dff727 100644 --- a/src/ExtStates/NotAuthenticated.tsx +++ b/src/ExtStates/NotAuthenticated.tsx @@ -22,7 +22,9 @@ import { CustomizedSnackbars } from "../components/Snackbar/Snackbar"; import { set } from "lodash"; import { cleanUrl, isUsingLocal } from "../background"; -const manifestData = chrome?.runtime?.getManifest(); +const manifestData = { + version: '2.2.0' +} export const NotAuthenticated = ({ getRootProps, @@ -69,6 +71,7 @@ export const NotAuthenticated = ({ } }; + const checkIfUserHasLocalNode = useCallback(async () => { try { const url = `http://127.0.0.1:12391/admin/status`; diff --git a/src/background-cases.ts b/src/background-cases.ts index 9c2522d..5eb5daf 100644 --- a/src/background-cases.ts +++ b/src/background-cases.ts @@ -53,6 +53,7 @@ import { import { decryptGroupEncryption, encryptAndPublishSymmetricKeyGroupChat, publishGroupEncryptedResource, publishOnQDN } from "./backgroundFunctions/encryption"; import { PUBLIC_NOTIFICATION_CODE_FIRST_SECRET_KEY } from "./constants/codes"; import { encryptSingle } from "./qdn/encryption/group-encryption"; +import { getData, storeData } from "./utils/chromeStorage"; export function versionCase(request, event) { event.source.postMessage( @@ -70,15 +71,42 @@ export async function getWalletInfoCase(request, event) { try { const response = await getKeyPair(); - event.source.postMessage( - { - requestId: request.requestId, - action: "getWalletInfo", - payload: { walletInfo: response }, - type: "backgroundMessageResponse", - }, - event.origin - ); + try { + const walletInfo = await getData('walletInfo').catch((error)=> null) + if(walletInfo){ + event.source.postMessage( + { + requestId: request.requestId, + action: "getWalletInfo", + payload: { walletInfo }, + type: "backgroundMessageResponse", + }, + event.origin + ); + } else { + event.source.postMessage( + { + requestId: request.requestId, + action: "getWalletInfo", + error: "No wallet info found", + type: "backgroundMessageResponse", + }, + event.origin + ); + } + + } catch (error) { + event.source.postMessage( + { + requestId: request.requestId, + action: "getWalletInfo", + error: "No wallet info found", + type: "backgroundMessageResponse", + }, + event.origin + ); + } + } catch (error) { event.source.postMessage( { @@ -171,10 +199,12 @@ export async function userInfoCase(request, event) { } export async function decryptWalletCase(request, event) { - try { + try { + console.log('request', request) const { password, wallet } = request.payload; - const response = await decryptWallet(password, wallet, walletVersion); - + console.log({password, wallet}) + const response = await decryptWallet({password, wallet, walletVersion}); + console.log('response', response) event.source.postMessage( { requestId: request.requestId, @@ -841,10 +871,7 @@ export async function addTimestampEnterChatCase(request, event) { export async function setApiKeyCase(request, event) { try { const payload = request.payload; - chrome.storage.local.set({ apiKey: payload }, () => { - // sendResponse(true); - }); - + storeData('apiKey', payload) event.source.postMessage( { requestId: request.requestId, @@ -869,9 +896,7 @@ export async function setApiKeyCase(request, event) { export async function setCustomNodesCase(request, event) { try { const nodes = request.payload; - chrome.storage.local.set({ customNodes: nodes }, () => { - // sendResponse(true); - }); + storeData('customNodes', nodes) event.source.postMessage( { @@ -1346,8 +1371,9 @@ export async function publishGroupEncryptedResourceCase(request, event) { export async function decryptGroupEncryptionCase(request, event) { try { const { data} = request.payload; + console.log('data', data) const response = await decryptGroupEncryption({ data }); - + console.log('dataresponse', response) event.source.postMessage( { requestId: request.requestId, diff --git a/src/background.ts b/src/background.ts index 0c484b7..723af24 100644 --- a/src/background.ts +++ b/src/background.ts @@ -87,6 +87,7 @@ import { validApiCase, versionCase, } from "./background-cases"; +import { getData, removeKeysAndLogout, storeData } from "./utils/chromeStorage"; export function cleanUrl(url) { return url?.replace(/^(https?:\/\/)?(www\.)?/, ""); @@ -165,28 +166,16 @@ const checkDifference = (createdTimestamp) => { Date.now() - createdTimestamp < timeDifferenceForNotificationChatsBackground ); }; -export const getApiKeyFromStorage = async () => { - return new Promise((resolve, reject) => { - chrome.storage.local.get("apiKey", (result) => { - if (chrome.runtime.lastError) { - return reject(chrome.runtime.lastError); - } - resolve(result.apiKey || null); // Return null if apiKey isn't found - }); - }); +export const getApiKeyFromStorage = async (): Promise => { + return getData("apiKey").catch(() => null); }; -export const getCustomNodesFromStorage = async () => { - return new Promise((resolve, reject) => { - chrome.storage.local.get("customNodes", (result) => { - if (chrome.runtime.lastError) { - return reject(chrome.runtime.lastError); - } - resolve(result.customNodes || null); // Return null if apiKey isn't found - }); - }); + +export const getCustomNodesFromStorage = async (): Promise => { + return getData("customNodes").catch(() => null); }; + const getArbitraryEndpoint = async () => { const apiKey = await getApiKeyFromStorage(); // Retrieve apiKey asynchronously if (apiKey) { @@ -392,23 +381,20 @@ const handleNotificationDirect = async (directs) => { (newestLatestTimestamp && newestLatestTimestamp?.timestamp > oldestLatestTimestamp?.timestamp) ) { - const notificationId = - "chat_notification_" + - Date.now() + - "_type=direct" + - `_from=${newestLatestTimestamp.address}`; - chrome.notifications.create(notificationId, { - type: "basic", - iconUrl: "qort.png", // Add an appropriate icon for chat notifications - title: `New Direct message! ${ - newestLatestTimestamp?.name && `from ${newestLatestTimestamp.name}` - }`, - message: "You have received a new direct message", - priority: 2, // Use the maximum priority to ensure it's noticeable - // buttons: [ - // { title: 'Go to group' } - // ] - }); + // const notificationId = + // "chat_notification_" + + // Date.now() + + // "_type=direct" + + // `_from=${newestLatestTimestamp.address}`; + // chrome.notifications.create(notificationId, { + // type: "basic", + // iconUrl: "qort.png", // Add an appropriate icon for chat notifications + // title: `New Direct message! ${ + // newestLatestTimestamp?.name && `from ${newestLatestTimestamp.name}` + // }`, + // message: "You have received a new direct message", + // priority: 2, // Use the maximum priority to ensure it's noticeable + // }); if (!isMobile) { setTimeout(() => { chrome.notifications.clear(notificationId); @@ -442,16 +428,13 @@ const handleNotificationDirect = async (directs) => { }); const notificationId = "chat_notification_" + Date.now(); - chrome.notifications.create(notificationId, { - type: "basic", - iconUrl: "qort.png", // Add an appropriate icon for chat notifications - title: `New Direct message!`, - message: "You have received a new direct message", - priority: 2, // Use the maximum priority to ensure it's noticeable - // buttons: [ - // { title: 'Go to group' } - // ] - }); + // chrome.notifications.create(notificationId, { + // type: "basic", + // iconUrl: "qort.png", // Add an appropriate icon for chat notifications + // title: `New Direct message!`, + // message: "You have received a new direct message", + // priority: 2, // Use the maximum priority to ensure it's noticeable + // }); if (!isMobile) { setTimeout(() => { chrome.notifications.clear(notificationId); @@ -473,59 +456,58 @@ const handleNotificationDirect = async (directs) => { // ); } }; -async function getThreadActivity() { +async function getThreadActivity(): Promise { const wallet = await getSaveWallet(); const address = wallet.address0; const key = `threadactivity-${address}`; - const res = await chrome.storage.local.get([key]); - if (res?.[key]) { - const parsedData = JSON.parse(res[key]); - return parsedData; - } else { - return null; - } + + return getData(key).catch(() => null); } -export async function updateThreadActivity({ + +export function updateThreadActivity({ threadId, qortalName, groupId, thread, +}: { + threadId: string; + qortalName: string; + groupId: string; + thread: any; }) { - const wallet = await getSaveWallet(); - const address = wallet.address0; - const ONE_WEEK_IN_MS = 7 * 24 * 60 * 60 * 1000; // One week in milliseconds - let lastResetTime = 0; - // Retrieve the last reset timestamp from storage - const key = `threadactivity-${address}`; + getSaveWallet().then((wallet) => { + const address = wallet.address0; + const ONE_WEEK_IN_MS = 7 * 24 * 60 * 60 * 1000; // One week in milliseconds + const key = `threadactivity-${address}`; + const currentTime = Date.now(); - chrome.storage.local.get([key], (data) => { + // Retrieve the existing thread activity data + const storedData = localStorage.getItem(key); let threads; - if (!data[key] || Object.keys(data?.[key]?.length === 0)) { + if (!storedData) { + // Initialize structure if no data found threads = { createdThreads: [], mostVisitedThreads: [], recentThreads: [], + lastResetTime: 0, }; } else { - threads = JSON.parse(data[key]); - } - if (threads?.lastResetTime) { - lastResetTime = threads.lastResetTime; + threads = storedData } - const currentTime = Date.now(); + let lastResetTime = threads.lastResetTime || 0; // Check if a week has passed since the last reset - if (!lastResetTime || currentTime - lastResetTime > ONE_WEEK_IN_MS) { - // Reset the visit counts for all most visited threads + if (currentTime - lastResetTime > ONE_WEEK_IN_MS) { + // Reset visit counts and update the last reset time threads.mostVisitedThreads.forEach((thread) => (thread.visitCount = 0)); - lastResetTime = currentTime; // Update the last reset time - threads.lastResetTime = lastResetTime; + threads.lastResetTime = currentTime; } - // Update the recent threads list + // Update recent threads threads.recentThreads = threads.recentThreads.filter( (t) => t.threadId !== threadId ); @@ -535,21 +517,17 @@ export async function updateThreadActivity({ groupId, thread, visitCount: 1, - lastVisited: Date.now(), + lastVisited: currentTime, }); - - // Sort the recent threads by lastVisited time (descending) - threads.recentThreads.sort((a, b) => b.lastVisited - a.lastVisited); - // Limit the recent threads list to 2 items threads.recentThreads = threads.recentThreads.slice(0, 2); - // Update the most visited threads list + // Update most visited threads const existingThread = threads.mostVisitedThreads.find( (t) => t.threadId === threadId ); if (existingThread) { existingThread.visitCount += 1; - existingThread.lastVisited = Date.now(); // Update the last visited time as well + existingThread.lastVisited = currentTime; } else { threads.mostVisitedThreads.push({ threadId, @@ -557,23 +535,17 @@ export async function updateThreadActivity({ groupId, thread, visitCount: 1, - lastVisited: Date.now(), + lastVisited: currentTime, }); } - - // Sort the most visited threads by visitCount (descending) - threads.mostVisitedThreads.sort((a, b) => b.visitCount - a.visitCount); - // Limit the most visited threads list to 2 items threads.mostVisitedThreads = threads.mostVisitedThreads.slice(0, 2); - // Store the updated thread information and last reset time - // chrome.storage.local.set({ threads, lastResetTime }); - - const dataString = JSON.stringify(threads); - chrome.storage.local.set({ [`threadactivity-${address}`]: dataString }); + // Save the updated data to localStorage without blocking + localStorage.setItem(key, JSON.stringify(threads)); }); } + const handleNotification = async (groups) => { const wallet = await getSaveWallet(); const address = wallet.address0; @@ -650,16 +622,14 @@ const handleNotification = async (groups) => { "_type=group" + `_from=${newestLatestTimestamp.groupId}`; - chrome.notifications.create(notificationId, { - type: "basic", - iconUrl: "qort.png", // Add an appropriate icon for chat notifications - title: "New Group Message!", - message: `You have received a new message from ${newestLatestTimestamp?.groupName}`, - priority: 2, // Use the maximum priority to ensure it's noticeable - // buttons: [ - // { title: 'Go to group' } - // ] - }); + // chrome.notifications.create(notificationId, { + // type: "basic", + // iconUrl: "qort.png", // Add an appropriate icon for chat notifications + // title: "New Group Message!", + // message: `You have received a new message from ${newestLatestTimestamp?.groupName}`, + // priority: 2, // Use the maximum priority to ensure it's noticeable + + // }); if (!isMobile) { setTimeout(() => { chrome.notifications.clear(notificationId); @@ -694,16 +664,14 @@ const handleNotification = async (groups) => { }); const notificationId = "chat_notification_" + Date.now(); - chrome.notifications.create(notificationId, { - type: "basic", - iconUrl: "qort.png", // Add an appropriate icon for chat notifications - title: "New Group Message!", - message: "You have received a new message from one of your groups", - priority: 2, // Use the maximum priority to ensure it's noticeable - // buttons: [ - // { title: 'Go to group' } - // ] - }); + // chrome.notifications.create(notificationId, { + // type: "basic", + // iconUrl: "qort.png", // Add an appropriate icon for chat notifications + // title: "New Group Message!", + // message: "You have received a new message from one of your groups", + // priority: 2, // Use the maximum priority to ensure it's noticeable + + // }); if (!isMobile) { setTimeout(() => { chrome.notifications.clear(notificationId); @@ -831,9 +799,7 @@ export const checkThreads = async (bringBack) => { const wallet = await getSaveWallet(); const address = wallet.address0; - const dataString = JSON.stringify(updateThreadWithLastNotified); - chrome.storage.local.set({ [`threadactivity-${address}`]: dataString }); - + storeData(`threadactivity-${address}`, updateThreadWithLastNotified).catch(() => null); if (newAnnouncements.length > 0) { const notificationId = "chat_notification_" + @@ -843,16 +809,14 @@ export const checkThreads = async (bringBack) => { let isDisableNotifications = (await getUserSettings({ key: "disable-push-notifications" })) || false; if (!isDisableNotifications) { - chrome.notifications.create(notificationId, { - type: "basic", - iconUrl: "qort.png", // Add an appropriate icon for chat notifications - title: `New thread post!`, - message: `New post in ${newAnnouncements[0]?.thread?.threadData?.title}`, - priority: 2, // Use the maximum priority to ensure it's noticeable - // buttons: [ - // { title: 'Go to group' } - // ] - }); + // chrome.notifications.create(notificationId, { + // type: "basic", + // iconUrl: "qort.png", // Add an appropriate icon for chat notifications + // title: `New thread post!`, + // message: `New post in ${newAnnouncements[0]?.thread?.threadData?.title}`, + // priority: 2, // Use the maximum priority to ensure it's noticeable + + // }); if (!isMobile) { setTimeout(() => { chrome.notifications.clear(notificationId); @@ -946,16 +910,14 @@ export const checkNewMessages = async () => { "_type=group-announcement" + `_from=${newAnnouncements[0]?.groupId}`; - chrome.notifications.create(notificationId, { - type: "basic", - iconUrl: "qort.png", // Add an appropriate icon for chat notifications - title: `New group announcement!`, - message: `You have received a new announcement from ${newAnnouncements[0]?.groupName}`, - priority: 2, // Use the maximum priority to ensure it's noticeable - // buttons: [ - // { title: 'Go to group' } - // ] - }); + // chrome.notifications.create(notificationId, { + // type: "basic", + // iconUrl: "qort.png", // Add an appropriate icon for chat notifications + // title: `New group announcement!`, + // message: `You have received a new announcement from ${newAnnouncements[0]?.groupName}`, + // priority: 2, // Use the maximum priority to ensure it's noticeable + + // }); if (!isMobile) { setTimeout(() => { chrome.notifications.clear(notificationId); @@ -1050,23 +1012,24 @@ async function getAddressInfo(address) { } export async function getKeyPair() { - const res = await chrome.storage.local.get(["keyPair"]); - if (res?.keyPair) { - return res.keyPair; + const res = await getData("keyPair").catch(() => null); + if (res) { + return res; } else { throw new Error("Wallet not authenticated"); } } export async function getSaveWallet() { - const res = await chrome.storage.local.get(["walletInfo"]); - if (res?.walletInfo) { - return res.walletInfo; + const res = await getData("walletInfo").catch(() => null); + if (res) { + return res; } else { throw new Error("No wallet saved"); } } + export async function clearAllNotifications() { const notifications = await chrome.notifications.getAll(); for (const notificationId of Object.keys(notifications)) { @@ -1086,11 +1049,12 @@ export async function getUserInfo() { }; } -async function connection(hostname) { - const isConnected = chrome.storage.local.get([hostname]); +async function connection(hostname: string) { + const isConnected = await getData(hostname).catch(() => null); return isConnected; } + async function getTradeInfo(qortalAtAddress) { const response = await fetch( buyTradeNodeBaseUrl + "/crosschain/trade/" + qortalAtAddress @@ -1121,7 +1085,7 @@ export async function getLTCBalance() { const wallet = await getSaveWallet(); let _url = `${buyTradeNodeBaseUrl}/crosschain/ltc/walletbalance`; const keyPair = await getKeyPair(); - const parsedKeyPair = JSON.parse(keyPair); + const parsedKeyPair = keyPair let _body = parsedKeyPair.ltcPublicKey; const response = await fetch(_url, { method: "POST", @@ -1311,19 +1275,19 @@ export async function getDataPublishes(groupId, type) { const address = wallet.address0; return new Promise((resolve) => { - chrome.storage.local.get([`${address}-publishData`], (result) => { - if (chrome.runtime.lastError) { - console.error("Error retrieving data:", chrome.runtime.lastError); - resolve(null); // Return null in case of an error - return; - } + getData(`${address}-publishData`) + .then((storedData) => { + storedData = storedData || {}; // Initialize an empty object if no data + const groupData = storedData[groupId] || {}; // Get data by groupId + const typeData = groupData[type] || {}; // Get data by type - let storedData = result[`${address}-publishData`] || {}; // Get the stored data or initialize an empty object - let groupData = storedData[groupId] || {}; // Get data by groupId - let typeData = groupData[type] || {}; // Get data by type + resolve(typeData); // Resolve with the data inside the specific type + }) + .catch((error) => { + console.error("Error retrieving data:", error); + resolve(null); // Return null in case of an error + }); - resolve(typeData); // Resolve with the data inside the specific type - }); }); } @@ -1336,57 +1300,59 @@ export async function addDataPublishes(newData, groupId, type) { if (newData?.size > 50000) return false; return new Promise((res) => { - chrome.storage.local.get([`${address}-publishData`], (result) => { - let storedData = result[`${address}-publishData`] || {}; // Get existing data or initialize - let groupData = storedData[groupId] || {}; // Get or initialize group by groupId - let typeData = groupData[type] || {}; // Get or initialize the type within the group - + getData(`${address}-publishData`) + .then((storedData) => { + storedData = storedData || {}; // Initialize if no data found + let groupData = storedData[groupId] || {}; // Initialize group data if not found + let typeData = groupData[type] || {}; // Initialize type data if not found + let totalSize = 0; - - // Calculate the current size of all stored data + + // Calculate total size of all stored data Object.values(storedData).forEach((group) => { Object.values(group).forEach((type) => { Object.values(type).forEach((data) => { - totalSize += data.size; // Accumulate the sizes of actual data + totalSize += data.size; // Accumulate data sizes }); }); }); - - // Check if adding the new data exceeds 3MB + + // Check if adding new data exceeds 3MB limit if (totalSize + newData.size > MAX_STORAGE_SIZE) { - // Sort and remove older data within the group and type let dataEntries = Object.entries(typeData); dataEntries.sort((a, b) => a[1].timestampSaved - b[1].timestampSaved); - - // Remove old data until there's enough space - while ( - totalSize + newData.size > MAX_STORAGE_SIZE && - dataEntries.length > 0 - ) { + + // Remove oldest entries until there's enough space + while (totalSize + newData.size > MAX_STORAGE_SIZE && dataEntries.length > 0) { const removedEntry = dataEntries.shift(); totalSize -= removedEntry[1].size; - delete typeData[removedEntry[0]]; // Remove from the typeData + delete typeData[removedEntry[0]]; // Remove from typeData } } - - // Add or update the new data within the group and type + + // Add or update the new data if there's space if (totalSize + newData.size <= MAX_STORAGE_SIZE) { - typeData[`${nameIdentifier}`] = newData; // Add new data under name-identifier - groupData[type] = typeData; // Update type data within the group - storedData[groupId] = groupData; // Update group data within the stored data - - // Save the updated structure back to chrome.storage.local - chrome.storage.local.set( - { [`${address}-publishData`]: storedData }, - () => { - res(true); // Data successfully added - } - ); + typeData[`${nameIdentifier}`] = newData; + groupData[type] = typeData; + storedData[groupId] = groupData; + + // Save updated structure back to localStorage + storeData(`${address}-publishData`, storedData) + .then(() => res(true)) // Successfully added + .catch((error) => { + console.error("Error saving data:", error); + res(false); // Save failed + }); } else { console.error("Failed to add data, still exceeds storage limit."); res(false); // Failure due to storage limit } + }) + .catch((error) => { + console.error("Error retrieving data:", error); + res(false); // Failure due to retrieval error }); + }); } @@ -1396,18 +1362,17 @@ export async function getUserSettings({ key }) { const address = wallet.address0; return new Promise((resolve) => { - chrome.storage.local.get([`${address}-userSettings`], (result) => { - if (chrome.runtime.lastError) { - console.error("Error retrieving data:", chrome.runtime.lastError); - resolve(null); // Return null in case of an error - return; - } + getData(`${address}-userSettings`) + .then((storedData) => { + storedData = storedData || {}; // Initialize empty object if no data + const value = storedData[key] || null; // Get data by key - const storedData = result[`${address}-userSettings`] || {}; // Get the stored data or initialize an empty object - const value = storedData[key] || null; // Get data by key + resolve(value); // Resolve with the data for the specific key + }) + .catch((error) => { + resolve(null); // Return null in case of an error + }); - resolve(value); // Resolve with the data for the specific key - }); }); } @@ -1420,19 +1385,25 @@ export async function addUserSettings({ keyValue }) { // No need to check size here, unless value is a large object. For simple settings, size checks aren't necessary. return new Promise((res) => { - chrome.storage.local.get([`${address}-userSettings`], (result) => { - let storedData = result[`${address}-userSettings`] || {}; // Get existing data or initialize - - storedData[key] = value; // Update the key-value pair within the stored data - - // Save the updated structure back to chrome.storage.local - chrome.storage.local.set( - { [`${address}-userSettings`]: storedData }, - () => { - res(true); // Data successfully added - } - ); + getData(`${address}-userSettings`) + .then((storedData) => { + storedData = storedData || {}; // Initialize if no data found + + storedData[key] = value; // Update the key-value pair within stored data + + // Save updated structure back to localStorage + storeData(`${address}-userSettings`, storedData) + .then(() => res(true)) // Data successfully added + .catch((error) => { + console.error("Error saving data:", error); + res(false); // Save failed + }); + }) + .catch((error) => { + console.error("Error retrieving data:", error); + res(false); // Failure due to retrieval error }); + }); } @@ -1469,15 +1440,13 @@ export async function decryptWallet({ password, wallet, walletVersion }) { rvnPublicKey: wallet2._addresses[0].rvnWallet.derivedMasterPublicKey, rvnPrivateKey: wallet2._addresses[0].rvnWallet.derivedMasterPrivateKey, }; - const dataString = JSON.stringify(toSave); await new Promise((resolve, reject) => { - chrome.storage.local.set({ keyPair: dataString }, () => { - if (chrome.runtime.lastError) { - reject(new Error(chrome.runtime.lastError.message)); - } else { - resolve(true); - } + storeData("keyPair", toSave) + .then(() => resolve(true)) + .catch((error) => { + reject(new Error(error.message || "Error saving data")); }); + }); const newWallet = { ...wallet, @@ -1485,13 +1454,12 @@ export async function decryptWallet({ password, wallet, walletVersion }) { ltcAddress: ltcAddress, }; await new Promise((resolve, reject) => { - chrome.storage.local.set({ walletInfo: newWallet }, () => { - if (chrome.runtime.lastError) { - reject(new Error(chrome.runtime.lastError.message)); - } else { - resolve(true); - } - }); + storeData("walletInfo", newWallet) + .then(() => resolve(true)) + .catch((error) => { + reject(new Error(error.message || "Error saving data")); + }); + }); return true; @@ -1579,25 +1547,24 @@ export const computePow = async ({ chatBytes, path, difficulty }) => { const getStoredData = async (key) => { return new Promise((resolve, reject) => { - chrome.storage.local.get(key, (result) => { - if (chrome.runtime.lastError) { - return reject(chrome.runtime.lastError); - } - resolve(result[key]); - }); + getData(key) + .then((data) => resolve(data)) + .catch((error) => reject(error)); + }); }; export async function handleActiveGroupDataFromSocket({ groups, directs }) { try { - chrome.runtime.sendMessage({ + window.postMessage({ action: "SET_GROUPS", payload: groups, - }); - chrome.runtime.sendMessage({ + }, "*"); + window.postMessage({ action: "SET_DIRECTS", payload: directs, - }); + }, "*"); + groups = groups; directs = directs; const activeData = { @@ -1606,7 +1573,11 @@ export async function handleActiveGroupDataFromSocket({ groups, directs }) { }; // Save the active data to localStorage - chrome.storage.local.set({ "active-groups-directs": activeData }); + storeData("active-groups-directs", activeData) + .catch((error) => { + console.error("Error saving data:", error); + }); + try { handleNotification(groups); handleNotificationDirect(directs); @@ -1622,7 +1593,7 @@ async function sendChat({ qortAddress, recipientPublicKey, message }) { let reference = Base58.encode(_reference); const resKeyPair = await getKeyPair(); - const parsedData = JSON.parse(resKeyPair); + const parsedData = resKeyPair; const uint8PrivateKey = Base58.decode(parsedData.privateKey); const uint8PublicKey = Base58.decode(parsedData.publicKey); const keyPair = { @@ -1693,7 +1664,7 @@ export async function sendChatGroup({ let reference = Base58.encode(_reference); const resKeyPair = await getKeyPair(); - const parsedData = JSON.parse(resKeyPair); + const parsedData = resKeyPair; const uint8PrivateKey = Base58.decode(parsedData.privateKey); const uint8PublicKey = Base58.decode(parsedData.publicKey); const keyPair = { @@ -1767,7 +1738,7 @@ export async function sendChatDirect({ let reference = Base58.encode(_reference); const resKeyPair = await getKeyPair(); - const parsedData = JSON.parse(resKeyPair); + const parsedData = resKeyPair; const uint8PrivateKey = Base58.decode(parsedData.privateKey); const uint8PublicKey = Base58.decode(parsedData.publicKey); const keyPair = { @@ -1870,7 +1841,7 @@ export async function decryptDirectFunc({ messages, involvingAddress }) { let holdMessages = []; const resKeyPair = await getKeyPair(); - const parsedData = JSON.parse(resKeyPair); + const parsedData = resKeyPair; const uint8PrivateKey = Base58.decode(parsedData.privateKey); const uint8PublicKey = Base58.decode(parsedData.publicKey); const keyPair = { @@ -1900,7 +1871,7 @@ async function createBuyOrderTx({ crosschainAtInfo, useLocal }) { const address = wallet.address0; const resKeyPair = await getKeyPair(); - const parsedData = JSON.parse(resKeyPair); + const parsedData = resKeyPair; const message = { addresses: crosschainAtInfo.map((order) => order.qortalAtAddress), foreignKey: parsedData.ltcPrivateKey, @@ -1969,7 +1940,7 @@ async function createBuyOrderTx({ crosschainAtInfo, useLocal }) { const address = wallet.address0; const resKeyPair = await getKeyPair(); - const parsedData = JSON.parse(resKeyPair); + const parsedData = resKeyPair; const message = { addresses: crosschainAtInfo.map((order) => order.qortalAtAddress), foreignKey: parsedData.ltcPrivateKey, @@ -2075,7 +2046,7 @@ export async function leaveGroup({ groupId }) { const address = wallet.address0; const lastReference = await getLastRef(); const resKeyPair = await getKeyPair(); - const parsedData = JSON.parse(resKeyPair); + const parsedData = resKeyPair; const uint8PrivateKey = Base58.decode(parsedData.privateKey); const uint8PublicKey = Base58.decode(parsedData.publicKey); const keyPair = { @@ -2104,7 +2075,7 @@ export async function joinGroup({ groupId }) { const address = wallet.address0; const lastReference = await getLastRef(); const resKeyPair = await getKeyPair(); - const parsedData = JSON.parse(resKeyPair); + const parsedData = resKeyPair; const uint8PrivateKey = Base58.decode(parsedData.privateKey); const uint8PublicKey = Base58.decode(parsedData.publicKey); const keyPair = { @@ -2131,7 +2102,7 @@ export async function joinGroup({ groupId }) { export async function cancelInvitationToGroup({ groupId, qortalAddress }) { const lastReference = await getLastRef(); const resKeyPair = await getKeyPair(); - const parsedData = JSON.parse(resKeyPair); + const parsedData = resKeyPair; const uint8PrivateKey = Base58.decode(parsedData.privateKey); const uint8PublicKey = Base58.decode(parsedData.publicKey); const keyPair = { @@ -2158,7 +2129,7 @@ export async function cancelInvitationToGroup({ groupId, qortalAddress }) { export async function cancelBan({ groupId, qortalAddress }) { const lastReference = await getLastRef(); const resKeyPair = await getKeyPair(); - const parsedData = JSON.parse(resKeyPair); + const parsedData = resKeyPair; const uint8PrivateKey = Base58.decode(parsedData.privateKey); const uint8PublicKey = Base58.decode(parsedData.publicKey); const keyPair = { @@ -2184,7 +2155,7 @@ export async function cancelBan({ groupId, qortalAddress }) { export async function registerName({ name }) { const lastReference = await getLastRef(); const resKeyPair = await getKeyPair(); - const parsedData = JSON.parse(resKeyPair); + const parsedData = resKeyPair; const uint8PrivateKey = Base58.decode(parsedData.privateKey); const uint8PublicKey = Base58.decode(parsedData.publicKey); const keyPair = { @@ -2210,7 +2181,7 @@ export async function registerName({ name }) { export async function makeAdmin({ groupId, qortalAddress }) { const lastReference = await getLastRef(); const resKeyPair = await getKeyPair(); - const parsedData = JSON.parse(resKeyPair); + const parsedData = resKeyPair; const uint8PrivateKey = Base58.decode(parsedData.privateKey); const uint8PublicKey = Base58.decode(parsedData.publicKey); const keyPair = { @@ -2237,7 +2208,7 @@ export async function makeAdmin({ groupId, qortalAddress }) { export async function removeAdmin({ groupId, qortalAddress }) { const lastReference = await getLastRef(); const resKeyPair = await getKeyPair(); - const parsedData = JSON.parse(resKeyPair); + const parsedData = resKeyPair; const uint8PrivateKey = Base58.decode(parsedData.privateKey); const uint8PublicKey = Base58.decode(parsedData.publicKey); const keyPair = { @@ -2269,7 +2240,7 @@ export async function banFromGroup({ }) { const lastReference = await getLastRef(); const resKeyPair = await getKeyPair(); - const parsedData = JSON.parse(resKeyPair); + const parsedData = resKeyPair; const uint8PrivateKey = Base58.decode(parsedData.privateKey); const uint8PublicKey = Base58.decode(parsedData.publicKey); const keyPair = { @@ -2302,7 +2273,7 @@ export async function kickFromGroup({ }) { const lastReference = await getLastRef(); const resKeyPair = await getKeyPair(); - const parsedData = JSON.parse(resKeyPair); + const parsedData = resKeyPair; const uint8PrivateKey = Base58.decode(parsedData.privateKey); const uint8PublicKey = Base58.decode(parsedData.publicKey); const keyPair = { @@ -2341,7 +2312,7 @@ export async function createGroup({ const lastReference = await getLastRef(); const feeres = await getFee("CREATE_GROUP"); const resKeyPair = await getKeyPair(); - const parsedData = JSON.parse(resKeyPair); + const parsedData = resKeyPair; const uint8PrivateKey = Base58.decode(parsedData.privateKey); const uint8PublicKey = Base58.decode(parsedData.publicKey); const keyPair = { @@ -2374,7 +2345,7 @@ export async function inviteToGroup({ groupId, qortalAddress, inviteTime }) { const lastReference = await getLastRef(); const feeres = await getFee("GROUP_INVITE"); const resKeyPair = await getKeyPair(); - const parsedData = JSON.parse(resKeyPair); + const parsedData = resKeyPair; const uint8PrivateKey = Base58.decode(parsedData.privateKey); const uint8PublicKey = Base58.decode(parsedData.publicKey); const keyPair = { @@ -2410,7 +2381,7 @@ export async function sendCoin( let keyPair = ""; if (skipConfirmPassword) { const resKeyPair = await getKeyPair(); - const parsedData = JSON.parse(resKeyPair); + const parsedData = resKeyPair; const uint8PrivateKey = Base58.decode(parsedData.privateKey); const uint8PublicKey = Base58.decode(parsedData.publicKey); keyPair = { @@ -2500,7 +2471,7 @@ async function fetchMessagesForBuyOrders(apiCall, signature, senderPublicKey) { if (data && data.length > 0) { const encodedMessageObj = data[0]; const resKeyPair = await getKeyPair(); - const parsedData = JSON.parse(resKeyPair); + const parsedData = resKeyPair; const uint8PrivateKey = Base58.decode(parsedData.privateKey); const uint8PublicKey = Base58.decode(parsedData.publicKey); const keyPair = { @@ -2560,7 +2531,7 @@ async function listenForChatMessage({ const encodedMessageObj = await fetchMessages(apiCall); const resKeyPair = await getKeyPair(); - const parsedData = JSON.parse(resKeyPair); + const parsedData = resKeyPair; const uint8PrivateKey = Base58.decode(parsedData.privateKey); const uint8PublicKey = Base58.decode(parsedData.publicKey); const keyPair = { @@ -2661,15 +2632,13 @@ export function removeDuplicateWindow(popupUrl) { export async function setChatHeads(data) { const wallet = await getSaveWallet(); const address = wallet.address0; - const dataString = JSON.stringify(data); return await new Promise((resolve, reject) => { - chrome.storage.local.set({ [`chatheads-${address}`]: dataString }, () => { - if (chrome.runtime.lastError) { - reject(new Error(chrome.runtime.lastError.message)); - } else { - resolve(true); - } + storeData(`chatheads-${address}`, data) + .then(() => resolve(true)) + .catch((error) => { + reject(new Error(error.message || "Error saving data")); }); + }); } @@ -2682,11 +2651,12 @@ export async function getTempPublish() { const wallet = await getSaveWallet(); const address = wallet.address0; const key = `tempPublish-${address}`; - const res = await chrome.storage.local.get([key]); + const res = await getData(key).catch(() => null); + const SIX_MINUTES = 6 * 60 * 1000; // 6 minutes in milliseconds - if (res?.[key]) { - const parsedData = JSON.parse(res[key]); + if (res) { + const parsedData = res const currentTime = Date.now(); // Filter through each top-level key (e.g., "announcement") and then through its nested entries @@ -2703,8 +2673,7 @@ export async function getTempPublish() { ); if (JSON.stringify(filteredData) !== JSON.stringify(parsedData)) { - const dataString = JSON.stringify(filteredData); - await chrome.storage.local.set({ [key]: dataString }); + await storeData(key, filteredData); } return filteredData; } else { @@ -2727,34 +2696,27 @@ export async function saveTempPublish({ data, key }) { }, }; - const dataString = JSON.stringify(newTemp); return await new Promise((resolve, reject) => { - chrome.storage.local.set({ [`tempPublish-${address}`]: dataString }, () => { - if (chrome.runtime.lastError) { - reject(new Error(chrome.runtime.lastError.message)); - } else { - resolve(newTemp[key]); - } - }); + storeData(`tempPublish-${address}`, newTemp) + .then(() => resolve(newTemp[key])) + .catch((error) => { + reject(new Error(error.message || "Error saving data")); + }); + }); } async function setChatHeadsDirect(data) { const wallet = await getSaveWallet(); const address = wallet.address0; - const dataString = JSON.stringify(data); return await new Promise((resolve, reject) => { - chrome.storage.local.set( - { [`chatheads-direct-${address}`]: dataString }, - () => { - if (chrome.runtime.lastError) { - reject(new Error(chrome.runtime.lastError.message)); - } else { - resolve(true); - } - } - ); + storeData(`chatheads-direct-${address}`, data) + .then(() => resolve(true)) + .catch((error) => { + reject(new Error(error.message || "Error saving data")); + }); + }); } @@ -2762,9 +2724,9 @@ export async function getTimestampEnterChat() { const wallet = await getSaveWallet(); const address = wallet.address0; const key = `enter-chat-timestamp-${address}`; - const res = await chrome.storage.local.get([key]); - if (res?.[key]) { - const parsedData = JSON.parse(res[key]); + const res = await getData(key).catch(() => null); + if (res) { + const parsedData = res return parsedData; } else { return {}; @@ -2774,9 +2736,9 @@ export async function getTimestampGroupAnnouncement() { const wallet = await getSaveWallet(); const address = wallet.address0; const key = `group-announcement-${address}`; - const res = await chrome.storage.local.get([key]); - if (res?.[key]) { - const parsedData = JSON.parse(res[key]); + const res = await getData(key).catch(() => null); + if (res) { + const parsedData = res return parsedData; } else { return {}; @@ -2795,18 +2757,13 @@ export async function addTimestampGroupAnnouncement({ notification: timestamp, seentimestamp: seenTimestamp ? true : false, }; - const dataString = JSON.stringify(data); return await new Promise((resolve, reject) => { - chrome.storage.local.set( - { [`group-announcement-${address}`]: dataString }, - () => { - if (chrome.runtime.lastError) { - reject(new Error(chrome.runtime.lastError.message)); - } else { - resolve(true); - } - } - ); + storeData(`group-announcement-${address}`, data) + .then(() => resolve(true)) + .catch((error) => { + reject(new Error(error.message || "Error saving data")); + }); + }); } @@ -2814,9 +2771,9 @@ async function getGroupData() { const wallet = await getSaveWallet(); const address = wallet.address0; const key = `group-data-${address}`; - const res = await chrome.storage.local.get([key]); - if (res?.[key]) { - const parsedData = JSON.parse(res[key]); + const res = await getData(key).catch(() => null); + if (res) { + const parsedData = res return parsedData; } else { return {}; @@ -2826,9 +2783,9 @@ export async function getGroupDataSingle(groupId) { const wallet = await getSaveWallet(); const address = wallet.address0; const key = `group-data-${address}`; - const res = await chrome.storage.local.get([key]); - if (res?.[key]) { - const parsedData = JSON.parse(res[key]); + const res = await getData(key).catch(() => null); + if (res) { + const parsedData = res return parsedData[groupId] || null; } else { return null; @@ -2850,15 +2807,13 @@ export async function setGroupData({ secretKeyData, secretKeyResource, }; - const dataString = JSON.stringify(data); return await new Promise((resolve, reject) => { - chrome.storage.local.set({ [`group-data-${address}`]: dataString }, () => { - if (chrome.runtime.lastError) { - reject(new Error(chrome.runtime.lastError.message)); - } else { - resolve(true); - } - }); + storeData(`group-data-${address}`, data) + .then(() => resolve(true)) + .catch((error) => { + reject(new Error(error.message || "Error saving data")); + }); + }); } @@ -2867,18 +2822,13 @@ export async function addTimestampEnterChat({ groupId, timestamp }) { const address = wallet.address0; const data = await getTimestampEnterChat(); data[groupId] = timestamp; - const dataString = JSON.stringify(data); return await new Promise((resolve, reject) => { - chrome.storage.local.set( - { [`enter-chat-timestamp-${address}`]: dataString }, - () => { - if (chrome.runtime.lastError) { - reject(new Error(chrome.runtime.lastError.message)); - } else { - resolve(true); - } - } - ); + storeData(`enter-chat-timestamp-${address}`, data) + .then(() => resolve(true)) + .catch((error) => { + reject(new Error(error.message || "Error saving data")); + }); + }); } @@ -2903,9 +2853,9 @@ async function getChatHeads() { const wallet = await getSaveWallet(); const address = wallet.address0; const key = `chatheads-${address}`; - const res = await chrome.storage.local.get([key]); - if (res?.[key]) { - const parsedData = JSON.parse(res[key]); + const res = await getData(key).catch(() => null); + if (res) { + const parsedData = res return parsedData; } else { throw new Error("No Chatheads saved"); @@ -2916,9 +2866,9 @@ async function getChatHeadsDirect() { const wallet = await getSaveWallet(); const address = wallet.address0; const key = `chatheads-direct-${address}`; - const res = await chrome.storage.local.get([key]); - if (res?.[key]) { - const parsedData = JSON.parse(res[key]); + const res = await getData(key).catch(() => null); + if (res) { + const parsedData = res return parsedData; } else { throw new Error("No Chatheads saved"); @@ -2959,6 +2909,7 @@ function setupMessageListener() { userInfoCase(request, event); break; case "decryptWallet": + console.log('going through') decryptWalletCase(request, event); break; case "balance": @@ -3126,38 +3077,17 @@ function setupMessageListener() { const key1 = `tempPublish-${address}`; const key2 = `group-data-${address}`; const key3 = `${address}-publishData`; - chrome.storage.local.remove( - [ - "keyPair", - "walletInfo", - "active-groups-directs", - key1, - key2, - key3, - ], - () => { - if (chrome.runtime.lastError) { - // Handle error - console.error(chrome.runtime.lastError.message); - } else { - chrome.tabs.query({}, function (tabs) { - tabs.forEach((tab) => { - chrome.tabs.sendMessage(tab.id, { type: "LOGOUT" }); - }); - }); - // Data removed successfully - event.source.postMessage( - { - requestId: request.requestId, - action: "logout", - payload: true, - type: "backgroundMessageResponse", - }, - event.origin - ); - } - } - ); + const keysToRemove = [ + "keyPair", + "walletInfo", + "active-groups-directs", + key1, + key2, + key3, + ]; + + removeKeysAndLogout(keysToRemove, event, request); + }; logoutFunc(); } catch (error) {} @@ -3173,117 +3103,9 @@ function setupMessageListener() { setupMessageListener(); -// Function to save window position and size -const saveWindowBounds = (windowId) => { - chrome.windows.get(windowId, (window) => { - const { top, left, width, height } = window; - chrome.storage.local.set( - { - windowBounds: { top, left, width, height }, - }, - () => { - console.log("Window bounds saved:", { top, left, width, height }); - } - ); - }); -}; -// Function to restore window position and size -const restoreWindowBounds = (callback) => { - chrome.storage.local.get("windowBounds", (data) => { - if (data.windowBounds) { - callback(data.windowBounds); - } else { - callback(null); // No saved bounds, use default size/position - } - }); -}; -chrome.action?.onClicked?.addListener((tab) => { - const popupUrl = chrome.runtime.getURL("index.html?main=true"); - chrome.windows.getAll( - { populate: true, windowTypes: ["popup"] }, - (windows) => { - // Attempt to find an existing popup window that has a tab with the correct URL - const existingPopup = windows.find((w) => { - return ( - w.tabs && - w.tabs.some((tab) => tab.url && tab.url.startsWith(popupUrl)) - ); - }); - if (existingPopup) { - // If the popup exists but is minimized or not focused, focus it - if (isMobile) { - const correctTab = existingPopup.tabs.find( - (tab) => tab.url && tab.url.startsWith(popupUrl) - ); - if (correctTab) { - chrome.tabs.update(correctTab.id, { active: true }); - chrome.windows.update(existingPopup.id, { - focused: true, - state: "normal", - }); - } - } else { - chrome.windows.update(existingPopup.id, { - focused: true, - state: "normal", - }); - } - } else { - // No existing popup found, restore the saved bounds or create a new one - restoreWindowBounds((savedBounds) => { - chrome.system.display.getInfo((displays) => { - // Assuming the primary display is the first one (adjust logic as needed) - const primaryDisplay = displays[0]; - const screenWidth = primaryDisplay.bounds.width; - const screenHeight = primaryDisplay.bounds.height; - - // Create a new window that uses the saved bounds if available - chrome.windows.create( - { - url: chrome.runtime.getURL("index.html?main=true"), - type: "popup", - width: savedBounds ? savedBounds.width : screenWidth, - height: savedBounds ? savedBounds.height : screenHeight, - left: savedBounds ? savedBounds.left : 0, - top: savedBounds ? savedBounds.top : 0, - }, - (newWindow) => { - // Listen for changes in the window's size or position and save them - chrome.windows.onBoundsChanged.addListener((window) => { - if (window.id === newWindow.id) { - saveWindowBounds(newWindow.id); - } - }); - - // Save the final window bounds when the window is closed - chrome.windows.onRemoved.addListener((windowId) => { - if (windowId === newWindow.id) { - saveWindowBounds(windowId); // Save the position/size before it’s closed - } - }); - } - ); - }); - }); - } - - const interactionId = Date.now().toString(); // Simple example; consider a better unique ID - - setTimeout(() => { - chrome.runtime.sendMessage({ - action: "INITIATE_MAIN", - payload: {}, - }); - }, 500); - - // Store sendResponse callback with the interaction ID - pendingResponses.set(interactionId, sendResponse); - } - ); -}); const checkGroupList = async () => { try { @@ -3344,174 +3166,10 @@ const checkActiveChatsForNotifications = async () => { ); } catch (error) {} }; -chrome.notifications?.onClicked?.addListener((notificationId) => { - const popupUrl = chrome.runtime.getURL("index.html?main=true"); - const isDirect = notificationId.includes("_type=direct_"); - const isGroup = notificationId.includes("_type=group_"); - const isGroupAnnouncement = notificationId.includes( - "_type=group-announcement_" - ); - const isNewThreadPost = notificationId.includes("_type=thread-post_"); - - let isExisting = false; - chrome.windows.getAll( - { populate: true, windowTypes: ["popup"] }, - async (windows) => { - // Attempt to find an existing popup window that has a tab with the correct URL - const existingPopup = windows.find((w) => { - return ( - w.tabs && - w.tabs.some((tab) => tab.url && tab.url.startsWith(popupUrl)) - ); - }); - - if (existingPopup) { - // If the popup exists but is minimized or not focused, focus it - chrome.windows.update(existingPopup.id, { - focused: true, - state: "normal", - }); - isExisting = true; - } else { - // No existing popup found, restore saved bounds or create a new one - restoreWindowBounds((savedBounds) => { - chrome.system.display.getInfo((displays) => { - // Assuming the primary display is the first one (adjust logic as needed) - const primaryDisplay = displays[0]; - const screenWidth = primaryDisplay.bounds.width; - const screenHeight = primaryDisplay.bounds.height; - - // Create a new window that takes up the full screen or uses saved bounds - chrome.windows.create( - { - url: chrome.runtime.getURL("index.html?main=true"), - type: "popup", - width: savedBounds ? savedBounds.width : screenWidth, - height: savedBounds ? savedBounds.height : screenHeight, - left: savedBounds ? savedBounds.left : 0, - top: savedBounds ? savedBounds.top : 0, - }, - (newWindow) => { - // Listen for changes in the window's size or position and save them - chrome.windows.onBoundsChanged.addListener((window) => { - if (window.id === newWindow.id) { - saveWindowBounds(newWindow.id); - } - }); - - // Save the final window bounds when the window is closed - chrome.windows.onRemoved.addListener((windowId) => { - if (windowId === newWindow.id) { - saveWindowBounds(windowId); // Save the position/size before it’s closed - } - }); - } - ); - }); - }); - } - const activeData = (await getStoredData("active-groups-directs")) || { - groups: [], - directs: [], - }; - setTimeout( - () => { - chrome.runtime.sendMessage({ - action: "SET_GROUPS", - payload: activeData?.groups || [], - }); - chrome.runtime.sendMessage({ - action: "SET_DIRECTS", - payload: activeData?.directs || [], - }); - }, - isExisting ? 100 : 1000 - ); - const interactionId = Date.now().toString(); // Simple example; consider a better unique ID - - setTimeout( - () => { - chrome.runtime.sendMessage({ - action: "INITIATE_MAIN", - payload: {}, - }); - - // Handle different types of notifications - if (isDirect) { - const fromValue = notificationId.split("_from=")[1]; - chrome.runtime.sendMessage({ - action: "NOTIFICATION_OPEN_DIRECT", - payload: { from: fromValue }, - }); - } else if (isGroup) { - const fromValue = notificationId.split("_from=")[1]; - chrome.runtime.sendMessage({ - action: "NOTIFICATION_OPEN_GROUP", - payload: { from: fromValue }, - }); - } else if (isGroupAnnouncement) { - const fromValue = notificationId.split("_from=")[1]; - chrome.runtime.sendMessage({ - action: "NOTIFICATION_OPEN_ANNOUNCEMENT_GROUP", - payload: { from: fromValue }, - }); - } else if (isNewThreadPost) { - const dataValue = notificationId.split("_data=")[1]; - const dataParsed = JSON.parse(dataValue); - - chrome.runtime.sendMessage({ - action: "NOTIFICATION_OPEN_THREAD_NEW_POST", - payload: { data: dataParsed }, - }); - } - }, - isExisting ? 400 : 3000 - ); - - // Store sendResponse callback with the interaction ID - pendingResponses.set(interactionId, sendResponse); - } - ); -}); // Reconnect when service worker wakes up -chrome.runtime?.onStartup.addListener(() => { - console.log("Service worker started up, reconnecting WebSocket..."); -}); -chrome.runtime?.onInstalled.addListener((details) => { - if (details.reason === chrome.runtime.OnInstalledReason.INSTALL) { - console.log("Extension Installed"); - // Perform tasks that should only happen on extension installation - // Example: Initialize WebSocket, set default settings, etc. - } else if (details.reason === chrome.runtime.OnInstalledReason.UPDATE) { - console.log("Extension Updated"); - // Handle the update logic here (e.g., migrate settings) - } else if ( - details.reason === chrome.runtime.OnInstalledReason.CHROME_UPDATE - ) { - console.log("Chrome updated"); - // Optional: Handle Chrome-specific updates if necessary - } -}); -// Check if the alarm already exists before creating it -chrome.alarms?.get("checkForNotifications", (existingAlarm) => { - if (!existingAlarm) { - // If the alarm does not exist, create it - chrome.alarms.create("checkForNotifications", { periodInMinutes: 10 }); - } -}); -chrome.alarms?.onAlarm.addListener(async (alarm) => { - try { - if (alarm.name === "checkForNotifications") { - const wallet = await getSaveWallet(); - const address = wallet.address0; - if (!address) return; - checkActiveChatsForNotifications(); - checkNewMessages(); - checkThreads(); - } - } catch (error) {} -}); + + diff --git a/src/backgroundFunctions/encryption.ts b/src/backgroundFunctions/encryption.ts index a78f479..3511597 100644 --- a/src/backgroundFunctions/encryption.ts +++ b/src/backgroundFunctions/encryption.ts @@ -1,6 +1,7 @@ import { getBaseApi } from "../background"; import { createSymmetricKeyAndNonce, decryptGroupData, encryptDataGroup, objectToBase64 } from "../qdn/encryption/group-encryption"; import { publishData } from "../qdn/publish/pubish"; +import { getData } from "../utils/chromeStorage"; const apiEndpoints = [ "https://api.qortal.org", @@ -36,9 +37,10 @@ async function findUsableApi() { async function getSaveWallet() { - const res = await chrome.storage.local.get(["walletInfo"]); - if (res?.walletInfo) { - return res.walletInfo; + const res = await getData("walletInfo").catch(() => null); + + if (res) { + return res } else { throw new Error("No wallet saved"); } @@ -56,9 +58,9 @@ export async function getNameInfo() { } } async function getKeyPair() { - const res = await chrome.storage.local.get(["keyPair"]); - if (res?.keyPair) { - return res.keyPair; + const res = await getData("keyPair").catch(() => null); + if (res) { + return res } else { throw new Error("Wallet not authenticated"); } @@ -98,7 +100,7 @@ export const encryptAndPublishSymmetricKeyGroupChat = async ({groupId, previousD } const resKeyPair = await getKeyPair() - const parsedData = JSON.parse(resKeyPair) + const parsedData = resKeyPair const privateKey = parsedData.privateKey const userPublicKey = parsedData.publicKey const groupmemberPublicKeys = await getPublicKeys(groupId) @@ -219,7 +221,7 @@ export const decryptGroupEncryption = async ({data}: { }) => { try { const resKeyPair = await getKeyPair() - const parsedData = JSON.parse(resKeyPair) + const parsedData = resKeyPair const privateKey = parsedData.privateKey const encryptedData = decryptGroupData( data, diff --git a/src/components/Apps/AppRating.tsx b/src/components/Apps/AppRating.tsx index a498779..0ac5fa0 100644 --- a/src/components/Apps/AppRating.tsx +++ b/src/components/Apps/AppRating.tsx @@ -118,32 +118,32 @@ export const AppRating = ({ app, myName, ratingCountPosition = "right" }) => { const pollName = `app-library-${app.service}-rating-${app.name}`; const pollOptions = [`1, 2, 3, 4, 5, initialValue-${newValue}`]; await new Promise((res, rej) => { - chrome?.runtime?.sendMessage( - { - action: "CREATE_POLL", - type: "qortalRequest", - payload: { - pollName: pollName, - pollDescription: `Rating for ${app.service} ${app.name}`, - pollOptions: pollOptions, - pollOwnerAddress: myName, - }, + window.sendMessage("CREATE_POLL", { + payload: { + pollName: pollName, + pollDescription: `Rating for ${app.service} ${app.name}`, + pollOptions: pollOptions, + pollOwnerAddress: myName, }, - (response) => { - if (response.error) { - rej(response?.message); - return; - } else { - res(response); - setInfoSnack({ - type: "success", - message: - "Successfully rated. Please wait a couple minutes for the network to propogate the changes.", - }); - setOpenSnack(true); - } + }, 60000) + .then((response) => { + if (response.error) { + rej(response?.message); + return; + } else { + res(response); + setInfoSnack({ + type: "success", + message: + "Successfully rated. Please wait a couple minutes for the network to propogate the changes.", + }); + setOpenSnack(true); } - ); + }) + .catch((error) => { + console.error("Failed qortalRequest", error); + }); + }); } else { const pollName = `app-library-${app.service}-rating-${app.name}`; @@ -153,30 +153,30 @@ export const AppRating = ({ app, myName, ratingCountPosition = "right" }) => { if (isNaN(optionIndex) || optionIndex === -1) throw new Error("Cannot find rating option"); await new Promise((res, rej) => { - chrome?.runtime?.sendMessage( - { - action: "VOTE_ON_POLL", - type: "qortalRequest", - payload: { - pollName: pollName, - optionIndex, - }, + window.sendMessage("VOTE_ON_POLL", { + payload: { + pollName: pollName, + optionIndex, }, - (response) => { - if (response.error) { - rej(response?.message); - return; - } else { - res(response); - setInfoSnack({ - type: "success", - message: - "Successfully rated. Please wait a couple minutes for the network to propogate the changes.", - }); - setOpenSnack(true); - } + }, 60000) + .then((response) => { + if (response.error) { + rej(response?.message); + return; + } else { + res(response); + setInfoSnack({ + type: "success", + message: + "Successfully rated. Please wait a couple minutes for the network to propogate the changes.", + }); + setOpenSnack(true); } - ); + }) + .catch((error) => { + console.error("Failed qortalRequest", error); + }); + }); } } catch (error) { diff --git a/src/components/Apps/useQortalMessageListener.tsx b/src/components/Apps/useQortalMessageListener.tsx index bf99e31..228bff6 100644 --- a/src/components/Apps/useQortalMessageListener.tsx +++ b/src/components/Apps/useQortalMessageListener.tsx @@ -368,7 +368,8 @@ isDOMContentLoaded: false if (event?.data?.requestedHandler !== 'UI') return; const sendMessageToRuntime = (message, eventPort) => { - chrome?.runtime?.sendMessage(message, (response) => { + window.sendMessage(message.action, message, 60000, message.isFromExtension) + .then((response) => { if (response.error) { eventPort.postMessage({ result: null, @@ -380,7 +381,11 @@ isDOMContentLoaded: false error: null, }); } + }) + .catch((error) => { + console.error("Failed qortalRequest", error); }); + }; // Check if action is included in the predefined list of UI requests diff --git a/src/components/Group/Group.tsx b/src/components/Group/Group.tsx index d6f95da..9ac0de0 100644 --- a/src/components/Group/Group.tsx +++ b/src/components/Group/Group.tsx @@ -126,7 +126,7 @@ const timeDifferenceForNotificationChats = 900000; export const requestQueueMemberNames = new RequestQueueWithPromise(5); export const requestQueueAdminMemberNames = new RequestQueueWithPromise(5); -const audio = new Audio(chrome.runtime?.getURL("msg-not1.wav")); +// const audio = new Audio(chrome.runtime?.getURL("msg-not1.wav")); export const getGroupAdminsAddress = async (groupNumber: number) => { // const validApi = await findUsableApi(); @@ -203,6 +203,7 @@ export const decryptResource = async (data: string) => { data, }) .then((response) => { + console.log('decryptseroucs', response) if (!response?.error) { res(response); return; @@ -892,78 +893,89 @@ export const Group = ({ useEffect(() => { - // Listen for messages from the background script - chrome?.runtime?.onMessage.addListener((message, sender, sendResponse) => { - if (message.action === "SET_GROUPS") { + // Handler function for incoming messages + const messageHandler = (event) => { + const message = event.data; + + if (message?.action === "SET_GROUPS") { // Update the component state with the received 'sendqort' state setGroups(message.payload); - getLatestRegularChat(message.payload) + getLatestRegularChat(message.payload); setMemberGroups(message.payload); - + if (selectedGroupRef.current && groupSectionRef.current === "chat") { window.sendMessage("addTimestampEnterChat", { timestamp: Date.now(), groupId: selectedGroupRef.current.groupId, }).catch((error) => { - console.error("Failed to add timestamp:", error.message || "An error occurred"); - }); - + console.error("Failed to add timestamp:", error.message || "An error occurred"); + }); } + if (selectedDirectRef.current) { window.sendMessage("addTimestampEnterChat", { timestamp: Date.now(), groupId: selectedDirectRef.current.address, }).catch((error) => { - console.error("Failed to add timestamp:", error.message || "An error occurred"); - }); - + console.error("Failed to add timestamp:", error.message || "An error occurred"); + }); } + setTimeout(() => { getTimestampEnterChat(); }, 200); } - if (message.action === "SET_GROUP_ANNOUNCEMENTS") { + + if (message?.action === "SET_GROUP_ANNOUNCEMENTS") { // Update the component state with the received 'sendqort' state setGroupAnnouncements(message.payload); - - if ( - selectedGroupRef.current && - groupSectionRef.current === "announcement" - ) { + + if (selectedGroupRef.current && groupSectionRef.current === "announcement") { window.sendMessage("addGroupNotificationTimestamp", { timestamp: Date.now(), groupId: selectedGroupRef.current.groupId, }).catch((error) => { - console.error("Failed to add group notification timestamp:", error.message || "An error occurred"); - }); - + console.error("Failed to add group notification timestamp:", error.message || "An error occurred"); + }); + setTimeout(() => { getGroupAnnouncements(); }, 200); } } - if (message.action === "SET_DIRECTS") { + + if (message?.action === "SET_DIRECTS") { // Update the component state with the received 'sendqort' state setDirects(message.payload); - - - } else if (message.action === "PLAY_NOTIFICATION_SOUND") { - audio.play(); + } else if (message?.action === "PLAY_NOTIFICATION_SOUND") { + // audio.play(); } - }); + }; + + // Attach the event listener + window.addEventListener("message", messageHandler); + + // Clean up the event listener on component unmount + return () => { + window.removeEventListener("message", messageHandler); + }; }, []); + useEffect(() => { if ( !myAddress || hasInitializedWebsocket.current || - !window?.location?.href?.includes("?main=true") || !groups || groups?.length === 0 ) return; - chrome?.runtime?.sendMessage({ action: "setupGroupWebsocket" }); + window.sendMessage("setupGroupWebsocket", {}) + .catch((error) => { + console.error("Failed to setup group websocket:", error.message || "An error occurred"); + }); + hasInitializedWebsocket.current = true; }, [myAddress, groups]); diff --git a/src/components/Group/WebsocketActive.tsx b/src/components/Group/WebsocketActive.tsx index 0498ff2..ffadd4f 100644 --- a/src/components/Group/WebsocketActive.tsx +++ b/src/components/Group/WebsocketActive.tsx @@ -18,7 +18,7 @@ export const WebSocketActive = ({ myAddress, setIsLoadingGroups }) => { useEffect(() => { if (!myAddress) return; // Only proceed if myAddress is set - if (!window?.location?.href?.includes("?main=true")) return; + const pingHeads = () => { try { diff --git a/src/components/Save/Save.tsx b/src/components/Save/Save.tsx index 7d94ec0..1de00ba 100644 --- a/src/components/Save/Save.tsx +++ b/src/components/Save/Save.tsx @@ -1,97 +1,121 @@ -import React, { useContext, useEffect, useMemo, useState } from 'react' -import { useRecoilState, useSetRecoilState } from 'recoil'; -import isEqual from 'lodash/isEqual'; // Import deep comparison utility -import { canSaveSettingToQdnAtom, hasSettingsChangedAtom, oldPinnedAppsAtom, settingsLocalLastUpdatedAtom, settingsQDNLastUpdatedAtom, sortablePinnedAppsAtom } from '../../atoms/global'; -import { ButtonBase } from '@mui/material'; -import { objectToBase64 } from '../../qdn/encryption/group-encryption'; -import { MyContext } from '../../App'; -import { getFee } from '../../background'; -import { CustomizedSnackbars } from '../Snackbar/Snackbar'; -import { SaveIcon } from '../../assets/svgs/SaveIcon'; -import { IconWrapper } from '../Desktop/DesktopFooter'; -export const Save = ({isDesktop}) => { - const [pinnedApps, setPinnedApps] = useRecoilState(sortablePinnedAppsAtom); - const [settingsQdnLastUpdated, setSettingsQdnLastUpdated] = useRecoilState(settingsQDNLastUpdatedAtom); - const [settingsLocalLastUpdated] = useRecoilState(settingsLocalLastUpdatedAtom); - const setHasSettingsChangedAtom = useSetRecoilState(hasSettingsChangedAtom); +import React, { useContext, useEffect, useMemo, useState } from "react"; +import { useRecoilState, useSetRecoilState } from "recoil"; +import isEqual from "lodash/isEqual"; // Import deep comparison utility +import { + canSaveSettingToQdnAtom, + hasSettingsChangedAtom, + oldPinnedAppsAtom, + settingsLocalLastUpdatedAtom, + settingsQDNLastUpdatedAtom, + sortablePinnedAppsAtom, +} from "../../atoms/global"; +import { ButtonBase } from "@mui/material"; +import { objectToBase64 } from "../../qdn/encryption/group-encryption"; +import { MyContext } from "../../App"; +import { getFee } from "../../background"; +import { CustomizedSnackbars } from "../Snackbar/Snackbar"; +import { SaveIcon } from "../../assets/svgs/SaveIcon"; +import { IconWrapper } from "../Desktop/DesktopFooter"; +export const Save = ({ isDesktop }) => { + const [pinnedApps, setPinnedApps] = useRecoilState(sortablePinnedAppsAtom); + const [settingsQdnLastUpdated, setSettingsQdnLastUpdated] = useRecoilState( + settingsQDNLastUpdatedAtom + ); + const [settingsLocalLastUpdated] = useRecoilState( + settingsLocalLastUpdatedAtom + ); + const setHasSettingsChangedAtom = useSetRecoilState(hasSettingsChangedAtom); - const [canSave] = useRecoilState(canSaveSettingToQdnAtom); - const [openSnack, setOpenSnack] = useState(false); - const [isLoading, setIsLoading] = useState(false) + const [canSave] = useRecoilState(canSaveSettingToQdnAtom); + const [openSnack, setOpenSnack] = useState(false); + const [isLoading, setIsLoading] = useState(false); const [infoSnack, setInfoSnack] = useState(null); - const [oldPinnedApps, setOldPinnedApps] = useRecoilState(oldPinnedAppsAtom) + const [oldPinnedApps, setOldPinnedApps] = useRecoilState(oldPinnedAppsAtom); - const { show } = useContext(MyContext); + const { show } = useContext(MyContext); - const hasChanged = useMemo(()=> { - const newChanges = { - sortablePinnedApps: pinnedApps.map((item)=> { + const hasChanged = useMemo(() => { + const newChanges = { + sortablePinnedApps: pinnedApps.map((item) => { + return { + name: item?.name, + service: item?.service, + }; + }), + }; + const oldChanges = { + sortablePinnedApps: oldPinnedApps.map((item) => { + return { + name: item?.name, + service: item?.service, + }; + }), + }; + if (settingsQdnLastUpdated === -100) return false; + return ( + !isEqual(oldChanges, newChanges) && + settingsQdnLastUpdated < settingsLocalLastUpdated + ); + }, [ + oldPinnedApps, + pinnedApps, + settingsQdnLastUpdated, + settingsLocalLastUpdated, + ]); + + useEffect(() => { + setHasSettingsChangedAtom(hasChanged); + }, [hasChanged]); + + const saveToQdn = async () => { + try { + setIsLoading(true); + const data64 = await objectToBase64({ + sortablePinnedApps: pinnedApps.map((item) => { return { name: item?.name, - service: item?.service - } - }) - } - const oldChanges = { - sortablePinnedApps: oldPinnedApps.map((item)=> { - return { - name: item?.name, - service: item?.service - } - }) - } - if(settingsQdnLastUpdated === -100) return false - return !isEqual(oldChanges, newChanges) && settingsQdnLastUpdated < settingsLocalLastUpdated - }, [oldPinnedApps, pinnedApps, settingsQdnLastUpdated, settingsLocalLastUpdated]) - - useEffect(()=> { - setHasSettingsChangedAtom(hasChanged) - }, [hasChanged]) - - const saveToQdn = async ()=> { - try { - setIsLoading(true) - const data64 = await objectToBase64({ - sortablePinnedApps: pinnedApps.map((item)=> { - return { - name: item?.name, - service: item?.service - } - }) - }) - const encryptData = await new Promise((res, rej) => { - chrome?.runtime?.sendMessage( + service: item?.service, + }; + }), + }); + const encryptData = await new Promise((res, rej) => { + window + .sendMessage( + "ENCRYPT_DATA", { - action: "ENCRYPT_DATA", - type: "qortalRequest", payload: { - data64 + data64, }, }, - (response) => { - if (response.error) { - rej(response?.message); - return; - } else { - res(response); - - } + 60000 + ) + .then((response) => { + if (response.error) { + rej(response?.message); + return; + } else { + res(response); } - ); - }); - if(encryptData && !encryptData?.error){ - const fee = await getFee('ARBITRARY') + }) + .catch((error) => { + console.error("Failed qortalRequest", error); + }); + }); + if (encryptData && !encryptData?.error) { + const fee = await getFee("ARBITRARY"); - await show({ - message: "Would you like to publish your settings to QDN (encrypted) ?" , - publishFee: fee.fee + ' QORT' - }) - const response = await new Promise((res, rej) => { - window.sendMessage("publishOnQDN", { - data: encryptData, - identifier: "ext_saved_settings", - service: "DOCUMENT_PRIVATE", - }) + await show({ + message: + "Would you like to publish your settings to QDN (encrypted) ?", + publishFee: fee.fee + " QORT", + }); + const response = await new Promise((res, rej) => { + window + .sendMessage("publishOnQDN", { + data: encryptData, + identifier: "ext_saved_settings", + service: "DOCUMENT_PRIVATE", + }) .then((response) => { if (!response?.error) { res(response); @@ -102,51 +126,67 @@ export const Save = ({isDesktop}) => { .catch((error) => { rej(error.message || "An error occurred"); }); - - }); - if(response?.identifier){ - setOldPinnedApps(pinnedApps) - setSettingsQdnLastUpdated(Date.now()) - setInfoSnack({ - type: "success", - message: - "Sucessfully published to QDN", - }); - setOpenSnack(true); - } - } - } catch (error) { - setInfoSnack({ - type: "error", - message: - error?.message || "Unable to save to QDN", }); - setOpenSnack(true); - } finally { - setIsLoading(false) + if (response?.identifier) { + setOldPinnedApps(pinnedApps); + setSettingsQdnLastUpdated(Date.now()); + setInfoSnack({ + type: "success", + message: "Sucessfully published to QDN", + }); + setOpenSnack(true); + } } + } catch (error) { + setInfoSnack({ + type: "error", + message: error?.message || "Unable to save to QDN", + }); + setOpenSnack(true); + } finally { + setIsLoading(false); } + }; return ( <> - - {isDesktop ? ( + + {isDesktop ? ( - + color="rgba(250, 250, 250, 0.5)" + label="Save" + selected={false} + > + - ) : ( - - )} - + ) : ( + + )} - { setInfo={setInfoSnack} /> - - ) -} + ); +}; diff --git a/src/main.tsx b/src/main.tsx index c19eaec..0531491 100644 --- a/src/main.tsx +++ b/src/main.tsx @@ -46,7 +46,7 @@ export default theme; ReactDOM.createRoot(document.getElementById('root')!).render( - + <> @@ -55,5 +55,5 @@ ReactDOM.createRoot(document.getElementById('root')!).render( - , + , ) diff --git a/src/messaging/messagesToBackground.tsx b/src/messaging/messagesToBackground.tsx index 6d1a4d2..2f08433 100644 --- a/src/messaging/messagesToBackground.tsx +++ b/src/messaging/messagesToBackground.tsx @@ -20,21 +20,17 @@ window.addEventListener("message", (event) => { const { resolve, reject } = callbackMap.get(requestId); callbackMap.delete(requestId); // Remove callback after use - if (error) { - reject({ error, message }); - } else { - resolve({ payload }); - } + resolve(event.data) } }); -export const sendMessageBackground = (action, data = {}, timeout = 60000) => { +export const sendMessageBackground = (action, data = {}, timeout = 60000, isFromExtension) => { return new Promise((resolve, reject) => { const requestId = generateRequestId(); // Unique ID for each request callbackMap.set(requestId, { resolve, reject }); // Store both resolve and reject callbacks // Send the message with `backgroundMessage` type - window.postMessage({ type: "backgroundMessage", action, requestId, payload: data }, "*"); + window.postMessage({ type: "backgroundMessage", action, requestId, payload: data, isFromExtension }, "*"); // Set up a timeout to automatically reject if no response is received const timeoutId = setTimeout(() => { diff --git a/src/qdn/encryption/group-encryption.ts b/src/qdn/encryption/group-encryption.ts index 4f61dd8..f0bf5f1 100644 --- a/src/qdn/encryption/group-encryption.ts +++ b/src/qdn/encryption/group-encryption.ts @@ -330,6 +330,7 @@ export const decodeBase64ForUIChatMessages = (messages)=> { export function decryptGroupData(data64EncryptedData: string, privateKey: string) { + console.log({data64EncryptedData, privateKey}) const allCombined = base64ToUint8Array(data64EncryptedData) const str = "qortalGroupEncryptedData" const strEncoder = new TextEncoder() diff --git a/src/qdn/publish/pubish.ts b/src/qdn/publish/pubish.ts index a57fd1e..79bd6f2 100644 --- a/src/qdn/publish/pubish.ts +++ b/src/qdn/publish/pubish.ts @@ -5,6 +5,7 @@ import Base58 from "../../deps/Base58" import nacl from "../../deps/nacl-fast" import utils from "../../utils/utils" import { createEndpoint, getBaseApi } from "../../background"; +import { getData } from "../../utils/chromeStorage"; export async function reusableGet(endpoint){ const validApi = await getBaseApi(); @@ -34,9 +35,9 @@ export async function reusableGet(endpoint){ } async function getKeyPair() { - const res = await chrome.storage.local.get(["keyPair"]); - if (res?.keyPair) { - return res.keyPair; + const res = await getData("keyPair").catch(() => null); + if (res) { + return res } else { throw new Error("Wallet not authenticated"); } @@ -118,7 +119,7 @@ export const publishData = async ({ const resKeyPair = await getKeyPair() - const parsedData = JSON.parse(resKeyPair) + const parsedData = resKeyPair const uint8PrivateKey = Base58.decode(parsedData.privateKey); const uint8PublicKey = Base58.decode(parsedData.publicKey); const keyPair = { diff --git a/src/qortalRequests copy.ts b/src/qortalRequests copy.ts new file mode 100644 index 0000000..3174148 --- /dev/null +++ b/src/qortalRequests copy.ts @@ -0,0 +1,428 @@ +import { addForeignServer, addListItems, createPoll, decryptData, deleteListItems, deployAt, encryptData, getCrossChainServerInfo, getDaySummary, getForeignFee, getListItems, getServerConnectionHistory, getTxActivitySummary, getUserAccount, getUserWallet, getUserWalletInfo, getWalletBalance, joinGroup, publishMultipleQDNResources, publishQDNResource, removeForeignServer, saveFile, sendChatMessage, sendCoin, setCurrentForeignServer, updateForeignFee, voteOnPoll } from "./qortalRequests/get"; + + + +// Promisify chrome.storage.local.get +function getLocalStorage(key) { + return new Promise((resolve, reject) => { + chrome.storage.local.get([key], function (result) { + if (chrome.runtime.lastError) { + return reject(chrome.runtime.lastError); + } + resolve(result[key]); + }); + }); + } + + // Promisify chrome.storage.local.set + function setLocalStorage(data) { + return new Promise((resolve, reject) => { + chrome.storage.local.set(data, function () { + if (chrome.runtime.lastError) { + return reject(chrome.runtime.lastError); + } + resolve(); + }); + }); + } + + + export async function setPermission(key, value) { + try { + // Get the existing qortalRequestPermissions object + const qortalRequestPermissions = (await getLocalStorage('qortalRequestPermissions')) || {}; + + // Update the permission + qortalRequestPermissions[key] = value; + + // Save the updated object back to storage + await setLocalStorage({ qortalRequestPermissions }); + + console.log('Permission set for', key); + } catch (error) { + console.error('Error setting permission:', error); + } + } + + export async function getPermission(key) { + try { + // Get the qortalRequestPermissions object from storage + const qortalRequestPermissions = (await getLocalStorage('qortalRequestPermissions')) || {}; + + // Return the value for the given key, or null if it doesn't exist + return qortalRequestPermissions[key] || null; + } catch (error) { + console.error('Error getting permission:', error); + return null; + } + } + + + // TODO: GET_FRIENDS_LIST + // NOT SURE IF TO IMPLEMENT: LINK_TO_QDN_RESOURCE, QDN_RESOURCE_DISPLAYED, SET_TAB_NOTIFICATIONS + +chrome?.runtime?.onMessage.addListener((request, sender, sendResponse) => { + if (request) { + const isFromExtension = request?.isExtension + switch (request.action) { + case "GET_USER_ACCOUNT": { + getUserAccount() + .then((res) => { + sendResponse(res); + }) + .catch((error) => { + sendResponse({ error: "Unable to get user account" }); + }); + + break; + } + case "ENCRYPT_DATA": { + const data = request.payload; + + encryptData(data, sender) + .then((res) => { + sendResponse(res); + }) + .catch((error) => { + sendResponse({ error: error.message }); + }); + + break; + } + case "DECRYPT_DATA": { + const data = request.payload; + + decryptData(data) + .then((res) => { + sendResponse(res); + }) + .catch((error) => { + sendResponse({ error: error.message }); + }); + + break; + } + case "GET_LIST_ITEMS": { + const data = request.payload; + + getListItems(data, isFromExtension) + .then((res) => { + sendResponse(res); + }) + .catch((error) => { + sendResponse({ error: error.message }); + }); + + break; + } + case "ADD_LIST_ITEMS": { + const data = request.payload; + + addListItems(data, isFromExtension) + .then((res) => { + sendResponse(res); + }) + .catch((error) => { + sendResponse({ error: error.message }); + }); + + break; + } + case "DELETE_LIST_ITEM": { + const data = request.payload; + + deleteListItems(data, isFromExtension) + .then((res) => { + sendResponse(res); + }) + .catch((error) => { + sendResponse({ error: error.message }); + }); + + break; + } + case "PUBLISH_QDN_RESOURCE": { + const data = request.payload; + + publishQDNResource(data, sender, isFromExtension) + .then((res) => { + sendResponse(res); + }) + .catch((error) => { + sendResponse({ error: error.message }); + }); + + break; + } + case "PUBLISH_MULTIPLE_QDN_RESOURCES": { + const data = request.payload; + + publishMultipleQDNResources(data, sender, isFromExtension) + .then((res) => { + sendResponse(res); + }) + .catch((error) => { + sendResponse({ error: error.message }); + }); + + break; + } + case "VOTE_ON_POLL": { + const data = request.payload; + + voteOnPoll(data, isFromExtension) + .then((res) => { + sendResponse(res); + }) + .catch((error) => { + sendResponse({ error: error.message }); + }); + + break; + } + case "CREATE_POLL": { + const data = request.payload; + + createPoll(data, isFromExtension) + .then((res) => { + sendResponse(res); + }) + .catch((error) => { + sendResponse({ error: error.message }); + }); + + break; + } + case "SEND_CHAT_MESSAGE": { + const data = request.payload; + sendChatMessage(data, isFromExtension) + .then((res) => { + sendResponse(res); + }) + .catch((error) => { + sendResponse({ error: error.message }); + }); + + break; + } + case "JOIN_GROUP": { + const data = request.payload; + + joinGroup(data, isFromExtension) + .then((res) => { + sendResponse(res); + }) + .catch((error) => { + sendResponse({ error: error.message }); + }); + + break; + } + case "SAVE_FILE": { + const data = request.payload; + + saveFile(data, sender, isFromExtension) + .then((res) => { + sendResponse(res); + }) + .catch((error) => { + sendResponse({ error: error.message }); + }); + + break; + } + case "DEPLOY_AT": { + const data = request.payload; + + deployAt(data, isFromExtension) + .then((res) => { + sendResponse(res); + }) + .catch((error) => { + sendResponse({ error: error.message }); + }); + + break; + } + case "GET_USER_WALLET": { + const data = request.payload; + + getUserWallet(data, isFromExtension) + .then((res) => { + sendResponse(res); + }) + .catch((error) => { + sendResponse({ error: error.message }); + }); + + break; + } + case "GET_WALLET_BALANCE": { + const data = request.payload; + + getWalletBalance(data, false, isFromExtension) + .then((res) => { + sendResponse(res); + }) + .catch((error) => { + sendResponse({ error: error.message }); + }); + + break; + } + + case "GET_USER_WALLET_INFO": { + const data = request.payload; + + getUserWalletInfo(data, isFromExtension) + .then((res) => { + sendResponse(res); + }) + .catch((error) => { + sendResponse({ error: error.message }); + }); + + break; + } + case "GET_CROSSCHAIN_SERVER_INFO": { + const data = request.payload; + + getCrossChainServerInfo(data) + .then((res) => { + sendResponse(res); + }) + .catch((error) => { + sendResponse({ error: error.message }); + }); + + break; + } + case "GET_TX_ACTIVITY_SUMMARY": { + const data = request.payload; + + getTxActivitySummary(data) + .then((res) => { + sendResponse(res); + }) + .catch((error) => { + sendResponse({ error: error.message }); + }); + + break; + } + + case "GET_FOREIGN_FEE": { + const data = request.payload; + + getForeignFee(data) + .then((res) => { + sendResponse(res); + }) + .catch((error) => { + sendResponse({ error: error.message }); + }); + + break; + } + + case "UPDATE_FOREIGN_FEE": { + const data = request.payload; + + updateForeignFee(data) + .then((res) => { + sendResponse(res); + }) + .catch((error) => { + sendResponse({ error: error.message }); + }); + + break; + } + + case "GET_SERVER_CONNECTION_HISTORY": { + const data = request.payload; + + getServerConnectionHistory(data) + .then((res) => { + sendResponse(res); + }) + .catch((error) => { + sendResponse({ error: error.message }); + }); + + break; + } + + case "SET_CURRENT_FOREIGN_SERVER": { + const data = request.payload; + + setCurrentForeignServer(data) + .then((res) => { + sendResponse(res); + }) + .catch((error) => { + sendResponse({ error: error.message }); + }); + + break; + } + + case "ADD_FOREIGN_SERVER": { + const data = request.payload; + + addForeignServer(data) + .then((res) => { + sendResponse(res); + }) + .catch((error) => { + sendResponse({ error: error.message }); + }); + + break; + } + + case "REMOVE_FOREIGN_SERVER": { + const data = request.payload; + + removeForeignServer(data) + .then((res) => { + sendResponse(res); + }) + .catch((error) => { + sendResponse({ error: error.message }); + }); + + break; + } + + case "GET_DAY_SUMMARY": { + const data = request.payload; + + getDaySummary(data) + .then((res) => { + sendResponse(res); + }) + .catch((error) => { + sendResponse({ error: error.message }); + }); + + break; + } + + case "SEND_COIN": { + const data = request.payload; + + sendCoin(data, isFromExtension) + .then((res) => { + sendResponse(res); + }) + .catch((error) => { + sendResponse({ error: error.message }); + }); + + break; + } + } + } + return true; +}); diff --git a/src/qortalRequests.ts b/src/qortalRequests.ts index 3174148..c0b12af 100644 --- a/src/qortalRequests.ts +++ b/src/qortalRequests.ts @@ -1,30 +1,22 @@ import { addForeignServer, addListItems, createPoll, decryptData, deleteListItems, deployAt, encryptData, getCrossChainServerInfo, getDaySummary, getForeignFee, getListItems, getServerConnectionHistory, getTxActivitySummary, getUserAccount, getUserWallet, getUserWalletInfo, getWalletBalance, joinGroup, publishMultipleQDNResources, publishQDNResource, removeForeignServer, saveFile, sendChatMessage, sendCoin, setCurrentForeignServer, updateForeignFee, voteOnPoll } from "./qortalRequests/get"; +import { storeData } from "./utils/chromeStorage"; -// Promisify chrome.storage.local.get function getLocalStorage(key) { - return new Promise((resolve, reject) => { - chrome.storage.local.get([key], function (result) { - if (chrome.runtime.lastError) { - return reject(chrome.runtime.lastError); - } - resolve(result[key]); - }); - }); - } - - // Promisify chrome.storage.local.set - function setLocalStorage(data) { - return new Promise((resolve, reject) => { - chrome.storage.local.set(data, function () { - if (chrome.runtime.lastError) { - return reject(chrome.runtime.lastError); - } - resolve(); - }); - }); - } + return getData(key).catch((error) => { + console.error("Error retrieving data:", error); + throw error; + }); +} + +// Promisify setting data in localStorage +function setLocalStorage(key, data) { + return storeData(key, data).catch((error) => { + console.error("Error saving data:", error); + throw error; + }); +} export async function setPermission(key, value) { @@ -60,369 +52,565 @@ function getLocalStorage(key) { // TODO: GET_FRIENDS_LIST // NOT SURE IF TO IMPLEMENT: LINK_TO_QDN_RESOURCE, QDN_RESOURCE_DISPLAYED, SET_TAB_NOTIFICATIONS + + function setupMessageListener() { + window.addEventListener("message", async (event) => { + const request = event.data; + + // Ensure the message is from a trusted source + const isFromExtension = request?.isExtension; + if (request?.type !== "backgroundMessage") return; // Only process messages of type 'backgroundMessage' -chrome?.runtime?.onMessage.addListener((request, sender, sendResponse) => { - if (request) { - const isFromExtension = request?.isExtension - switch (request.action) { - case "GET_USER_ACCOUNT": { - getUserAccount() - .then((res) => { - sendResponse(res); - }) - .catch((error) => { - sendResponse({ error: "Unable to get user account" }); - }); - - break; + console.log("REQUEST MESSAGE QORTALREQUEST", request); + + // Handle actions based on the `request.action` value + switch (request.action) { + case "GET_USER_ACCOUNT": { + try { + const res = await getUserAccount(); + event.source.postMessage({ + requestId: request.requestId, + action: request.action, + payload: res, + type: "backgroundMessageResponse", + }, event.origin); + } catch (error) { + event.source.postMessage({ + requestId: request.requestId, + action: request.action, + error: "Unable to get user account", + type: "backgroundMessageResponse", + }, event.origin); + } + break; + } + + case "ENCRYPT_DATA": { + try { + const res = await encryptData(request.payload, event.source); + event.source.postMessage({ + requestId: request.requestId, + action: request.action, + payload: res, + type: "backgroundMessageResponse", + }, event.origin); + } catch (error) { + event.source.postMessage({ + requestId: request.requestId, + action: request.action, + error: error.message, + type: "backgroundMessageResponse", + }, event.origin); + } + break; + } + + case "DECRYPT_DATA": { + try { + const res = await decryptData(request.payload); + event.source.postMessage({ + requestId: request.requestId, + action: request.action, + payload: res, + type: "backgroundMessageResponse", + }, event.origin); + } catch (error) { + event.source.postMessage({ + requestId: request.requestId, + action: request.action, + error: error.message, + type: "backgroundMessageResponse", + }, event.origin); + } + break; + } + + case "GET_LIST_ITEMS": { + try { + const res = await getListItems(request.payload, isFromExtension); + event.source.postMessage({ + requestId: request.requestId, + action: request.action, + payload: res, + type: "backgroundMessageResponse", + }, event.origin); + } catch (error) { + event.source.postMessage({ + requestId: request.requestId, + action: request.action, + error: error.message, + type: "backgroundMessageResponse", + }, event.origin); + } + break; + } + + case "ADD_LIST_ITEMS": { + try { + const res = await addListItems(request.payload, isFromExtension); + event.source.postMessage({ + requestId: request.requestId, + action: request.action, + payload: res, + type: "backgroundMessageResponse", + }, event.origin); + } catch (error) { + event.source.postMessage({ + requestId: request.requestId, + action: request.action, + error: error.message, + type: "backgroundMessageResponse", + }, event.origin); + } + break; + } + + case "DELETE_LIST_ITEM": { + try { + const res = await deleteListItems(request.payload, isFromExtension); + event.source.postMessage({ + requestId: request.requestId, + action: request.action, + payload: res, + type: "backgroundMessageResponse", + }, event.origin); + } catch (error) { + event.source.postMessage({ + requestId: request.requestId, + action: request.action, + error: error.message, + type: "backgroundMessageResponse", + }, event.origin); + } + break; + } + + case "PUBLISH_QDN_RESOURCE": { + try { + const res = await publishQDNResource(request.payload, event.source, isFromExtension); + event.source.postMessage({ + requestId: request.requestId, + action: request.action, + payload: res, + type: "backgroundMessageResponse", + }, event.origin); + } catch (error) { + event.source.postMessage({ + requestId: request.requestId, + action: request.action, + error: error.message, + type: "backgroundMessageResponse", + }, event.origin); + } + break; + } + + case "PUBLISH_MULTIPLE_QDN_RESOURCES": { + try { + const res = await publishMultipleQDNResources(request.payload, event.source, isFromExtension); + event.source.postMessage({ + requestId: request.requestId, + action: request.action, + payload: res, + type: "backgroundMessageResponse", + }, event.origin); + } catch (error) { + event.source.postMessage({ + requestId: request.requestId, + action: request.action, + error: error.message, + type: "backgroundMessageResponse", + }, event.origin); + } + break; + } + + case "VOTE_ON_POLL": { + try { + const res = await voteOnPoll(request.payload, isFromExtension); + event.source.postMessage({ + requestId: request.requestId, + action: request.action, + payload: res, + type: "backgroundMessageResponse", + }, event.origin); + } catch (error) { + event.source.postMessage({ + requestId: request.requestId, + action: request.action, + error: error.message, + type: "backgroundMessageResponse", + }, event.origin); + } + break; + } + + case "CREATE_POLL": { + try { + const res = await createPoll(request.payload, isFromExtension); + event.source.postMessage({ + requestId: request.requestId, + action: request.action, + payload: res, + type: "backgroundMessageResponse", + }, event.origin); + } catch (error) { + event.source.postMessage({ + requestId: request.requestId, + action: request.action, + error: error.message, + type: "backgroundMessageResponse", + }, event.origin); + } + break; + } + + case "SEND_CHAT_MESSAGE": { + try { + const res = await sendChatMessage(request.payload, isFromExtension); + event.source.postMessage({ + requestId: request.requestId, + action: request.action, + payload: res, + type: "backgroundMessageResponse", + }, event.origin); + } catch (error) { + event.source.postMessage({ + requestId: request.requestId, + action: request.action, + error: error.message, + type: "backgroundMessageResponse", + }, event.origin); + } + break; + } + + case "JOIN_GROUP": { + try { + const res = await joinGroup(request.payload, isFromExtension); + event.source.postMessage({ + requestId: request.requestId, + action: request.action, + payload: res, + type: "backgroundMessageResponse", + }, event.origin); + } catch (error) { + event.source.postMessage({ + requestId: request.requestId, + action: request.action, + error: error.message, + type: "backgroundMessageResponse", + }, event.origin); + } + break; + } + + case "SAVE_FILE": { + try { + const res = await saveFile(request.payload, event.source, isFromExtension); + event.source.postMessage({ + requestId: request.requestId, + action: request.action, + payload: res, + type: "backgroundMessageResponse", + }, event.origin); + } catch (error) { + event.source.postMessage({ + requestId: request.requestId, + action: request.action, + error: error.message, + type: "backgroundMessageResponse", + }, event.origin); + } + break; + } + + case "DEPLOY_AT": { + try { + const res = await deployAt(request.payload, isFromExtension); + event.source.postMessage({ + requestId: request.requestId, + action: request.action, + payload: res, + type: "backgroundMessageResponse", + }, event.origin); + } catch (error) { + event.source.postMessage({ + requestId: request.requestId, + action: request.action, + error: error.message, + type: "backgroundMessageResponse", + }, event.origin); + } + break; + } + + case "GET_USER_WALLET": { + try { + const res = await getUserWallet(request.payload, isFromExtension); + event.source.postMessage({ + requestId: request.requestId, + action: request.action, + payload: res, + type: "backgroundMessageResponse", + }, event.origin); + } catch (error) { + event.source.postMessage({ + requestId: request.requestId, + action: request.action, + error: error.message, + type: "backgroundMessageResponse", + }, event.origin); + } + break; + } + + case "GET_WALLET_BALANCE": { + try { + const res = await getWalletBalance(request.payload, false, isFromExtension); + event.source.postMessage({ + requestId: request.requestId, + action: request.action, + payload: res, + type: "backgroundMessageResponse", + }, event.origin); + } catch (error) { + event.source.postMessage({ + requestId: request.requestId, + action: request.action, + error: error.message, + type: "backgroundMessageResponse", + }, event.origin); + } + break; + } + + case "GET_USER_WALLET_INFO": { + try { + const res = await getUserWalletInfo(request.payload, isFromExtension); + event.source.postMessage({ + requestId: request.requestId, + action: request.action, + payload: res, + type: "backgroundMessageResponse", + }, event.origin); + } catch (error) { + event.source.postMessage({ + requestId: request.requestId, + action: request.action, + error: error.message, + type: "backgroundMessageResponse", + }, event.origin); + } + break; + } + + case "GET_CROSSCHAIN_SERVER_INFO": { + try { + const res = await getCrossChainServerInfo(request.payload); + event.source.postMessage({ + requestId: request.requestId, + action: request.action, + payload: res, + type: "backgroundMessageResponse", + }, event.origin); + } catch (error) { + event.source.postMessage({ + requestId: request.requestId, + action: request.action, + error: error.message, + type: "backgroundMessageResponse", + }, event.origin); + } + break; + } + + case "GET_TX_ACTIVITY_SUMMARY": { + try { + const res = await getTxActivitySummary(request.payload); + event.source.postMessage({ + requestId: request.requestId, + action: request.action, + payload: res, + type: "backgroundMessageResponse", + }, event.origin); + } catch (error) { + event.source.postMessage({ + requestId: request.requestId, + action: request.action, + error: error.message, + type: "backgroundMessageResponse", + }, event.origin); + } + break; + } + + case "GET_FOREIGN_FEE": { + try { + const res = await getForeignFee(request.payload); + event.source.postMessage({ + requestId: request.requestId, + action: request.action, + payload: res, + type: "backgroundMessageResponse", + }, event.origin); + } catch (error) { + event.source.postMessage({ + requestId: request.requestId, + action: request.action, + error: error.message, + type: "backgroundMessageResponse", + }, event.origin); + } + break; + } + + case "UPDATE_FOREIGN_FEE": { + try { + const res = await updateForeignFee(request.payload); + event.source.postMessage({ + requestId: request.requestId, + action: request.action, + payload: res, + type: "backgroundMessageResponse", + }, event.origin); + } catch (error) { + event.source.postMessage({ + requestId: request.requestId, + action: request.action, + error: error.message, + type: "backgroundMessageResponse", + }, event.origin); + } + break; + } + + case "GET_SERVER_CONNECTION_HISTORY": { + try { + const res = await getServerConnectionHistory(request.payload); + event.source.postMessage({ + requestId: request.requestId, + action: request.action, + payload: res, + type: "backgroundMessageResponse", + }, event.origin); + } catch (error) { + event.source.postMessage({ + requestId: request.requestId, + action: request.action, + error: error.message, + type: "backgroundMessageResponse", + }, event.origin); + } + break; + } + + case "SET_CURRENT_FOREIGN_SERVER": { + try { + const res = await setCurrentForeignServer(request.payload); + event.source.postMessage({ + requestId: request.requestId, + action: request.action, + payload: res, + type: "backgroundMessageResponse", + }, event.origin); + } catch (error) { + event.source.postMessage({ + requestId: request.requestId, + action: request.action, + error: error.message, + type: "backgroundMessageResponse", + }, event.origin); + } + break; + } + + case "ADD_FOREIGN_SERVER": { + try { + const res = await addForeignServer(request.payload); + event.source.postMessage({ + requestId: request.requestId, + action: request.action, + payload: res, + type: "backgroundMessageResponse", + }, event.origin); + } catch (error) { + event.source.postMessage({ + requestId: request.requestId, + action: request.action, + error: error.message, + type: "backgroundMessageResponse", + }, event.origin); + } + break; + } + + case "REMOVE_FOREIGN_SERVER": { + try { + const res = await removeForeignServer(request.payload); + event.source.postMessage({ + requestId: request.requestId, + action: request.action, + payload: res, + type: "backgroundMessageResponse", + }, event.origin); + } catch (error) { + event.source.postMessage({ + requestId: request.requestId, + action: request.action, + error: error.message, + type: "backgroundMessageResponse", + }, event.origin); + } + break; + } + + case "GET_DAY_SUMMARY": { + try { + const res = await getDaySummary(request.payload); + event.source.postMessage({ + requestId: request.requestId, + action: request.action, + payload: res, + type: "backgroundMessageResponse", + }, event.origin); + } catch (error) { + event.source.postMessage({ + requestId: request.requestId, + action: request.action, + error: error.message, + type: "backgroundMessageResponse", + }, event.origin); + } + break; + } + + case "SEND_COIN": { + try { + const res = await sendCoin(request.payload, isFromExtension); + event.source.postMessage({ + requestId: request.requestId, + action: request.action, + payload: res, + type: "backgroundMessageResponse", + }, event.origin); + } catch (error) { + event.source.postMessage({ + requestId: request.requestId, + action: request.action, + error: error.message, + type: "backgroundMessageResponse", + }, event.origin); + } + break; + } + + default: + break; } - case "ENCRYPT_DATA": { - const data = request.payload; - - encryptData(data, sender) - .then((res) => { - sendResponse(res); - }) - .catch((error) => { - sendResponse({ error: error.message }); - }); - - break; - } - case "DECRYPT_DATA": { - const data = request.payload; - - decryptData(data) - .then((res) => { - sendResponse(res); - }) - .catch((error) => { - sendResponse({ error: error.message }); - }); - - break; - } - case "GET_LIST_ITEMS": { - const data = request.payload; - - getListItems(data, isFromExtension) - .then((res) => { - sendResponse(res); - }) - .catch((error) => { - sendResponse({ error: error.message }); - }); - - break; - } - case "ADD_LIST_ITEMS": { - const data = request.payload; - - addListItems(data, isFromExtension) - .then((res) => { - sendResponse(res); - }) - .catch((error) => { - sendResponse({ error: error.message }); - }); - - break; - } - case "DELETE_LIST_ITEM": { - const data = request.payload; - - deleteListItems(data, isFromExtension) - .then((res) => { - sendResponse(res); - }) - .catch((error) => { - sendResponse({ error: error.message }); - }); - - break; - } - case "PUBLISH_QDN_RESOURCE": { - const data = request.payload; - - publishQDNResource(data, sender, isFromExtension) - .then((res) => { - sendResponse(res); - }) - .catch((error) => { - sendResponse({ error: error.message }); - }); - - break; - } - case "PUBLISH_MULTIPLE_QDN_RESOURCES": { - const data = request.payload; - - publishMultipleQDNResources(data, sender, isFromExtension) - .then((res) => { - sendResponse(res); - }) - .catch((error) => { - sendResponse({ error: error.message }); - }); - - break; - } - case "VOTE_ON_POLL": { - const data = request.payload; - - voteOnPoll(data, isFromExtension) - .then((res) => { - sendResponse(res); - }) - .catch((error) => { - sendResponse({ error: error.message }); - }); - - break; - } - case "CREATE_POLL": { - const data = request.payload; - - createPoll(data, isFromExtension) - .then((res) => { - sendResponse(res); - }) - .catch((error) => { - sendResponse({ error: error.message }); - }); - - break; - } - case "SEND_CHAT_MESSAGE": { - const data = request.payload; - sendChatMessage(data, isFromExtension) - .then((res) => { - sendResponse(res); - }) - .catch((error) => { - sendResponse({ error: error.message }); - }); - - break; - } - case "JOIN_GROUP": { - const data = request.payload; - - joinGroup(data, isFromExtension) - .then((res) => { - sendResponse(res); - }) - .catch((error) => { - sendResponse({ error: error.message }); - }); - - break; - } - case "SAVE_FILE": { - const data = request.payload; - - saveFile(data, sender, isFromExtension) - .then((res) => { - sendResponse(res); - }) - .catch((error) => { - sendResponse({ error: error.message }); - }); - - break; - } - case "DEPLOY_AT": { - const data = request.payload; - - deployAt(data, isFromExtension) - .then((res) => { - sendResponse(res); - }) - .catch((error) => { - sendResponse({ error: error.message }); - }); - - break; - } - case "GET_USER_WALLET": { - const data = request.payload; - - getUserWallet(data, isFromExtension) - .then((res) => { - sendResponse(res); - }) - .catch((error) => { - sendResponse({ error: error.message }); - }); - - break; - } - case "GET_WALLET_BALANCE": { - const data = request.payload; - - getWalletBalance(data, false, isFromExtension) - .then((res) => { - sendResponse(res); - }) - .catch((error) => { - sendResponse({ error: error.message }); - }); - - break; - } - - case "GET_USER_WALLET_INFO": { - const data = request.payload; - - getUserWalletInfo(data, isFromExtension) - .then((res) => { - sendResponse(res); - }) - .catch((error) => { - sendResponse({ error: error.message }); - }); - - break; - } - case "GET_CROSSCHAIN_SERVER_INFO": { - const data = request.payload; - - getCrossChainServerInfo(data) - .then((res) => { - sendResponse(res); - }) - .catch((error) => { - sendResponse({ error: error.message }); - }); - - break; - } - case "GET_TX_ACTIVITY_SUMMARY": { - const data = request.payload; - - getTxActivitySummary(data) - .then((res) => { - sendResponse(res); - }) - .catch((error) => { - sendResponse({ error: error.message }); - }); - - break; - } - - case "GET_FOREIGN_FEE": { - const data = request.payload; - - getForeignFee(data) - .then((res) => { - sendResponse(res); - }) - .catch((error) => { - sendResponse({ error: error.message }); - }); - - break; - } - - case "UPDATE_FOREIGN_FEE": { - const data = request.payload; - - updateForeignFee(data) - .then((res) => { - sendResponse(res); - }) - .catch((error) => { - sendResponse({ error: error.message }); - }); - - break; - } - - case "GET_SERVER_CONNECTION_HISTORY": { - const data = request.payload; - - getServerConnectionHistory(data) - .then((res) => { - sendResponse(res); - }) - .catch((error) => { - sendResponse({ error: error.message }); - }); - - break; - } - - case "SET_CURRENT_FOREIGN_SERVER": { - const data = request.payload; - - setCurrentForeignServer(data) - .then((res) => { - sendResponse(res); - }) - .catch((error) => { - sendResponse({ error: error.message }); - }); - - break; - } - - case "ADD_FOREIGN_SERVER": { - const data = request.payload; - - addForeignServer(data) - .then((res) => { - sendResponse(res); - }) - .catch((error) => { - sendResponse({ error: error.message }); - }); - - break; - } - - case "REMOVE_FOREIGN_SERVER": { - const data = request.payload; - - removeForeignServer(data) - .then((res) => { - sendResponse(res); - }) - .catch((error) => { - sendResponse({ error: error.message }); - }); - - break; - } - - case "GET_DAY_SUMMARY": { - const data = request.payload; - - getDaySummary(data) - .then((res) => { - sendResponse(res); - }) - .catch((error) => { - sendResponse({ error: error.message }); - }); - - break; - } - - case "SEND_COIN": { - const data = request.payload; - - sendCoin(data, isFromExtension) - .then((res) => { - sendResponse(res); - }) - .catch((error) => { - sendResponse({ error: error.message }); - }); - - break; - } - } + }); } - return true; -}); + + // Initialize the message listener + setupMessageListener(); + diff --git a/src/qortalRequests/get.ts b/src/qortalRequests/get.ts index de91590..fa00e81 100644 --- a/src/qortalRequests/get.ts +++ b/src/qortalRequests/get.ts @@ -54,7 +54,7 @@ const _createPoll = async ({pollName, pollDescription, options}, isFromExtension const wallet = await getSaveWallet(); const address = wallet.address0; const resKeyPair = await getKeyPair(); - const parsedData = JSON.parse(resKeyPair); + const parsedData = resKeyPair; const uint8PrivateKey = Base58.decode(parsedData.privateKey); const uint8PublicKey = Base58.decode(parsedData.publicKey); const keyPair = { @@ -106,7 +106,7 @@ const _deployAt = async ( const address = wallet.address0; const lastReference = await getLastRef(); const resKeyPair = await getKeyPair(); - const parsedData = JSON.parse(resKeyPair); + const parsedData = resKeyPair; const uint8PrivateKey = Base58.decode(parsedData.privateKey); const uint8PublicKey = Base58.decode(parsedData.publicKey); const keyPair = { @@ -154,7 +154,7 @@ const _voteOnPoll = async ({pollName, optionIndex, optionName}, isFromExtension) const wallet = await getSaveWallet(); const address = wallet.address0; const resKeyPair = await getKeyPair(); - const parsedData = JSON.parse(resKeyPair); + const parsedData = resKeyPair; const uint8PrivateKey = Base58.decode(parsedData.privateKey); const uint8PublicKey = Base58.decode(parsedData.publicKey); const keyPair = { @@ -373,7 +373,7 @@ export const encryptData = async (data, sender) => { } const resKeyPair = await getKeyPair(); - const parsedData = JSON.parse(resKeyPair); + const parsedData = resKeyPair; const privateKey = parsedData.privateKey; const userPublicKey = parsedData.publicKey; @@ -396,7 +396,7 @@ export const decryptData = async (data) => { throw new Error(`Missing fields: encryptedData`); } const resKeyPair = await getKeyPair(); - const parsedData = JSON.parse(resKeyPair); + const parsedData = resKeyPair; const uint8PrivateKey = Base58.decode(parsedData.privateKey); const uint8Array = base64ToUint8Array(encryptedData); const startsWithQortalEncryptedData = uint8ArrayStartsWith( @@ -638,7 +638,7 @@ export const publishQDNResource = async (data: any, sender, isFromExtension) => if (data.encrypt) { try { const resKeyPair = await getKeyPair() - const parsedData = JSON.parse(resKeyPair) + const parsedData = resKeyPair const privateKey = parsedData.privateKey const userPublicKey = parsedData.publicKey const encryptDataResponse = encryptDataGroup({ @@ -858,7 +858,7 @@ export const publishMultipleQDNResources = async (data: any, sender, isFromExten if (data.encrypt) { try { const resKeyPair = await getKeyPair() - const parsedData = JSON.parse(resKeyPair) + const parsedData = resKeyPair const privateKey = parsedData.privateKey const userPublicKey = parsedData.publicKey const encryptDataResponse = encryptDataGroup({ @@ -1088,7 +1088,7 @@ export const sendChatMessage = async (data, isFromExtension) => { let reference = Base58.encode(_reference); const resKeyPair = await getKeyPair(); - const parsedData = JSON.parse(resKeyPair); + const parsedData = resKeyPair; const uint8PrivateKey = Base58.decode(parsedData.privateKey); const uint8PublicKey = Base58.decode(parsedData.publicKey); const keyPair = { @@ -1127,7 +1127,7 @@ export const sendChatMessage = async (data, isFromExtension) => { let reference = Base58.encode(_reference); const resKeyPair = await getKeyPair(); - const parsedData = JSON.parse(resKeyPair); + const parsedData = resKeyPair; const uint8PrivateKey = Base58.decode(parsedData.privateKey); const uint8PublicKey = Base58.decode(parsedData.publicKey); const keyPair = { @@ -1355,7 +1355,7 @@ export const getUserWallet = async (data, isFromExtension) => { const wallet = await getSaveWallet(); const address = wallet.address0; const resKeyPair = await getKeyPair(); - const parsedData = JSON.parse(resKeyPair); + const parsedData = resKeyPair; const arrrSeed58 = parsedData.arrrSeed58; if (coin === "ARRR") { const bodyToString = arrrSeed58; @@ -1448,7 +1448,7 @@ export const getWalletBalance = async (data, bypassPermission?: boolean, isFromE const wallet = await getSaveWallet(); const address = wallet.address0; const resKeyPair = await getKeyPair(); - const parsedData = JSON.parse(resKeyPair); + const parsedData = resKeyPair; if (coin === "QORT") { let qortAddress = address; try { @@ -1535,7 +1535,7 @@ const getUserWalletFunc = async (coin) => { const wallet = await getSaveWallet(); const address = wallet.address0; const resKeyPair = await getKeyPair(); - const parsedData = JSON.parse(resKeyPair); + const parsedData = resKeyPair; switch (coin) { case "QORT": userWallet["address"] = address; @@ -2068,7 +2068,7 @@ export const sendCoin = async (data, isFromExtension) => { const wallet = await getSaveWallet(); const address = wallet.address0; const resKeyPair = await getKeyPair(); - const parsedData = JSON.parse(resKeyPair); + const parsedData = resKeyPair; const localNodeAvailable = await isUsingLocal() if(checkCoin !== 'QORT' && !localNodeAvailable) throw new Error('Cannot send a non-QORT coin through the gateway. Please use your local node.') if (checkCoin === "QORT") { diff --git a/src/utils/chromeStorage.ts b/src/utils/chromeStorage.ts index ded57af..71c8863 100644 --- a/src/utils/chromeStorage.ts +++ b/src/utils/chromeStorage.ts @@ -1,28 +1,54 @@ -export const storeWalletInfo = (payload: any)=> { - return new Promise((resolve, reject) => { - chrome.storage.local.set({walletInfo: payload}, () => { - if (chrome.runtime.lastError) { - reject(new Error('Error saving data')); - } else { - resolve('Data saved successfully'); - } - }); - }); -} -export const getWalletInfo = (): Promise => { +export const storeData = (key: string, payload: any): Promise => { return new Promise((resolve, reject) => { - chrome.storage.local.get(['walletInfo'], (result) => { - if (chrome.runtime.lastError) { - reject(new Error('Error retrieving data')); - } else if (result.walletInfo) { - resolve(result.walletInfo as any); - } else { - reject(new Error('No wallet info found')); - } - }); + try { + localStorage.setItem(key, JSON.stringify(payload)); + resolve("Data saved successfully"); + } catch (error) { + reject(new Error("Error saving data")); + } }); -}; - + }; + + export const getData = (key: string): Promise => { + return new Promise((resolve, reject) => { + try { + const data = localStorage.getItem(key); + if (data) { + resolve(JSON.parse(data) as T); + } else { + reject(new Error(`No data found for key: ${key}`)); + } + } catch (error) { + reject(new Error("Error retrieving data")); + } + }); + }; + + export async function removeKeysAndLogout( + keys: string[], + event: MessageEvent, + request: any + ) { + try { + // Remove each key from localStorage + keys.forEach((key) => localStorage.removeItem(key)); + + + // Send a response back to indicate successful logout + event.source.postMessage( + { + requestId: request.requestId, + action: "logout", + payload: true, + type: "backgroundMessageResponse", + }, + event.origin + ); + } catch (error) { + console.error("Error removing keys:", error); + } + } +