@zing-protocol/zing-sdk 0.0.1 → 0.0.3

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.
Files changed (227) hide show
  1. package/dist/_generated/index.js +6 -0
  2. package/dist/_generated/utils/index.d.ts +12 -0
  3. package/dist/_generated/utils/index.js +135 -0
  4. package/dist/_generated/zing_framework/coin_utils.d.ts +15 -0
  5. package/dist/_generated/zing_framework/coin_utils.js +19 -0
  6. package/dist/_generated/zing_framework/deps/sui/object.d.ts +8 -0
  7. package/{src/_generated/zing_governance/deps/sui/object.ts → dist/_generated/zing_framework/deps/sui/object.js} +4 -7
  8. package/dist/_generated/zing_framework/derived_object_bag.d.ts +166 -0
  9. package/dist/_generated/zing_framework/derived_object_bag.js +221 -0
  10. package/dist/_generated/zing_framework/derived_table.d.ts +153 -0
  11. package/dist/_generated/zing_framework/derived_table.js +200 -0
  12. package/dist/_generated/zing_governance/admin.d.ts +20 -0
  13. package/dist/_generated/zing_governance/admin.js +26 -0
  14. package/dist/_generated/zing_governance/deps/sui/object.d.ts +8 -0
  15. package/{src/_generated/zing_identity/deps/sui/object.ts → dist/_generated/zing_governance/deps/sui/object.js} +4 -7
  16. package/dist/_generated/zing_governance/treasury.d.ts +56 -0
  17. package/dist/_generated/zing_governance/treasury.js +78 -0
  18. package/dist/_generated/zing_identity/config.d.ts +87 -0
  19. package/dist/_generated/zing_identity/config.js +98 -0
  20. package/{src/_generated/zing_studio/deps/std/type_name.ts → dist/_generated/zing_identity/deps/std/type_name.d.ts} +3 -11
  21. package/dist/_generated/zing_identity/deps/std/type_name.js +22 -0
  22. package/dist/_generated/zing_identity/deps/sui/object.d.ts +8 -0
  23. package/{src/_generated/zing_studio/deps/sui/object.ts → dist/_generated/zing_identity/deps/sui/object.js} +4 -7
  24. package/dist/_generated/zing_identity/deps/sui/object_table.d.ts +12 -0
  25. package/{src/_generated/zing_identity/deps/sui/object_table.ts → dist/_generated/zing_identity/deps/sui/object_table.js} +7 -10
  26. package/dist/_generated/zing_identity/deps/sui/table.d.ts +12 -0
  27. package/{src/_generated/zing_studio/deps/sui/table.ts → dist/_generated/zing_identity/deps/sui/table.js} +7 -10
  28. package/{src/_generated/zing_identity/deps/sui/vec_set.ts → dist/_generated/zing_identity/deps/sui/vec_set.d.ts} +3 -14
  29. package/dist/_generated/zing_identity/deps/sui/vec_set.js +22 -0
  30. package/dist/_generated/zing_identity/ecdsa.d.ts +81 -0
  31. package/dist/_generated/zing_identity/ecdsa.js +87 -0
  32. package/dist/_generated/zing_identity/identity.d.ts +262 -0
  33. package/dist/_generated/zing_identity/identity.js +294 -0
  34. package/dist/_generated/zing_identity/reclaim.d.ts +356 -0
  35. package/dist/_generated/zing_identity/reclaim.js +414 -0
  36. package/dist/_generated/zing_studio/app.d.ts +351 -0
  37. package/dist/_generated/zing_studio/app.js +451 -0
  38. package/dist/_generated/zing_studio/article.d.ts +331 -0
  39. package/dist/_generated/zing_studio/article.js +331 -0
  40. package/dist/_generated/zing_studio/config.d.ts +203 -0
  41. package/dist/_generated/zing_studio/config.js +233 -0
  42. package/{src/_generated/zing_identity/deps/std/type_name.ts → dist/_generated/zing_studio/deps/std/type_name.d.ts} +3 -11
  43. package/dist/_generated/zing_studio/deps/std/type_name.js +22 -0
  44. package/dist/_generated/zing_studio/deps/sui/bag.d.ts +12 -0
  45. package/{src/_generated/zing_studio/deps/sui/bag.ts → dist/_generated/zing_studio/deps/sui/bag.js} +7 -10
  46. package/dist/_generated/zing_studio/deps/sui/balance.d.ts +12 -0
  47. package/{src/_generated/zing_studio/deps/sui/balance.ts → dist/_generated/zing_studio/deps/sui/balance.js} +4 -7
  48. package/dist/_generated/zing_studio/deps/sui/coin.d.ts +12 -0
  49. package/{src/_generated/zing_studio/deps/sui/coin.ts → dist/_generated/zing_studio/deps/sui/coin.js} +5 -8
  50. package/dist/_generated/zing_studio/deps/sui/dynamic_field.d.ts +126 -0
  51. package/dist/_generated/zing_studio/deps/sui/dynamic_field.js +140 -0
  52. package/dist/_generated/zing_studio/deps/sui/object.d.ts +8 -0
  53. package/{src/_generated/zing_framework/deps/sui/object.ts → dist/_generated/zing_studio/deps/sui/object.js} +4 -7
  54. package/dist/_generated/zing_studio/deps/sui/table.d.ts +12 -0
  55. package/{src/_generated/zing_identity/deps/sui/table.ts → dist/_generated/zing_studio/deps/sui/table.js} +7 -10
  56. package/dist/_generated/zing_studio/deps/sui/vec_map.d.ts +30 -0
  57. package/{src/_generated/zing_studio/deps/sui/vec_map.ts → dist/_generated/zing_studio/deps/sui/vec_map.js} +15 -21
  58. package/{src/_generated/zing_studio/deps/sui/vec_set.ts → dist/_generated/zing_studio/deps/sui/vec_set.d.ts} +3 -14
  59. package/dist/_generated/zing_studio/deps/sui/vec_set.js +22 -0
  60. package/dist/_generated/zing_studio/deps/walrus/blob.d.ts +20 -0
  61. package/{src/_generated/zing_studio/deps/walrus/blob.ts → dist/_generated/zing_studio/deps/walrus/blob.js} +11 -12
  62. package/dist/_generated/zing_studio/deps/walrus/events.d.ts +83 -0
  63. package/dist/_generated/zing_studio/deps/walrus/events.js +122 -0
  64. package/dist/_generated/zing_studio/deps/walrus/metadata.d.ts +71 -0
  65. package/dist/_generated/zing_studio/deps/walrus/metadata.js +73 -0
  66. package/dist/_generated/zing_studio/deps/walrus/storage_resource.d.ts +12 -0
  67. package/{src/_generated/zing_studio/deps/walrus/storage_resource.ts → dist/_generated/zing_studio/deps/walrus/storage_resource.js} +7 -8
  68. package/dist/_generated/zing_studio/deps/zing_framework/derived_object_bag.d.ts +12 -0
  69. package/{src/_generated/zing_studio/deps/zing_framework/derived_object_bag.ts → dist/_generated/zing_studio/deps/zing_framework/derived_object_bag.js} +7 -8
  70. package/dist/_generated/zing_studio/deps/zing_framework/derived_table.d.ts +12 -0
  71. package/{src/_generated/zing_studio/deps/zing_framework/derived_table.ts → dist/_generated/zing_studio/deps/zing_framework/derived_table.js} +7 -8
  72. package/dist/_generated/zing_studio/donation.d.ts +24 -0
  73. package/{src/_generated/zing_studio/donation.ts → dist/_generated/zing_studio/donation.js} +7 -8
  74. package/dist/_generated/zing_studio/enclave.d.ts +187 -0
  75. package/dist/_generated/zing_studio/enclave.js +231 -0
  76. package/dist/_generated/zing_studio/nitro_attestation.d.ts +148 -0
  77. package/dist/_generated/zing_studio/nitro_attestation.js +183 -0
  78. package/dist/_generated/zing_studio/referral.d.ts +166 -0
  79. package/dist/_generated/zing_studio/referral.js +224 -0
  80. package/dist/_generated/zing_studio/storage.d.ts +327 -0
  81. package/dist/_generated/zing_studio/storage.js +365 -0
  82. package/dist/_generated/zing_studio/studio.d.ts +282 -0
  83. package/dist/_generated/zing_studio/studio.js +360 -0
  84. package/dist/bcs.d.ts +61 -0
  85. package/dist/bcs.js +109 -0
  86. package/dist/client/index.d.ts +228 -0
  87. package/dist/client/index.js +296 -0
  88. package/dist/client/types.d.ts +23 -0
  89. package/dist/client/types.js +1 -0
  90. package/dist/components/index.js +3 -0
  91. package/dist/components/wallet-provider.d.ts +7 -0
  92. package/dist/components/wallet-provider.js +33 -0
  93. package/dist/components/walrus-provider.d.ts +31 -0
  94. package/dist/components/walrus-provider.js +71 -0
  95. package/dist/components/zing-provider.d.ts +15 -0
  96. package/dist/components/zing-provider.js +22 -0
  97. package/dist/config/common.d.ts +23 -0
  98. package/dist/config/common.js +61 -0
  99. package/dist/config/index.d.ts +8 -0
  100. package/dist/config/index.js +28 -0
  101. package/dist/config/mainnet.d.ts +6 -0
  102. package/dist/config/mainnet.js +80 -0
  103. package/dist/config/testnet.d.ts +6 -0
  104. package/dist/config/testnet.js +81 -0
  105. package/dist/config/types.d.ts +49 -0
  106. package/dist/config/types.js +1 -0
  107. package/dist/const.d.ts +4 -0
  108. package/dist/const.js +25 -0
  109. package/dist/getters.d.ts +228 -0
  110. package/dist/getters.js +317 -0
  111. package/{src/hooks/index.ts → dist/hooks/index.d.ts} +2 -3
  112. package/dist/hooks/index.js +9 -0
  113. package/dist/hooks/useGetStudio.d.ts +26 -0
  114. package/dist/hooks/useGetStudio.js +17 -0
  115. package/dist/hooks/useGetTierPlan.d.ts +7 -0
  116. package/dist/hooks/useGetTierPlan.js +85 -0
  117. package/dist/hooks/useReclaim.d.ts +12 -0
  118. package/dist/hooks/useReclaim.js +87 -0
  119. package/dist/hooks/useSignAndExecuteTransaction.d.ts +6 -0
  120. package/dist/hooks/useSignAndExecuteTransaction.js +40 -0
  121. package/dist/hooks/useSignPersonalMessage.d.ts +8 -0
  122. package/dist/hooks/useSignPersonalMessage.js +21 -0
  123. package/dist/hooks/useZingInfiniteQueries.d.ts +75 -0
  124. package/dist/hooks/useZingInfiniteQueries.js +28 -0
  125. package/dist/hooks/useZingMutation.d.ts +35 -0
  126. package/dist/hooks/useZingMutation.js +37 -0
  127. package/dist/hooks/useZingQueries.d.ts +127 -0
  128. package/dist/hooks/useZingQueries.js +37 -0
  129. package/dist/hooks/useZingQuery.d.ts +147 -0
  130. package/dist/hooks/useZingQuery.js +34 -0
  131. package/{src/index.ts → dist/index.d.ts} +2 -3
  132. package/dist/index.js +9 -0
  133. package/dist/lib/utils/colorful-logger.d.ts +2 -0
  134. package/dist/lib/utils/colorful-logger.js +23 -0
  135. package/dist/lib/utils/const.d.ts +25 -0
  136. package/dist/lib/utils/const.js +25 -0
  137. package/dist/lib/utils/helpers.d.ts +10 -0
  138. package/dist/lib/utils/helpers.js +49 -0
  139. package/dist/lib/utils/index.js +4 -0
  140. package/dist/lib/utils/init-app-with-shadow.d.ts +6 -0
  141. package/dist/lib/utils/init-app-with-shadow.js +28 -0
  142. package/dist/lib/utils/quilt.d.ts +61 -0
  143. package/dist/lib/utils/quilt.js +194 -0
  144. package/dist/lib/utils/reclaim.d.ts +29 -0
  145. package/dist/lib/utils/reclaim.js +88 -0
  146. package/dist/lib/utils/types.d.ts +5 -0
  147. package/dist/lib/utils/types.js +1 -0
  148. package/dist/mutations/index.js +3 -0
  149. package/dist/mutations/seal.d.ts +12 -0
  150. package/dist/mutations/seal.js +41 -0
  151. package/dist/mutations/signer.d.ts +10 -0
  152. package/dist/mutations/signer.js +176 -0
  153. package/dist/mutations/walrus.d.ts +98 -0
  154. package/dist/mutations/walrus.js +488 -0
  155. package/dist/stores/index.js +3 -0
  156. package/dist/stores/walletStore.d.ts +48 -0
  157. package/dist/stores/walletStore.js +232 -0
  158. package/dist/stores/walrusStore.d.ts +28 -0
  159. package/dist/stores/walrusStore.js +61 -0
  160. package/dist/stores/zkloginStore.d.ts +28 -0
  161. package/dist/stores/zkloginStore.js +27 -0
  162. package/dist/types.d.ts +99 -0
  163. package/dist/types.js +1 -0
  164. package/package.json +18 -10
  165. package/src/_generated/utils/index.ts +0 -181
  166. package/src/_generated/zing_framework/coin_utils.ts +0 -41
  167. package/src/_generated/zing_framework/derived_object_bag.ts +0 -400
  168. package/src/_generated/zing_framework/derived_table.ts +0 -366
  169. package/src/_generated/zing_governance/admin.ts +0 -47
  170. package/src/_generated/zing_governance/treasury.ts +0 -134
  171. package/src/_generated/zing_identity/config.ts +0 -191
  172. package/src/_generated/zing_identity/ecdsa.ts +0 -166
  173. package/src/_generated/zing_identity/identity.ts +0 -661
  174. package/src/_generated/zing_identity/reclaim.ts +0 -803
  175. package/src/_generated/zing_studio/app.ts +0 -855
  176. package/src/_generated/zing_studio/article.ts +0 -598
  177. package/src/_generated/zing_studio/config.ts +0 -475
  178. package/src/_generated/zing_studio/deps/sui/dynamic_field.ts +0 -272
  179. package/src/_generated/zing_studio/deps/walrus/events.ts +0 -124
  180. package/src/_generated/zing_studio/deps/walrus/metadata.ts +0 -137
  181. package/src/_generated/zing_studio/enclave.ts +0 -466
  182. package/src/_generated/zing_studio/nitro_attestation.ts +0 -308
  183. package/src/_generated/zing_studio/referral.ts +0 -447
  184. package/src/_generated/zing_studio/storage.ts +0 -664
  185. package/src/_generated/zing_studio/studio.ts +0 -682
  186. package/src/bcs.ts +0 -139
  187. package/src/client/index.ts +0 -557
  188. package/src/client/types.ts +0 -28
  189. package/src/components/wallet-provider.tsx +0 -53
  190. package/src/components/walrus-provider.tsx +0 -212
  191. package/src/components/zing-provider.tsx +0 -54
  192. package/src/config/common.ts +0 -82
  193. package/src/config/index.ts +0 -45
  194. package/src/config/mainnet.ts +0 -109
  195. package/src/config/testnet.ts +0 -111
  196. package/src/config/types.ts +0 -69
  197. package/src/const.ts +0 -32
  198. package/src/getters.ts +0 -523
  199. package/src/hooks/useGetStudio.ts +0 -22
  200. package/src/hooks/useGetTierPlan.ts +0 -115
  201. package/src/hooks/useReclaim.ts +0 -165
  202. package/src/hooks/useSignAndExecuteTransaction.ts +0 -57
  203. package/src/hooks/useSignPersonalMessage.ts +0 -28
  204. package/src/hooks/useZingInfiniteQueries.ts +0 -92
  205. package/src/hooks/useZingMutation.ts +0 -66
  206. package/src/hooks/useZingQueries.ts +0 -107
  207. package/src/hooks/useZingQuery.ts +0 -88
  208. package/src/lib/utils/colorful-logger.ts +0 -27
  209. package/src/lib/utils/const.ts +0 -25
  210. package/src/lib/utils/helpers.ts +0 -78
  211. package/src/lib/utils/init-app-with-shadow.ts +0 -42
  212. package/src/lib/utils/quilt.ts +0 -317
  213. package/src/lib/utils/reclaim.ts +0 -148
  214. package/src/lib/utils/types.ts +0 -14
  215. package/src/mutations/seal.ts +0 -78
  216. package/src/mutations/signer.ts +0 -241
  217. package/src/mutations/walrus.ts +0 -862
  218. package/src/stores/walletStore.ts +0 -360
  219. package/src/stores/walrusStore.ts +0 -118
  220. package/src/stores/zkloginStore.ts +0 -53
  221. package/src/types.ts +0 -120
  222. package/tsconfig.json +0 -12
  223. /package/{src/_generated/index.js → dist/_generated/index.d.ts} +0 -0
  224. /package/{src/components/index.ts → dist/components/index.d.ts} +0 -0
  225. /package/{src/lib/utils/index.ts → dist/lib/utils/index.d.ts} +0 -0
  226. /package/{src/mutations/index.ts → dist/mutations/index.d.ts} +0 -0
  227. /package/{src/stores/index.ts → dist/stores/index.d.ts} +0 -0
@@ -0,0 +1,488 @@
1
+ import { signAndExecuteGasPoolTransaction } from "./signer.js";
2
+ import { certifyArticleBlob, finalizePublishArticle, startPublishArticle, } from "../_generated/zing_studio/app.js";
3
+ import { articleBlobAddMetadata, articleBlobInsertOrUpdateMetadataPair, articleBlobRemoveMetadata, } from "../_generated/zing_studio/article.js";
4
+ import { _new as newMetadata } from "../_generated/zing_studio/deps/walrus/metadata.js";
5
+ import { encodedBlobLength, encodeQuiltPatchId, getDerivedStorageID, getDerivedStudioID, getPublishedArticleAndBlobId, signersToBitmap, } from "../getters.js";
6
+ import { encryptData } from "../mutations/seal.js";
7
+ import { bcs } from "@mysten/sui/bcs";
8
+ import { Transaction } from "@mysten/sui/transactions";
9
+ import { blobIdToInt } from "@mysten/walrus";
10
+ const REDSTUFF_CODING_TYPE = 1;
11
+ // ZING_PREFIX
12
+ const FIXED_FILE_IV = new Uint8Array([
13
+ 4, 122, 105, 110, 103, 0, 0, 0, 0, 0, 0, 0,
14
+ ]);
15
+ const BYTES_PER_UNIT_SIZE = 1024 * 1024;
16
+ export function buildPublishArticleTransaction(config, walrusSystem, walTreasury, storageByEpoch, fileSize, owner, subscriptionLevel, blobId, rootHash, articleMetadata, attributes, existingAttributes) {
17
+ const { zingStudioPackageId, walrusPackageId, zingStudioConfigSharedObjectRef, walrusSystemSharedObjectRef, zingStorageTreasurySharedObjectRef, } = config;
18
+ return (tx) => {
19
+ const { encodedSize, writeCost } = storageCost(walrusSystem, fileSize, 2);
20
+ console.log({ encodedSize });
21
+ const currentEpoch = walrusSystem.committee.epoch;
22
+ if (!storageByEpoch?.[currentEpoch]) {
23
+ throw new Error(`No Epochs Found for ${currentEpoch}`);
24
+ }
25
+ if (!storageByEpoch?.[currentEpoch + 1]) {
26
+ throw new Error(`No Epochs Found for ${currentEpoch + 1}`);
27
+ }
28
+ if (storageByEpoch[currentEpoch] < encodedSize) {
29
+ throw new Error(`Insufficient Storages size ${storageByEpoch[currentEpoch]} for Epochs ${currentEpoch} with required size ${encodedSize}`);
30
+ }
31
+ if (storageByEpoch[currentEpoch + 1] < encodedSize) {
32
+ throw new Error(`Insufficient Storages size ${storageByEpoch[currentEpoch + 1]} for Epochs ${currentEpoch + 1} with required size ${encodedSize}`);
33
+ }
34
+ if (BigInt(walTreasury) < writeCost) {
35
+ throw new Error(`Insufficient walTreasury Balance ${walTreasury} for writeCost: ${writeCost}`);
36
+ }
37
+ console.log({ fileSize, encodedSize });
38
+ console.log({ articleMetadata });
39
+ const [article, publishReceipt] = tx.add(startPublishArticle({
40
+ package: zingStudioPackageId,
41
+ arguments: {
42
+ config: tx.sharedObjectRef(zingStudioConfigSharedObjectRef),
43
+ studio: tx.object(getDerivedStudioID(zingStudioConfigSharedObjectRef.objectId, owner)),
44
+ walrusSystem: tx.sharedObjectRef(walrusSystemSharedObjectRef),
45
+ storageTreasury: tx.sharedObjectRef(zingStorageTreasurySharedObjectRef),
46
+ storageSpace: tx.object(getDerivedStorageID(zingStudioConfigSharedObjectRef.objectId, owner)),
47
+ subscriptionLevel: tx.pure.option("u8", subscriptionLevel),
48
+ blobId: blobIdToInt(blobId),
49
+ rootHash: BigInt(bcs.u256().parse(rootHash)),
50
+ unencodedBlobSize: fileSize,
51
+ encodingType: REDSTUFF_CODING_TYPE,
52
+ identifiers: tx.pure.vector("string", articleMetadata.map((m) => m.identifier)),
53
+ blobIndexes: tx.pure.vector("u64", articleMetadata.map(() => 0)),
54
+ mimeTypes: tx.pure.vector("string", articleMetadata.map((m) => m.tags["content-type"])),
55
+ metadataSizes: tx.pure.vector("u64", articleMetadata.map((m) => m.size)),
56
+ },
57
+ }));
58
+ if (!existingAttributes) {
59
+ tx.add(articleBlobAddMetadata({
60
+ package: zingStudioPackageId,
61
+ arguments: {
62
+ config: tx.sharedObjectRef(zingStudioConfigSharedObjectRef),
63
+ self: article,
64
+ blobIndex: tx.pure.u64(0),
65
+ metadata: newMetadata({
66
+ package: walrusPackageId,
67
+ }),
68
+ },
69
+ }));
70
+ }
71
+ Object.keys(attributes).forEach((key) => {
72
+ const value = attributes[key];
73
+ if (value === null) {
74
+ if (existingAttributes && key in existingAttributes) {
75
+ tx.add(articleBlobRemoveMetadata({
76
+ package: zingStudioPackageId,
77
+ arguments: {
78
+ config: tx.sharedObjectRef(zingStudioConfigSharedObjectRef),
79
+ self: article,
80
+ blobIndex: tx.pure.u64(0),
81
+ key,
82
+ },
83
+ }));
84
+ }
85
+ }
86
+ else {
87
+ tx.add(articleBlobInsertOrUpdateMetadataPair({
88
+ package: zingStudioPackageId,
89
+ arguments: {
90
+ config: tx.sharedObjectRef(zingStudioConfigSharedObjectRef),
91
+ self: article,
92
+ blobIndex: tx.pure.u64(0),
93
+ key,
94
+ value,
95
+ },
96
+ }));
97
+ }
98
+ });
99
+ // put article to studio
100
+ tx.add(finalizePublishArticle({
101
+ package: zingStudioPackageId,
102
+ arguments: {
103
+ config: tx.sharedObjectRef(zingStudioConfigSharedObjectRef),
104
+ studio: tx.object(getDerivedStudioID(zingStudioConfigSharedObjectRef.objectId, owner)),
105
+ receipt: publishReceipt,
106
+ article: article,
107
+ },
108
+ }));
109
+ };
110
+ }
111
+ export function buildCertifyArticleBlobTransaction(config, walrusClient, owner, articleId, { blobId, blobObjectId, confirmations, certificate, deletable, }) {
112
+ const { zingStudioPackageId, zingStudioConfigSharedObjectRef, walrusSystemSharedObjectRef, } = config;
113
+ return async (tx) => {
114
+ const systemState = await walrusClient.systemState();
115
+ const combinedSignature = certificate ??
116
+ (await walrusClient.certificateFromConfirmations({
117
+ confirmations,
118
+ blobId,
119
+ deletable,
120
+ blobObjectId,
121
+ }));
122
+ tx.add(certifyArticleBlob({
123
+ package: zingStudioPackageId,
124
+ arguments: {
125
+ config: tx.sharedObjectRef(zingStudioConfigSharedObjectRef),
126
+ studio: tx.object(getDerivedStudioID(zingStudioConfigSharedObjectRef.objectId, owner)),
127
+ walrusSystem: tx.sharedObjectRef(walrusSystemSharedObjectRef),
128
+ articleId: tx.object(articleId),
129
+ blobIndex: tx.pure.u64(0), // TODO
130
+ signature: tx.pure.vector("u8", combinedSignature.signature),
131
+ signersBitmap: tx.pure.vector("u8", signersToBitmap(combinedSignature.signers, systemState.committee.members.length)),
132
+ message: tx.pure.vector("u8", combinedSignature.serializedMessage),
133
+ },
134
+ }));
135
+ };
136
+ }
137
+ export const zingWriteFlow = (config, suiGrpcClient, suiJsonRpcClient, walrusClient, walrusSystem, walTreasury, storageByEpoch, fileKey, studioObjectId, owner, subscriptionLevel, articleMetadata, options, withUploadRelayClient, blobRegisteredEventType, publishArticleEventType) => {
138
+ const { files } = options;
139
+ const encode = async () => {
140
+ const { quilt, index } = await walrusClient.encodeQuilt({
141
+ blobs: await Promise.all(files.map(async (file, i) => {
142
+ const contents = await file.bytes();
143
+ const bytes = await encryptData(fileKey, contents, FIXED_FILE_IV);
144
+ return {
145
+ contents: bytes,
146
+ identifier: (await file.getIdentifier()) ?? `file-${i}`,
147
+ tags: (await file.getTags()) ?? {},
148
+ };
149
+ })),
150
+ });
151
+ console.log({ walrus_system: await walrusClient.systemState() });
152
+ console.log({ quiltlength: quilt.length });
153
+ // store encryptedBytes
154
+ const metadata = withUploadRelayClient
155
+ ? await walrusClient.computeBlobMetadata({
156
+ bytes: quilt,
157
+ })
158
+ : await walrusClient.encodeBlob(quilt);
159
+ return {
160
+ metadata,
161
+ size: quilt.length,
162
+ data: withUploadRelayClient ? quilt : undefined,
163
+ index,
164
+ };
165
+ };
166
+ const register = ({ data, metadata, index, size }, { deletable, owner, attributes }) => {
167
+ const transaction = new Transaction();
168
+ // transaction.setSenderIfNotSet(owner);
169
+ if (withUploadRelayClient) {
170
+ const meta = metadata;
171
+ transaction.add(walrusClient.sendUploadRelayTip({
172
+ size,
173
+ blobDigest: meta.blobDigest,
174
+ nonce: meta.nonce,
175
+ }));
176
+ }
177
+ // 1. rent storage space and publish article
178
+ transaction.add(buildPublishArticleTransaction(config, walrusSystem, walTreasury, storageByEpoch, size, owner, subscriptionLevel, metadata.blobId, metadata.rootHash, articleMetadata, { _walrusBlobType: "quilt", ...attributes }, null));
179
+ console.log({ registerTransaction: transaction });
180
+ return {
181
+ registerTransaction: transaction,
182
+ index,
183
+ data,
184
+ metadata,
185
+ deletable,
186
+ };
187
+ };
188
+ const upload = async ({ index, data, metadata, deletable }, { digest }) => {
189
+ const { parsedPublishArticleEvent, blobObjectId } = await getPublishedArticleAndBlobId(suiGrpcClient, suiJsonRpcClient, walrusClient, digest, blobRegisteredEventType, publishArticleEventType);
190
+ const articleId = parsedPublishArticleEvent.article_id;
191
+ if (withUploadRelayClient) {
192
+ const meta = metadata;
193
+ return {
194
+ index,
195
+ parsedPublishArticleEvent,
196
+ articleId,
197
+ blobObjectId,
198
+ metadata,
199
+ deletable,
200
+ certificate: (await walrusClient.writeBlobToUploadRelay({
201
+ blobId: metadata.blobId,
202
+ blob: data,
203
+ nonce: meta.nonce,
204
+ txDigest: digest,
205
+ blobObjectId,
206
+ deletable,
207
+ encodingType: meta.metadata.encodingType,
208
+ })).certificate,
209
+ };
210
+ }
211
+ const meta = metadata;
212
+ return {
213
+ index,
214
+ blobObjectId,
215
+ articleId,
216
+ parsedPublishArticleEvent,
217
+ metadata,
218
+ deletable,
219
+ confirmations: await walrusClient.writeEncodedBlobToNodes({
220
+ blobId: metadata.blobId,
221
+ objectId: blobObjectId,
222
+ metadata: meta.metadata,
223
+ sliversByNode: meta.sliversByNode,
224
+ deletable,
225
+ }),
226
+ };
227
+ };
228
+ const certify = ({ index, metadata, confirmations, certificate, articleId, blobObjectId, deletable, }) => {
229
+ console.log({ confirmations });
230
+ const tx = new Transaction();
231
+ if (confirmations) {
232
+ tx.add(buildCertifyArticleBlobTransaction({
233
+ zingStudioPackageId: config.zingStudioPackageId,
234
+ zingStudioConfigSharedObjectRef: config.zingStudioConfigSharedObjectRef,
235
+ walrusSystemSharedObjectRef: config.walrusSystemSharedObjectRef,
236
+ }, walrusClient, owner, articleId, {
237
+ certificate,
238
+ blobId: metadata.blobId,
239
+ blobObjectId,
240
+ confirmations,
241
+ deletable,
242
+ }));
243
+ }
244
+ else {
245
+ tx.add(buildCertifyArticleBlobTransaction({
246
+ zingStudioPackageId: config.zingStudioPackageId,
247
+ zingStudioConfigSharedObjectRef: config.zingStudioConfigSharedObjectRef,
248
+ walrusSystemSharedObjectRef: config.walrusSystemSharedObjectRef,
249
+ }, walrusClient, owner, articleId, {
250
+ certificate,
251
+ blobId: metadata.blobId,
252
+ blobObjectId,
253
+ deletable,
254
+ }));
255
+ }
256
+ return {
257
+ index,
258
+ blobObjectId,
259
+ metadata,
260
+ transaction: tx,
261
+ };
262
+ };
263
+ async function listFiles({ index, blobObjectId, metadata, }) {
264
+ return index.patches.map((patch) => ({
265
+ id: encodeQuiltPatchId({
266
+ quiltId: metadata.blobId,
267
+ patchId: {
268
+ version: 1,
269
+ startIndex: patch.startIndex,
270
+ endIndex: patch.endIndex,
271
+ },
272
+ }),
273
+ blobId: metadata.blobId,
274
+ blobObjectId,
275
+ }));
276
+ }
277
+ const stepResults = {};
278
+ function getResults(step, current) {
279
+ if (!stepResults[step]) {
280
+ throw new Error(`${step} must be executed before calling ${current}`);
281
+ }
282
+ return stepResults[step];
283
+ }
284
+ return {
285
+ encode: async () => {
286
+ if (!stepResults.encode) {
287
+ stepResults.encode = await encode();
288
+ }
289
+ },
290
+ register: (options) => {
291
+ stepResults.register = register(getResults("encode", "register"), options);
292
+ return stepResults.register.registerTransaction;
293
+ },
294
+ upload: async (options) => {
295
+ stepResults.upload = await upload(getResults("register", "upload"), options);
296
+ return stepResults.upload.parsedPublishArticleEvent;
297
+ },
298
+ certify: () => {
299
+ stepResults.certify = certify(getResults("upload", "certify"));
300
+ return stepResults.certify.transaction;
301
+ },
302
+ listFiles: async () => listFiles(getResults("certify", "listFiles")),
303
+ };
304
+ };
305
+ export async function uploadFileToWalrus(zingWriteFlowConfig, suiGrpcClient, suiJsonRpcClient, walrusClient, walrusSystem, walTreasury, storageByEpoch, fileKey, walrusFiles, subscriptionLevel, metadata, signer, gasPoolBearerToken, onProgress) {
306
+ const report = (stage) => {
307
+ if (onProgress)
308
+ onProgress(stage);
309
+ };
310
+ const owner = signer.suiAddress;
311
+ if (!owner)
312
+ throw new Error("no signer");
313
+ // Step 1: Create and encode the flow (can be done immediately when file is selected)
314
+ const flow = zingWriteFlow(zingWriteFlowConfig, suiGrpcClient, suiJsonRpcClient, walrusClient, walrusSystem, walTreasury, storageByEpoch, fileKey, getDerivedStudioID(zingWriteFlowConfig.zingStudioConfigSharedObjectRef.objectId, owner), owner, subscriptionLevel, metadata, {
315
+ files: walrusFiles,
316
+ }, true, zingWriteFlowConfig.blobRegisteredEventType, zingWriteFlowConfig.publishArticleEventType);
317
+ report("encode");
318
+ await flow.encode();
319
+ // Step 2: Register the blob (triggered by user clicking a register button after the encode step)
320
+ async function handleRegister() {
321
+ if (!owner)
322
+ throw new Error("suiaddress not found in zkloginsignerstate");
323
+ report("register_blob");
324
+ const registerTx = flow.register({
325
+ epochs: 1,
326
+ owner,
327
+ deletable: true,
328
+ });
329
+ const registerTxEffects = await signAndExecuteGasPoolTransaction(signer, suiJsonRpcClient, registerTx);
330
+ if (!registerTxEffects?.transactionDigest)
331
+ throw new Error("fail to execute register Blob transaction");
332
+ const finalizedTransaction = await suiJsonRpcClient.waitForTransaction({
333
+ digest: registerTxEffects.transactionDigest,
334
+ });
335
+ // Step 3: Upload the data to storage nodes
336
+ // This can be done immediately after the register step, or as a separate step the user initiates
337
+ report("upload");
338
+ return await flow.upload({
339
+ digest: finalizedTransaction.digest,
340
+ });
341
+ }
342
+ const parsedPublishArticleEvent = await handleRegister();
343
+ // Step 4: Certify the blob (triggered by user clicking a certify button after the blob is uploaded)
344
+ async function handleCertify() {
345
+ report("certify_blob");
346
+ const certifyTx = flow.certify();
347
+ const certifyTxEffects = await signAndExecuteGasPoolTransaction(signer, suiJsonRpcClient, certifyTx);
348
+ if (!certifyTxEffects?.transactionDigest)
349
+ throw new Error("fail to execute certify Blob transaction");
350
+ await suiJsonRpcClient.waitForTransaction({
351
+ digest: certifyTxEffects.transactionDigest,
352
+ });
353
+ report("publish");
354
+ }
355
+ await handleCertify();
356
+ return parsedPublishArticleEvent;
357
+ }
358
+ export async function downloadImagesFromMarkdown(markdown, as = "blob") {
359
+ // Match ![alt](url) or [![alt](url)](...)
360
+ const imageRegex = /!\[[^\]]*\]\(([^)]+)\)/g;
361
+ const urls = new Set();
362
+ let match;
363
+ while ((match = imageRegex.exec(markdown)) !== null) {
364
+ let url = match[1].trim();
365
+ // Remove optional Markdown title e.g. (url "title")
366
+ const spaceIndex = url.indexOf(" ");
367
+ if (spaceIndex !== -1 && url[0] !== '"') {
368
+ url = url.slice(0, spaceIndex);
369
+ }
370
+ // Include both HTTP URLs and data URLs (base64 encoded images)
371
+ if (url.startsWith("http") ||
372
+ url.startsWith("https") ||
373
+ url.startsWith("data:")) {
374
+ urls.add(url);
375
+ }
376
+ }
377
+ const images = [];
378
+ for (const url of urls) {
379
+ try {
380
+ if (url.startsWith("data:")) {
381
+ // Handle base64 encoded data URLs
382
+ const response = await fetch(url);
383
+ if (!response.ok)
384
+ throw new Error(`Failed to process data URL`);
385
+ if (as === "blob") {
386
+ const blob = await response.blob();
387
+ images.push({
388
+ url,
389
+ data: blob,
390
+ });
391
+ }
392
+ else {
393
+ const buffer = await response.arrayBuffer();
394
+ images.push({
395
+ url,
396
+ data: new Uint8Array(buffer),
397
+ });
398
+ }
399
+ }
400
+ else {
401
+ // Handle regular HTTP/HTTPS URLs
402
+ const response = await fetch(url);
403
+ if (!response.ok)
404
+ throw new Error(`Failed to fetch ${url}`);
405
+ if (as === "blob") {
406
+ const blob = await response.blob();
407
+ images.push({
408
+ url,
409
+ data: blob,
410
+ });
411
+ }
412
+ else {
413
+ const buffer = await response.arrayBuffer();
414
+ images.push({
415
+ url,
416
+ data: new Uint8Array(buffer),
417
+ });
418
+ }
419
+ }
420
+ }
421
+ catch (err) {
422
+ console.error(`Error processing image from ${url.startsWith("data:") ? "data URL" : url}:`, err);
423
+ }
424
+ }
425
+ return images;
426
+ }
427
+ /**
428
+ * Calculate the cost of storing a blob for a given a size and number of epochs.
429
+ */
430
+ export function storageCost(systemState, size, epochs) {
431
+ const encodedSize = encodedBlobLength(size, systemState.committee.n_shards);
432
+ const storageUnits = storageUnitsFromSize(encodedSize);
433
+ const storageCost = BigInt(storageUnits) *
434
+ BigInt(systemState.storage_price_per_unit_size) *
435
+ BigInt(epochs);
436
+ BigInt(epochs);
437
+ const writeCost = BigInt(storageUnits) * BigInt(systemState.write_price_per_unit_size);
438
+ return {
439
+ encodedSize,
440
+ storageCost,
441
+ writeCost,
442
+ totalCost: storageCost + writeCost,
443
+ };
444
+ }
445
+ export function storageUnitsFromSize(size) {
446
+ return Math.ceil(size / BYTES_PER_UNIT_SIZE);
447
+ }
448
+ /**
449
+ * Replace all base64 image URLs in markdown with asset identifiers (e.g. assets-0.png).
450
+ *
451
+ * @param markdown - the original markdown string containing data URLs
452
+ * @param assets - the array returned from downloadImagesFromMarkdown()
453
+ * @returns a new markdown string with data URLs replaced by identifiers
454
+ */
455
+ export function replaceBase64ImagesWithIdentifiers(markdown, assets) {
456
+ let replacedMarkdown = markdown;
457
+ // Regex to match ![alt](url) markdown image syntax
458
+ const imageRegex = /!\[([^\]]*)\]\(([^)]+)\)/g;
459
+ replacedMarkdown = replacedMarkdown.replace(imageRegex, (match, alt, url) => {
460
+ url = url.trim();
461
+ // Find the matching asset by comparing the original URL
462
+ const assetIndex = assets.findIndex((asset) => asset.url === url);
463
+ if (assetIndex === -1) {
464
+ // No matching asset found, keep original
465
+ return match;
466
+ }
467
+ const asset = assets[assetIndex];
468
+ // Try to infer extension from mime type
469
+ let extension = ".bin";
470
+ if (asset.data instanceof Blob) {
471
+ const type = asset.data.type;
472
+ if (type.includes("png"))
473
+ extension = ".png";
474
+ else if (type.includes("jpeg") || type.includes("jpg"))
475
+ extension = ".jpg";
476
+ else if (type.includes("gif"))
477
+ extension = ".gif";
478
+ else if (type.includes("webp"))
479
+ extension = ".webp";
480
+ else if (type.includes("svg"))
481
+ extension = ".svg";
482
+ }
483
+ // Replace with new identifier reference
484
+ const newIdentifier = `assets-${assetIndex}${extension}`;
485
+ return `![${alt}](${newIdentifier})`;
486
+ });
487
+ return replacedMarkdown;
488
+ }
@@ -0,0 +1,3 @@
1
+ export * from "./walrusStore.js";
2
+ export * from "./walletStore.js";
3
+ export * from "./zkloginStore.js";
@@ -0,0 +1,48 @@
1
+ import { Ed25519Keypair } from "@mysten/sui/keypairs/ed25519";
2
+ import { decodeJwt } from "@mysten/sui/zklogin";
3
+ import type { AuthProvider } from "../config/common.js";
4
+ import type { PartialZkLoginSignature, ZKLoginSignerState } from "../types.js";
5
+ import type { SuiClient } from "@mysten/sui/client";
6
+ import type { StoreApi } from "zustand";
7
+ export interface WalletAccount {
8
+ jwt: ReturnType<typeof decodeJwt> & {
9
+ email: string;
10
+ email_verified: boolean;
11
+ family_name?: string;
12
+ given_name?: string;
13
+ name?: string;
14
+ picture?: string;
15
+ };
16
+ }
17
+ export interface WalletState {
18
+ suiClient: SuiClient;
19
+ isConnected: boolean;
20
+ isLoading: boolean;
21
+ account: WalletAccount | null;
22
+ error: string | null;
23
+ network: string;
24
+ jwt: string | null;
25
+ decodedJwt: ReturnType<typeof decodeJwt> | null;
26
+ authProvider: AuthProvider | null;
27
+ ephemeralKeyPair: Ed25519Keypair | null;
28
+ suiAddress: string | null;
29
+ zkProof: PartialZkLoginSignature | null;
30
+ maxEpoch?: number | null;
31
+ }
32
+ export type WalletActions = {
33
+ login: (provider: AuthProvider) => Promise<void>;
34
+ disconnect: () => Promise<void>;
35
+ getSigner: () => ZKLoginSignerState | null;
36
+ initFromStorage: () => Promise<void>;
37
+ setError: (err: string | null) => void;
38
+ setLoading: (v: boolean) => void;
39
+ setNetwork: (n: string) => void;
40
+ };
41
+ export type WalletStore = WalletState & WalletActions;
42
+ export type WalletStoreConfig = {
43
+ suiClient: SuiClient;
44
+ oAuthClientId: string;
45
+ network?: string;
46
+ autoInit?: boolean;
47
+ };
48
+ export declare function createWalletStore(config: WalletStoreConfig): StoreApi<WalletStore>;