@net-protocol/storage 0.1.8 → 0.1.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,19 +1,15 @@
1
1
  'use strict';
2
2
 
3
- var wagmi = require('wagmi');
4
- var react = require('react');
5
- var core = require('@net-protocol/core');
6
3
  var viem = require('viem');
7
- var pako = require('pako');
8
4
  var actions = require('viem/actions');
9
- var useAsyncEffect = require('use-async-effect');
5
+ var core = require('@net-protocol/core');
6
+ var pako = require('pako');
10
7
 
11
8
  function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
12
9
 
13
10
  var pako__default = /*#__PURE__*/_interopDefault(pako);
14
- var useAsyncEffect__default = /*#__PURE__*/_interopDefault(useAsyncEffect);
15
11
 
16
- // src/hooks/useStorage.ts
12
+ // src/client/StorageClient.ts
17
13
 
18
14
  // src/abis/storage.json
19
15
  var storage_default = [
@@ -598,6 +594,150 @@ var SAFE_STORAGE_READER_CONTRACT = {
598
594
  abi: safe_storage_reader_default,
599
595
  address: "0x0000000d03bad401fae4935dc9cbbf8084347214"
600
596
  };
597
+ function isBinaryString(str) {
598
+ return str.split("").some((char) => char.charCodeAt(0) > 127);
599
+ }
600
+ function formatStorageKeyForDisplay(storageKey) {
601
+ if (storageKey.startsWith("0x") && storageKey.length === 66 && /^0x[0-9a-fA-F]{64}$/.test(storageKey)) {
602
+ try {
603
+ const decoded = viem.fromHex(storageKey, "string");
604
+ const trimmed = decoded.replace(/\0/g, "");
605
+ if (!isBinaryString(trimmed) && trimmed.trim().length > 0) {
606
+ return {
607
+ displayText: trimmed,
608
+ isDecoded: true
609
+ };
610
+ }
611
+ } catch {
612
+ }
613
+ }
614
+ return {
615
+ displayText: storageKey,
616
+ isDecoded: false
617
+ };
618
+ }
619
+ function getStorageKeyBytes(input, keyFormat) {
620
+ if (keyFormat === "bytes32") {
621
+ return input.toLowerCase();
622
+ }
623
+ if (keyFormat === "raw") {
624
+ return input.length > 32 ? core.keccak256HashString(input.toLowerCase()) : core.toBytes32(input.toLowerCase());
625
+ }
626
+ if (input.startsWith("0x") && input.length === 66 && // 0x + 64 hex chars = bytes32
627
+ /^0x[0-9a-fA-F]{64}$/.test(input)) {
628
+ return input.toLowerCase();
629
+ }
630
+ return input.length > 32 ? core.keccak256HashString(input.toLowerCase()) : core.toBytes32(input.toLowerCase());
631
+ }
632
+ function encodeStorageKeyForUrl(key) {
633
+ return encodeURIComponent(key);
634
+ }
635
+ function generateStorageEmbedTag(params) {
636
+ const operator = params.operatorAddress.toLowerCase();
637
+ const indexAttr = params.versionIndex !== void 0 ? ` i="${params.versionIndex}"` : "";
638
+ const sourceAttr = params.isRegularStorage ? ` s="d"` : "";
639
+ return `<net k="${params.storageKeyBytes}" v="0.0.1"${indexAttr} o="${operator}"${sourceAttr} />`;
640
+ }
641
+
642
+ // src/client/storage.ts
643
+ function getStorageReadConfig(params) {
644
+ const { chainId, key, operator, keyFormat } = params;
645
+ const storageKeyBytes = getStorageKeyBytes(key, keyFormat);
646
+ return {
647
+ abi: STORAGE_CONTRACT.abi,
648
+ address: STORAGE_CONTRACT.address,
649
+ functionName: "get",
650
+ args: [storageKeyBytes, operator],
651
+ chainId
652
+ };
653
+ }
654
+ function getStorageValueAtIndexReadConfig(params) {
655
+ const { chainId, key, operator, index, keyFormat } = params;
656
+ const storageKeyBytes = getStorageKeyBytes(key, keyFormat);
657
+ return {
658
+ abi: STORAGE_CONTRACT.abi,
659
+ address: STORAGE_CONTRACT.address,
660
+ functionName: "getValueAtIndex",
661
+ args: [storageKeyBytes, operator, index],
662
+ chainId
663
+ };
664
+ }
665
+ function getStorageTotalWritesReadConfig(params) {
666
+ const { chainId, key, operator, keyFormat } = params;
667
+ const storageKeyBytes = getStorageKeyBytes(key, keyFormat);
668
+ return {
669
+ abi: STORAGE_CONTRACT.abi,
670
+ address: STORAGE_CONTRACT.address,
671
+ functionName: "getTotalWrites",
672
+ args: [storageKeyBytes, operator],
673
+ chainId
674
+ };
675
+ }
676
+ function getStorageBulkGetReadConfig(params) {
677
+ const { chainId, keys, safe = false, keyFormat } = params;
678
+ const contract = safe ? SAFE_STORAGE_READER_CONTRACT : STORAGE_CONTRACT;
679
+ const bulkKeys = keys.map((k) => ({
680
+ key: getStorageKeyBytes(k.key, k.keyFormat ?? keyFormat),
681
+ operator: k.operator
682
+ }));
683
+ return {
684
+ abi: contract.abi,
685
+ address: contract.address,
686
+ functionName: "bulkGet",
687
+ args: [bulkKeys],
688
+ chainId
689
+ };
690
+ }
691
+ function getStorageRouterReadConfig(params) {
692
+ const { chainId, key, operator, keyFormat } = params;
693
+ const storageKeyBytes = getStorageKeyBytes(key, keyFormat);
694
+ return {
695
+ abi: STORAGE_ROUTER_CONTRACT.abi,
696
+ address: STORAGE_ROUTER_CONTRACT.address,
697
+ functionName: "get",
698
+ args: [storageKeyBytes, operator],
699
+ chainId
700
+ };
701
+ }
702
+
703
+ // src/client/chunkedStorage.ts
704
+ function getChunkedStorageMetadataReadConfig(params) {
705
+ const { chainId, key, operator, index, keyFormat } = params;
706
+ const storageKeyBytes = getStorageKeyBytes(key, keyFormat);
707
+ const functionName = index !== void 0 ? "getMetadataAtIndex" : "getMetadata";
708
+ const args = index !== void 0 ? [storageKeyBytes, operator, index] : [storageKeyBytes, operator];
709
+ return {
710
+ abi: CHUNKED_STORAGE_READER_CONTRACT.abi,
711
+ address: CHUNKED_STORAGE_READER_CONTRACT.address,
712
+ functionName,
713
+ args,
714
+ chainId
715
+ };
716
+ }
717
+ function getChunkedStorageChunksReadConfig(params) {
718
+ const { chainId, key, operator, start, end, index, keyFormat } = params;
719
+ const storageKeyBytes = getStorageKeyBytes(key, keyFormat);
720
+ const functionName = index !== void 0 ? "getChunksAtIndex" : "getChunks";
721
+ const args = index !== void 0 ? [storageKeyBytes, operator, start, end, index] : [storageKeyBytes, operator, start, end];
722
+ return {
723
+ abi: CHUNKED_STORAGE_READER_CONTRACT.abi,
724
+ address: CHUNKED_STORAGE_READER_CONTRACT.address,
725
+ functionName,
726
+ args,
727
+ chainId
728
+ };
729
+ }
730
+ function getChunkedStorageTotalWritesReadConfig(params) {
731
+ const { chainId, key, operator, keyFormat } = params;
732
+ const storageKeyBytes = getStorageKeyBytes(key, keyFormat);
733
+ return {
734
+ abi: CHUNKED_STORAGE_READER_CONTRACT.abi,
735
+ address: CHUNKED_STORAGE_READER_CONTRACT.address,
736
+ functionName: "getTotalWrites",
737
+ args: [storageKeyBytes, operator],
738
+ chainId
739
+ };
740
+ }
601
741
 
602
742
  // src/utils/xmlUtils.ts
603
743
  function parseNetReferences(metadata) {
@@ -688,406 +828,6 @@ function assembleChunks(chunks, returnHex) {
688
828
  throw new Error("Failed to decompress chunked data");
689
829
  }
690
830
  }
691
- function isBinaryString(str) {
692
- return str.split("").some((char) => char.charCodeAt(0) > 127);
693
- }
694
- function formatStorageKeyForDisplay(storageKey) {
695
- if (storageKey.startsWith("0x") && storageKey.length === 66 && /^0x[0-9a-fA-F]{64}$/.test(storageKey)) {
696
- try {
697
- const decoded = viem.fromHex(storageKey, "string");
698
- const trimmed = decoded.replace(/\0/g, "");
699
- if (!isBinaryString(trimmed) && trimmed.trim().length > 0) {
700
- return {
701
- displayText: trimmed,
702
- isDecoded: true
703
- };
704
- }
705
- } catch {
706
- }
707
- }
708
- return {
709
- displayText: storageKey,
710
- isDecoded: false
711
- };
712
- }
713
- function getStorageKeyBytes(input, keyFormat) {
714
- if (keyFormat === "bytes32") {
715
- return input.toLowerCase();
716
- }
717
- if (keyFormat === "raw") {
718
- return input.length > 32 ? core.keccak256HashString(input.toLowerCase()) : core.toBytes32(input.toLowerCase());
719
- }
720
- if (input.startsWith("0x") && input.length === 66 && // 0x + 64 hex chars = bytes32
721
- /^0x[0-9a-fA-F]{64}$/.test(input)) {
722
- return input.toLowerCase();
723
- }
724
- return input.length > 32 ? core.keccak256HashString(input.toLowerCase()) : core.toBytes32(input.toLowerCase());
725
- }
726
- function encodeStorageKeyForUrl(key) {
727
- return encodeURIComponent(key);
728
- }
729
- function generateStorageEmbedTag(params) {
730
- const operator = params.operatorAddress.toLowerCase();
731
- const indexAttr = params.versionIndex !== void 0 ? ` i="${params.versionIndex}"` : "";
732
- const sourceAttr = params.isRegularStorage ? ` s="d"` : "";
733
- return `<net k="${params.storageKeyBytes}" v="0.0.1"${indexAttr} o="${operator}"${sourceAttr} />`;
734
- }
735
-
736
- // src/hooks/useStorage.ts
737
- var BATCH_SIZE = 2;
738
- function useStorage({
739
- chainId,
740
- key,
741
- operatorAddress,
742
- enabled = true,
743
- index,
744
- keyFormat,
745
- useRouter = false,
746
- outputFormat = "hex"
747
- }) {
748
- const isLatestVersion = index === void 0;
749
- const shouldUseRouter = useRouter === true && isLatestVersion;
750
- const outputAsString = outputFormat === "string";
751
- const storageKeyBytes = key ? getStorageKeyBytes(key, keyFormat) : void 0;
752
- const formatData = (text, dataHex) => {
753
- return {
754
- text,
755
- value: outputAsString ? viem.hexToString(dataHex) : dataHex
756
- };
757
- };
758
- const [routerData, setRouterData] = react.useState();
759
- const [routerChunkLoading, setRouterChunkLoading] = react.useState(false);
760
- const [routerChunkError, setRouterChunkError] = react.useState();
761
- const routerHook = wagmi.useReadContract({
762
- abi: STORAGE_ROUTER_CONTRACT.abi,
763
- address: STORAGE_ROUTER_CONTRACT.address,
764
- functionName: "get",
765
- args: storageKeyBytes && operatorAddress ? [storageKeyBytes, operatorAddress] : void 0,
766
- chainId,
767
- query: {
768
- enabled: shouldUseRouter && enabled && !!key && !!operatorAddress
769
- }
770
- });
771
- react.useEffect(() => {
772
- async function processRouterResult() {
773
- if (!routerHook.data || routerHook.isLoading || routerHook.error) {
774
- return;
775
- }
776
- const [isChunkedStorage, text, data] = routerHook.data;
777
- if (!isChunkedStorage) {
778
- if (!data || typeof data !== "string") {
779
- setRouterData(void 0);
780
- return;
781
- }
782
- const formatted = formatData(text, data);
783
- setRouterData(formatted);
784
- return;
785
- }
786
- setRouterChunkLoading(true);
787
- setRouterChunkError(void 0);
788
- try {
789
- const [chunkCount] = viem.decodeAbiParameters([{ type: "uint8" }], data);
790
- if (chunkCount === 0) {
791
- setRouterData(void 0);
792
- return;
793
- }
794
- const client = core.getPublicClient({ chainId });
795
- if (!client) {
796
- throw new Error(`Chain not found for chainId: ${chainId}`);
797
- }
798
- const allChunks = [];
799
- for (let start = 0; start < Number(chunkCount); start += BATCH_SIZE) {
800
- const end = Math.min(start + BATCH_SIZE, Number(chunkCount));
801
- const batch = await actions.readContract(client, {
802
- abi: CHUNKED_STORAGE_CONTRACT.abi,
803
- address: CHUNKED_STORAGE_CONTRACT.address,
804
- functionName: "getChunks",
805
- args: [storageKeyBytes, operatorAddress, start, end]
806
- });
807
- allChunks.push(...batch);
808
- }
809
- const assembledString = assembleChunks(allChunks);
810
- if (assembledString === void 0) {
811
- setRouterData(void 0);
812
- } else {
813
- if (outputAsString) {
814
- setRouterData({ text, value: assembledString });
815
- } else {
816
- const hexData = viem.stringToHex(assembledString);
817
- setRouterData({ text, value: hexData });
818
- }
819
- }
820
- } catch (error) {
821
- setRouterChunkError(error);
822
- } finally {
823
- setRouterChunkLoading(false);
824
- }
825
- }
826
- processRouterResult();
827
- }, [
828
- routerHook.data,
829
- routerHook.isLoading,
830
- routerHook.error,
831
- operatorAddress,
832
- chainId,
833
- storageKeyBytes,
834
- outputAsString
835
- ]);
836
- const {
837
- data: latestData,
838
- isLoading: latestLoading,
839
- error: latestError
840
- } = wagmi.useReadContract({
841
- abi: STORAGE_CONTRACT.abi,
842
- address: STORAGE_CONTRACT.address,
843
- functionName: "get",
844
- args: key && operatorAddress ? [getStorageKeyBytes(key, keyFormat), operatorAddress] : void 0,
845
- chainId,
846
- query: {
847
- enabled: !shouldUseRouter && enabled && !!operatorAddress && !!key && isLatestVersion
848
- }
849
- });
850
- const [historicalData, setHistoricalData] = react.useState(
851
- void 0
852
- );
853
- const [historicalLoading, setHistoricalLoading] = react.useState(false);
854
- const [historicalError, setHistoricalError] = react.useState();
855
- react.useEffect(() => {
856
- async function fetchHistoricalVersion() {
857
- if (isLatestVersion || !key || !operatorAddress || !enabled) {
858
- return;
859
- }
860
- setHistoricalLoading(true);
861
- setHistoricalError(void 0);
862
- setHistoricalData(void 0);
863
- try {
864
- const client = core.getPublicClient({ chainId });
865
- if (!client) {
866
- throw new Error(`Chain not found for chainId: ${chainId}`);
867
- }
868
- const storageKeyBytes2 = getStorageKeyBytes(
869
- key,
870
- keyFormat
871
- );
872
- try {
873
- const metadata = await actions.readContract(client, {
874
- abi: CHUNKED_STORAGE_READER_CONTRACT.abi,
875
- address: CHUNKED_STORAGE_READER_CONTRACT.address,
876
- functionName: "getMetadataAtIndex",
877
- args: [storageKeyBytes2, operatorAddress, index]
878
- });
879
- const [chunkCount, text2] = metadata;
880
- if (chunkCount > 0) {
881
- const chunks = await actions.readContract(client, {
882
- abi: CHUNKED_STORAGE_READER_CONTRACT.abi,
883
- address: CHUNKED_STORAGE_READER_CONTRACT.address,
884
- functionName: "getChunksAtIndex",
885
- args: [storageKeyBytes2, operatorAddress, 0, chunkCount, index]
886
- });
887
- const assembledData = assembleChunks(chunks);
888
- if (assembledData !== void 0) {
889
- const hexData = viem.stringToHex(assembledData);
890
- setHistoricalData(formatData(text2, hexData));
891
- setHistoricalLoading(false);
892
- return;
893
- }
894
- }
895
- } catch (chunkedError) {
896
- }
897
- const result = await actions.readContract(client, {
898
- abi: STORAGE_CONTRACT.abi,
899
- address: STORAGE_CONTRACT.address,
900
- functionName: "getValueAtIndex",
901
- args: [storageKeyBytes2, operatorAddress, index]
902
- });
903
- const [text, data] = result;
904
- if (!data || typeof data !== "string") {
905
- setHistoricalData(void 0);
906
- setHistoricalLoading(false);
907
- return;
908
- }
909
- setHistoricalData(formatData(text, data));
910
- } catch (error) {
911
- console.error(
912
- "[useStorage] Failed to fetch historical version:",
913
- error
914
- );
915
- setHistoricalError(error);
916
- } finally {
917
- setHistoricalLoading(false);
918
- }
919
- }
920
- fetchHistoricalVersion();
921
- }, [
922
- chainId,
923
- key,
924
- operatorAddress,
925
- index,
926
- enabled,
927
- isLatestVersion,
928
- outputAsString
929
- ]);
930
- if (!isLatestVersion) {
931
- return {
932
- data: historicalData,
933
- isLoading: historicalLoading,
934
- error: historicalError
935
- };
936
- }
937
- if (shouldUseRouter) {
938
- return {
939
- data: routerData,
940
- isLoading: routerHook.isLoading || routerChunkLoading,
941
- error: routerHook.error || routerChunkError
942
- };
943
- }
944
- const formattedDirectData = latestData ? (() => {
945
- const result = latestData;
946
- const [text, valueHex] = result;
947
- if (!valueHex || typeof valueHex !== "string") {
948
- return void 0;
949
- }
950
- return formatData(text, valueHex);
951
- })() : void 0;
952
- return {
953
- data: formattedDirectData,
954
- isLoading: latestLoading,
955
- error: latestError
956
- };
957
- }
958
- function useStorageForOperator({
959
- chainId,
960
- operatorAddress
961
- }) {
962
- const netContract = core.getNetContract(chainId);
963
- const { data: totalCount, isLoading: isLoadingCount } = wagmi.useReadContract({
964
- abi: netContract.abi,
965
- address: netContract.address,
966
- functionName: "getTotalMessagesForAppUserCount",
967
- args: [STORAGE_CONTRACT.address, operatorAddress],
968
- chainId
969
- });
970
- const totalCountNumber = totalCount ? Number(totalCount) : 0;
971
- const { data: messages, isLoading: isLoadingMessages } = wagmi.useReadContract({
972
- abi: netContract.abi,
973
- address: netContract.address,
974
- functionName: "getMessagesInRangeForAppUser",
975
- args: [0, totalCountNumber, STORAGE_CONTRACT.address, operatorAddress],
976
- chainId
977
- });
978
- return {
979
- data: messages?.map((msg) => [
980
- msg.topic,
981
- msg.text,
982
- Number(msg.timestamp),
983
- msg.data
984
- ]) || [],
985
- isLoading: isLoadingCount || isLoadingMessages,
986
- error: void 0
987
- };
988
- }
989
- function useStorageForOperatorAndKey({
990
- chainId,
991
- key,
992
- operatorAddress,
993
- keyFormat,
994
- outputFormat = "hex"
995
- }) {
996
- const storageKeyBytes = key ? getStorageKeyBytes(key, keyFormat) : void 0;
997
- const outputAsString = outputFormat === "string";
998
- const readContractArgs = {
999
- abi: STORAGE_CONTRACT.abi,
1000
- address: STORAGE_CONTRACT.address,
1001
- functionName: "getForOperatorAndKey",
1002
- args: storageKeyBytes ? [operatorAddress, storageKeyBytes] : void 0,
1003
- chainId,
1004
- query: {
1005
- enabled: !!key && !!operatorAddress
1006
- }
1007
- };
1008
- const { data, isLoading, error } = wagmi.useReadContract(readContractArgs);
1009
- return {
1010
- data: data ? (() => {
1011
- const [text, valueHex] = data;
1012
- return {
1013
- text,
1014
- value: outputAsString ? viem.hexToString(valueHex) : valueHex
1015
- };
1016
- })() : void 0,
1017
- isLoading,
1018
- error
1019
- };
1020
- }
1021
- function useBulkStorage({
1022
- chainId,
1023
- keys,
1024
- safe = false,
1025
- keyFormat
1026
- }) {
1027
- const contract = safe ? SAFE_STORAGE_READER_CONTRACT : STORAGE_CONTRACT;
1028
- const bulkKeys = keys.map((k) => ({
1029
- key: getStorageKeyBytes(k.key, keyFormat),
1030
- operator: k.operator
1031
- }));
1032
- const readContractArgs = {
1033
- abi: contract.abi,
1034
- address: contract.address,
1035
- functionName: "bulkGet",
1036
- args: [bulkKeys],
1037
- chainId
1038
- };
1039
- const { data, isLoading, error } = wagmi.useReadContract(readContractArgs);
1040
- return {
1041
- data,
1042
- isLoading,
1043
- error
1044
- };
1045
- }
1046
- function useStorageTotalWrites({
1047
- chainId,
1048
- key,
1049
- operatorAddress,
1050
- enabled = true,
1051
- keyFormat
1052
- }) {
1053
- const storageKeyBytes = key ? getStorageKeyBytes(key, keyFormat) : void 0;
1054
- const {
1055
- data: chunkedTotal,
1056
- isLoading: chunkedLoading,
1057
- error: chunkedError
1058
- } = wagmi.useReadContract({
1059
- abi: CHUNKED_STORAGE_READER_CONTRACT.abi,
1060
- address: CHUNKED_STORAGE_READER_CONTRACT.address,
1061
- functionName: "getTotalWrites",
1062
- args: storageKeyBytes && operatorAddress ? [storageKeyBytes, operatorAddress] : void 0,
1063
- chainId,
1064
- query: {
1065
- enabled: enabled && !!key && !!operatorAddress
1066
- }
1067
- });
1068
- const {
1069
- data: regularTotal,
1070
- isLoading: regularLoading,
1071
- error: regularError
1072
- } = wagmi.useReadContract({
1073
- abi: STORAGE_CONTRACT.abi,
1074
- address: STORAGE_CONTRACT.address,
1075
- functionName: "getTotalWrites",
1076
- args: storageKeyBytes && operatorAddress ? [storageKeyBytes, operatorAddress] : void 0,
1077
- chainId,
1078
- query: {
1079
- enabled: enabled && !!key && !!operatorAddress && (chunkedTotal === void 0 || Number(chunkedTotal) === 0)
1080
- }
1081
- });
1082
- const chunkedTotalNumber = chunkedTotal ? Number(chunkedTotal) : 0;
1083
- const regularTotalNumber = regularTotal ? Number(regularTotal) : 0;
1084
- const totalWrites = chunkedTotalNumber > 0 ? chunkedTotalNumber : regularTotalNumber;
1085
- return {
1086
- data: totalWrites > 0 ? totalWrites : void 0,
1087
- isLoading: chunkedLoading || regularLoading,
1088
- error: chunkedTotalNumber === 0 && regularTotalNumber === 0 ? chunkedError || regularError : void 0
1089
- };
1090
- }
1091
831
  var MAX_XML_DEPTH = 3;
1092
832
  var CONCURRENT_XML_FETCHES = 3;
1093
833
  function assembleXmlData(metadata, chunks, references) {
@@ -1233,308 +973,6 @@ async function resolveXmlRecursive(content, defaultOperator, client, maxDepth, v
1233
973
  const assembled = assembleXmlData(content, resolvedChunks, references);
1234
974
  return assembled;
1235
975
  }
1236
- function useXmlStorage({
1237
- chainId,
1238
- key,
1239
- operatorAddress,
1240
- skipXmlParsing = false,
1241
- enabled = true,
1242
- content,
1243
- index,
1244
- keyFormat,
1245
- useRouter,
1246
- outputFormat = "hex"
1247
- }) {
1248
- const isPreviewMode = !!content;
1249
- const outputAsString = outputFormat === "string";
1250
- const {
1251
- data: metadata,
1252
- isLoading: metadataLoading,
1253
- error: metadataError
1254
- } = useStorage({
1255
- chainId,
1256
- key: key || "",
1257
- operatorAddress,
1258
- enabled: enabled && !isPreviewMode,
1259
- index,
1260
- // Pass index to useStorage for historical versions
1261
- keyFormat,
1262
- // Pass keyFormat through
1263
- useRouter,
1264
- // Pass useRouter through to enable router path
1265
- outputFormat: "string"
1266
- // Always get plain string from useStorage, then convert based on our outputFormat
1267
- });
1268
- const metadataString = react.useMemo(() => {
1269
- if (skipXmlParsing) return "";
1270
- if (isPreviewMode) return content || "";
1271
- if (!metadata?.value) return "";
1272
- return metadata.value;
1273
- }, [skipXmlParsing, isPreviewMode, content, metadata]);
1274
- react.useMemo(() => {
1275
- if (!metadataString) return [];
1276
- return parseNetReferences(metadataString);
1277
- }, [metadataString]);
1278
- const [chunks, setChunks] = react.useState([]);
1279
- const [chunksLoading, setChunksLoading] = react.useState(false);
1280
- const [chunksError, setChunksError] = react.useState();
1281
- useAsyncEffect__default.default(async () => {
1282
- if (skipXmlParsing || !metadataString) {
1283
- setChunks([]);
1284
- setChunksLoading(false);
1285
- return;
1286
- }
1287
- if (!containsXmlReferences(metadataString)) {
1288
- setChunks([]);
1289
- setChunksLoading(false);
1290
- return;
1291
- }
1292
- setChunksLoading(true);
1293
- setChunksError(void 0);
1294
- try {
1295
- const client = core.getPublicClient({ chainId });
1296
- if (!client) {
1297
- throw new Error(`Chain not found for chainId: ${chainId}`);
1298
- }
1299
- const resolved = await resolveXmlRecursive(
1300
- metadataString,
1301
- operatorAddress,
1302
- client,
1303
- MAX_XML_DEPTH,
1304
- /* @__PURE__ */ new Set()
1305
- );
1306
- setChunks([resolved]);
1307
- } catch (error) {
1308
- console.error("[useXmlStorage] Error in recursive resolution:", error);
1309
- setChunksError(error);
1310
- setChunks([]);
1311
- } finally {
1312
- setChunksLoading(false);
1313
- }
1314
- }, [metadataString, operatorAddress, chainId, skipXmlParsing]);
1315
- const assembledData = react.useMemo(() => {
1316
- if (skipXmlParsing || !metadataString || !chunks.length) return void 0;
1317
- return chunks[0];
1318
- }, [metadataString, chunks, skipXmlParsing]);
1319
- const isXml = react.useMemo(() => {
1320
- if (skipXmlParsing || !metadataString) return false;
1321
- return containsXmlReferences(metadataString);
1322
- }, [metadataString, skipXmlParsing]);
1323
- const formatValue = (value) => {
1324
- if (!value) return "";
1325
- return outputAsString ? value : viem.stringToHex(value);
1326
- };
1327
- if (skipXmlParsing) {
1328
- return {
1329
- text: metadata?.text || "",
1330
- value: isPreviewMode ? content || "" : formatValue(metadata?.value),
1331
- isLoading: metadataLoading,
1332
- error: metadataError,
1333
- isXml: false
1334
- };
1335
- }
1336
- return {
1337
- text: metadata?.text || "",
1338
- value: isXml ? formatValue(assembledData) : isPreviewMode ? content || "" : formatValue(metadata?.value),
1339
- isLoading: metadataLoading || isXml && chunksLoading,
1340
- error: metadataError || chunksError,
1341
- isXml
1342
- };
1343
- }
1344
- var BATCH_SIZE2 = 2;
1345
- function useStorageFromRouter({
1346
- chainId,
1347
- storageKey,
1348
- operatorAddress,
1349
- enabled = true
1350
- }) {
1351
- const [assembledData, setAssembledData] = react.useState();
1352
- const [isChunkLoading, setIsChunkLoading] = react.useState(false);
1353
- const [chunkError, setChunkError] = react.useState();
1354
- const {
1355
- data: routerResult,
1356
- isLoading: routerLoading,
1357
- error: routerError
1358
- } = wagmi.useReadContract({
1359
- abi: STORAGE_ROUTER_CONTRACT.abi,
1360
- address: STORAGE_ROUTER_CONTRACT.address,
1361
- functionName: "get",
1362
- args: [storageKey, operatorAddress],
1363
- chainId,
1364
- query: {
1365
- enabled: enabled && !!operatorAddress
1366
- }
1367
- });
1368
- react.useEffect(() => {
1369
- async function processResult() {
1370
- if (!routerResult || routerLoading || routerError) {
1371
- return;
1372
- }
1373
- const [isChunkedStorage, text, data] = routerResult;
1374
- if (!isChunkedStorage) {
1375
- setAssembledData({ text, value: data });
1376
- return;
1377
- }
1378
- setIsChunkLoading(true);
1379
- setChunkError(void 0);
1380
- try {
1381
- const [chunkCount] = viem.decodeAbiParameters([{ type: "uint8" }], data);
1382
- if (chunkCount === 0) {
1383
- setAssembledData(void 0);
1384
- return;
1385
- }
1386
- const allChunks = await fetchChunksInBatches(
1387
- Number(chunkCount),
1388
- operatorAddress,
1389
- chainId,
1390
- storageKey
1391
- );
1392
- const assembledString = assembleChunks(allChunks);
1393
- if (assembledString === void 0) {
1394
- setAssembledData(void 0);
1395
- } else {
1396
- const hexData = viem.stringToHex(assembledString);
1397
- setAssembledData({ text, value: hexData });
1398
- }
1399
- } catch (error) {
1400
- setChunkError(error);
1401
- } finally {
1402
- setIsChunkLoading(false);
1403
- }
1404
- }
1405
- processResult();
1406
- }, [
1407
- routerResult,
1408
- routerLoading,
1409
- routerError,
1410
- operatorAddress,
1411
- chainId,
1412
- storageKey
1413
- ]);
1414
- return {
1415
- data: assembledData,
1416
- isLoading: routerLoading || isChunkLoading,
1417
- error: routerError || chunkError
1418
- };
1419
- }
1420
- async function fetchChunksInBatches(chunkCount, operatorAddress, chainId, storageKey) {
1421
- const client = core.getPublicClient({ chainId });
1422
- if (!client) {
1423
- throw new Error(`Chain not found for chainId: ${chainId}`);
1424
- }
1425
- const allChunks = [];
1426
- for (let start = 0; start < chunkCount; start += BATCH_SIZE2) {
1427
- const end = Math.min(start + BATCH_SIZE2, chunkCount);
1428
- const batch = await actions.readContract(client, {
1429
- abi: CHUNKED_STORAGE_CONTRACT.abi,
1430
- address: CHUNKED_STORAGE_CONTRACT.address,
1431
- functionName: "getChunks",
1432
- args: [storageKey, operatorAddress, start, end]
1433
- });
1434
- allChunks.push(...batch);
1435
- }
1436
- return allChunks;
1437
- }
1438
-
1439
- // src/client/storage.ts
1440
- function getStorageReadConfig(params) {
1441
- const { chainId, key, operator, keyFormat } = params;
1442
- const storageKeyBytes = getStorageKeyBytes(key, keyFormat);
1443
- return {
1444
- abi: STORAGE_CONTRACT.abi,
1445
- address: STORAGE_CONTRACT.address,
1446
- functionName: "get",
1447
- args: [storageKeyBytes, operator],
1448
- chainId
1449
- };
1450
- }
1451
- function getStorageValueAtIndexReadConfig(params) {
1452
- const { chainId, key, operator, index, keyFormat } = params;
1453
- const storageKeyBytes = getStorageKeyBytes(key, keyFormat);
1454
- return {
1455
- abi: STORAGE_CONTRACT.abi,
1456
- address: STORAGE_CONTRACT.address,
1457
- functionName: "getValueAtIndex",
1458
- args: [storageKeyBytes, operator, index],
1459
- chainId
1460
- };
1461
- }
1462
- function getStorageTotalWritesReadConfig(params) {
1463
- const { chainId, key, operator, keyFormat } = params;
1464
- const storageKeyBytes = getStorageKeyBytes(key, keyFormat);
1465
- return {
1466
- abi: STORAGE_CONTRACT.abi,
1467
- address: STORAGE_CONTRACT.address,
1468
- functionName: "getTotalWrites",
1469
- args: [storageKeyBytes, operator],
1470
- chainId
1471
- };
1472
- }
1473
- function getStorageBulkGetReadConfig(params) {
1474
- const { chainId, keys, safe = false, keyFormat } = params;
1475
- const contract = safe ? SAFE_STORAGE_READER_CONTRACT : STORAGE_CONTRACT;
1476
- const bulkKeys = keys.map((k) => ({
1477
- key: getStorageKeyBytes(k.key, k.keyFormat ?? keyFormat),
1478
- operator: k.operator
1479
- }));
1480
- return {
1481
- abi: contract.abi,
1482
- address: contract.address,
1483
- functionName: "bulkGet",
1484
- args: [bulkKeys],
1485
- chainId
1486
- };
1487
- }
1488
- function getStorageRouterReadConfig(params) {
1489
- const { chainId, key, operator, keyFormat } = params;
1490
- const storageKeyBytes = getStorageKeyBytes(key, keyFormat);
1491
- return {
1492
- abi: STORAGE_ROUTER_CONTRACT.abi,
1493
- address: STORAGE_ROUTER_CONTRACT.address,
1494
- functionName: "get",
1495
- args: [storageKeyBytes, operator],
1496
- chainId
1497
- };
1498
- }
1499
-
1500
- // src/client/chunkedStorage.ts
1501
- function getChunkedStorageMetadataReadConfig(params) {
1502
- const { chainId, key, operator, index, keyFormat } = params;
1503
- const storageKeyBytes = getStorageKeyBytes(key, keyFormat);
1504
- const functionName = index !== void 0 ? "getMetadataAtIndex" : "getMetadata";
1505
- const args = index !== void 0 ? [storageKeyBytes, operator, index] : [storageKeyBytes, operator];
1506
- return {
1507
- abi: CHUNKED_STORAGE_READER_CONTRACT.abi,
1508
- address: CHUNKED_STORAGE_READER_CONTRACT.address,
1509
- functionName,
1510
- args,
1511
- chainId
1512
- };
1513
- }
1514
- function getChunkedStorageChunksReadConfig(params) {
1515
- const { chainId, key, operator, start, end, index, keyFormat } = params;
1516
- const storageKeyBytes = getStorageKeyBytes(key, keyFormat);
1517
- const functionName = index !== void 0 ? "getChunksAtIndex" : "getChunks";
1518
- const args = index !== void 0 ? [storageKeyBytes, operator, start, end, index] : [storageKeyBytes, operator, start, end];
1519
- return {
1520
- abi: CHUNKED_STORAGE_READER_CONTRACT.abi,
1521
- address: CHUNKED_STORAGE_READER_CONTRACT.address,
1522
- functionName,
1523
- args,
1524
- chainId
1525
- };
1526
- }
1527
- function getChunkedStorageTotalWritesReadConfig(params) {
1528
- const { chainId, key, operator, keyFormat } = params;
1529
- const storageKeyBytes = getStorageKeyBytes(key, keyFormat);
1530
- return {
1531
- abi: CHUNKED_STORAGE_READER_CONTRACT.abi,
1532
- address: CHUNKED_STORAGE_READER_CONTRACT.address,
1533
- functionName: "getTotalWrites",
1534
- args: [storageKeyBytes, operator],
1535
- chainId
1536
- };
1537
- }
1538
976
  var MAX_CHUNKS = 255;
1539
977
  var OPTIMAL_CHUNK_SIZE = 80 * 1e3;
1540
978
  function chunkData(data, chunkSize = OPTIMAL_CHUNK_SIZE) {
@@ -2209,6 +1647,129 @@ function base64ToDataUri(base64Data) {
2209
1647
  const mimeType = detectFileTypeFromBase64(base64Data) || "application/octet-stream";
2210
1648
  return `data:${mimeType};base64,${base64Data}`;
2211
1649
  }
1650
+ var STREAMING_CHUNK_SIZE = 80 * 1e3;
1651
+ var BINARY_CHUNK_SIZE = 79998;
1652
+ function isBinaryFile(file) {
1653
+ const mimeType = file.type.toLowerCase();
1654
+ const textTypes = [
1655
+ "text/",
1656
+ "application/json",
1657
+ "application/xml",
1658
+ "application/javascript",
1659
+ "application/typescript",
1660
+ "application/x-javascript",
1661
+ "application/ecmascript"
1662
+ ];
1663
+ for (const textType of textTypes) {
1664
+ if (mimeType.startsWith(textType)) {
1665
+ return false;
1666
+ }
1667
+ }
1668
+ if (!mimeType || mimeType === "application/octet-stream") {
1669
+ const extension = file.name.split(".").pop()?.toLowerCase() || "";
1670
+ const textExtensions = [
1671
+ "txt",
1672
+ "md",
1673
+ "json",
1674
+ "xml",
1675
+ "html",
1676
+ "htm",
1677
+ "css",
1678
+ "js",
1679
+ "ts",
1680
+ "jsx",
1681
+ "tsx",
1682
+ "yaml",
1683
+ "yml",
1684
+ "toml",
1685
+ "ini",
1686
+ "cfg",
1687
+ "conf",
1688
+ "log",
1689
+ "csv",
1690
+ "svg"
1691
+ ];
1692
+ return !textExtensions.includes(extension);
1693
+ }
1694
+ return true;
1695
+ }
1696
+ async function readFileSlice(file, offset, size, isBinary, isFirstChunk) {
1697
+ const blob = file.slice(offset, offset + size);
1698
+ if (isBinary) {
1699
+ const arrayBuffer = await blob.arrayBuffer();
1700
+ const bytes = new Uint8Array(arrayBuffer);
1701
+ let base64 = "";
1702
+ const chunkSize = 32766;
1703
+ for (let i = 0; i < bytes.length; i += chunkSize) {
1704
+ const chunk = bytes.slice(i, i + chunkSize);
1705
+ base64 += btoa(String.fromCharCode(...chunk));
1706
+ }
1707
+ if (isFirstChunk) {
1708
+ const mimeType = detectFileTypeFromBase64(base64) || file.type || "application/octet-stream";
1709
+ return `data:${mimeType};base64,${base64}`;
1710
+ }
1711
+ return base64;
1712
+ } else {
1713
+ return await blob.text();
1714
+ }
1715
+ }
1716
+ async function* processFileStreaming(file, chunkSize = STREAMING_CHUNK_SIZE) {
1717
+ const binary = isBinaryFile(file);
1718
+ const effectiveChunkSize = binary ? BINARY_CHUNK_SIZE : chunkSize;
1719
+ let offset = 0;
1720
+ let chunkIndex = 0;
1721
+ while (offset < file.size) {
1722
+ const chunkString = await readFileSlice(
1723
+ file,
1724
+ offset,
1725
+ effectiveChunkSize,
1726
+ binary,
1727
+ chunkIndex === 0
1728
+ );
1729
+ const hash = core.keccak256HashString(chunkString);
1730
+ const compressedChunks = chunkDataForStorage(chunkString);
1731
+ yield {
1732
+ chunkIndex,
1733
+ hash,
1734
+ compressedChunks
1735
+ };
1736
+ offset += effectiveChunkSize;
1737
+ chunkIndex++;
1738
+ }
1739
+ if (chunkIndex === 0) {
1740
+ const emptyString = binary ? `data:${file.type || "application/octet-stream"};base64,` : "";
1741
+ const hash = core.keccak256HashString(emptyString);
1742
+ const compressedChunks = chunkDataForStorage(emptyString);
1743
+ yield {
1744
+ chunkIndex: 0,
1745
+ hash,
1746
+ compressedChunks
1747
+ };
1748
+ }
1749
+ }
1750
+ async function processFileStreamingComplete(file, onProgress) {
1751
+ const totalChunks = Math.max(1, Math.ceil(file.size / STREAMING_CHUNK_SIZE));
1752
+ const hashes = [];
1753
+ const allCompressedChunks = [];
1754
+ const binary = isBinaryFile(file);
1755
+ let processed = 0;
1756
+ for await (const result of processFileStreaming(file)) {
1757
+ hashes.push(result.hash);
1758
+ allCompressedChunks.push(result.compressedChunks);
1759
+ processed++;
1760
+ onProgress?.(processed, totalChunks);
1761
+ }
1762
+ return {
1763
+ hashes,
1764
+ allCompressedChunks,
1765
+ totalChunks: hashes.length,
1766
+ isBinary: binary
1767
+ };
1768
+ }
1769
+ function estimateChunkCount(fileSize, isBinary = true) {
1770
+ const chunkSize = isBinary ? BINARY_CHUNK_SIZE : STREAMING_CHUNK_SIZE;
1771
+ return Math.max(1, Math.ceil(fileSize / chunkSize));
1772
+ }
2212
1773
 
2213
1774
  exports.CHUNKED_STORAGE_CONTRACT = CHUNKED_STORAGE_CONTRACT;
2214
1775
  exports.CHUNKED_STORAGE_READER_CONTRACT = CHUNKED_STORAGE_READER_CONTRACT;
@@ -2227,6 +1788,7 @@ exports.containsXmlReferences = containsXmlReferences;
2227
1788
  exports.detectFileTypeFromBase64 = detectFileTypeFromBase64;
2228
1789
  exports.detectStorageType = detectStorageType;
2229
1790
  exports.encodeStorageKeyForUrl = encodeStorageKeyForUrl;
1791
+ exports.estimateChunkCount = estimateChunkCount;
2230
1792
  exports.fileToDataUri = fileToDataUri;
2231
1793
  exports.formatStorageKeyForDisplay = formatStorageKeyForDisplay;
2232
1794
  exports.generateStorageEmbedTag = generateStorageEmbedTag;
@@ -2235,18 +1797,15 @@ exports.generateXmlMetadataWithSource = generateXmlMetadataWithSource;
2235
1797
  exports.getChunkCount = getChunkCount;
2236
1798
  exports.getReferenceKey = getReferenceKey;
2237
1799
  exports.getStorageKeyBytes = getStorageKeyBytes;
1800
+ exports.isBinaryFile = isBinaryFile;
2238
1801
  exports.parseNetReferences = parseNetReferences;
2239
1802
  exports.processDataForStorage = processDataForStorage;
1803
+ exports.processFileStreaming = processFileStreaming;
1804
+ exports.processFileStreamingComplete = processFileStreamingComplete;
1805
+ exports.readFileSlice = readFileSlice;
2240
1806
  exports.resolveOperator = resolveOperator;
2241
1807
  exports.resolveXmlRecursive = resolveXmlRecursive;
2242
1808
  exports.shouldSuggestXmlStorage = shouldSuggestXmlStorage;
2243
- exports.useBulkStorage = useBulkStorage;
2244
- exports.useStorage = useStorage;
2245
- exports.useStorageForOperator = useStorageForOperator;
2246
- exports.useStorageForOperatorAndKey = useStorageForOperatorAndKey;
2247
- exports.useStorageFromRouter = useStorageFromRouter;
2248
- exports.useStorageTotalWrites = useStorageTotalWrites;
2249
- exports.useXmlStorage = useXmlStorage;
2250
1809
  exports.validateDataSize = validateDataSize;
2251
1810
  //# sourceMappingURL=index.js.map
2252
1811
  //# sourceMappingURL=index.js.map