@zing-protocol/zing-sdk 0.0.5 → 0.0.6

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.
@@ -11,15 +11,13 @@ interface Params {
11
11
  network: SuiNetwork;
12
12
  suiGrpcClient: SuiGrpcClient;
13
13
  suiJsonRpcClient: SuiJsonRpcClient;
14
- gasPoolBearerToken: string;
15
14
  }
16
15
  export declare class ZingClient {
17
16
  suiGrpcClient: SuiGrpcClient;
18
17
  suiJsonRpcClient: SuiJsonRpcClient;
19
18
  network: SuiNetwork;
20
19
  config: Config;
21
- gasPoolBearerToken: string;
22
- constructor({ network, suiGrpcClient, suiJsonRpcClient, gasPoolBearerToken, }: Params);
20
+ constructor({ network, suiGrpcClient, suiJsonRpcClient }: Params);
23
21
  getConfig(): Config;
24
22
  getDerivedStudioID(address: string): string;
25
23
  getDerivedStorageID(address: string): string;
@@ -199,14 +197,48 @@ export declare class ZingClient {
199
197
  nextCursor: string | undefined;
200
198
  hasNextPage: boolean;
201
199
  }>;
200
+ getWorksByObjectIds(owner: string, workObjectIds: string[], workType?: WorkType): Promise<{
201
+ id: {
202
+ id: string;
203
+ };
204
+ owner: string;
205
+ deleted: boolean;
206
+ created_at: string;
207
+ subscription_level: number | null;
208
+ blobs: {
209
+ id: {
210
+ id: string;
211
+ };
212
+ registered_epoch: number;
213
+ blob_id: string;
214
+ size: string;
215
+ encoding_type: number;
216
+ certified_epoch: number | null;
217
+ storage: {
218
+ id: {
219
+ id: string;
220
+ };
221
+ start_epoch: number;
222
+ end_epoch: number;
223
+ storage_size: string;
224
+ };
225
+ deletable: boolean;
226
+ }[];
227
+ files: {
228
+ contents: {
229
+ key: string;
230
+ value: {
231
+ blob_index: string;
232
+ mime_type: string;
233
+ size: string;
234
+ };
235
+ }[];
236
+ };
237
+ }[]>;
202
238
  getBalance(owner: string, coinSymbol: CoinSymbol): Promise<import("node_modules/@mysten/sui/dist/esm/grpc/proto/sui/rpc/v2/state_service.js").GetBalanceResponse>;
203
239
  getSessionKey(signer: ZKLoginSignerState, owner: string): Promise<SessionKey>;
204
240
  buildSealApproveTransactionBytes(owner: string): Promise<Uint8Array<ArrayBuffer>>;
205
241
  getFileKey(sealClient: SealClient, sessionKey: SessionKey, owner: string, encryptedFileKeyBytes: number[]): Promise<CryptoKey>;
206
- /**
207
- * Constructs the transaction for subscribing to a studio.
208
- * Does not execute; returns the Transaction object to be signed.
209
- */
210
242
  subscribeToStudioTransaction({ sender, creatorAddress, subscriptionAmount, level, }: SubscribeParams): (tx: Transaction) => void;
211
243
  purchaseStorageTierTransaction({ sender, objs, newTierIdx, balance, referrer, }: PurchaseStorageTierParams): (tx: Transaction) => void;
212
244
  setMonthlySubscriptionFeeTransaction({ sender, monthlyFee, level, }: SetMonthlySubscriptionFeeParams): (tx: Transaction) => void;
@@ -4,19 +4,18 @@ import { addReferralToStudio } from "../_generated/zing_studio/referral.js";
4
4
  import { shareStorageSpace } from "../_generated/zing_studio/storage.js";
5
5
  import { _new as newStudio, sealApproveStudioOwner, shareStudio, } from "../_generated/zing_studio/studio.js";
6
6
  import { getConfig } from "../config/index.js";
7
- import { getDerivedMembershipID, getDerivedStorageID, getDerivedStudioID, getDerivedWorksID, getIdentifierByAddress, getIdentifierInfoByIdentifier, getMember, getMembers, getStorageSpace, getStorageTreasury, getStudio, getWork, getWorks, } from "../getters.js";
7
+ import { getDerivedMembershipID, getDerivedStorageID, getDerivedStudioID, getDerivedWorksID, getIdentifierByAddress, getIdentifierInfoByIdentifier, getMember, getMembers, getStorageSpace, getStorageTreasury, getStudio, getWork, getWorks, getWorksByObjectIds, } from "../getters.js";
8
8
  import { importFileKey } from "../mutations/seal.js";
9
9
  import { signPersonalMessage } from "../mutations/signer.js";
10
10
  import { SessionKey } from "@mysten/seal";
11
11
  import { Transaction, coinWithBalance } from "@mysten/sui/transactions";
12
12
  import { fromHex } from "@mysten/sui/utils";
13
13
  export class ZingClient {
14
- constructor({ network, suiGrpcClient, suiJsonRpcClient, gasPoolBearerToken, }) {
14
+ constructor({ network, suiGrpcClient, suiJsonRpcClient }) {
15
15
  this.suiGrpcClient = suiGrpcClient;
16
16
  this.suiJsonRpcClient = suiJsonRpcClient;
17
17
  this.network = network || "testnet";
18
18
  this.config = getConfig(network);
19
- this.gasPoolBearerToken = gasPoolBearerToken;
20
19
  }
21
20
  getConfig() {
22
21
  return this.config;
@@ -82,6 +81,9 @@ export class ZingClient {
82
81
  async getWorks(owner, workType, cursor, limit = 20) {
83
82
  return getWorks(this.suiGrpcClient, this.getDerivedWorksID(owner), workType ? this.config.zing.ZING_WORKS_TYPE[workType] : undefined, cursor, limit);
84
83
  }
84
+ async getWorksByObjectIds(owner, workObjectIds, workType) {
85
+ return getWorksByObjectIds(this.suiGrpcClient, workObjectIds, workType ? this.config.zing.ZING_WORKS_TYPE[workType] : undefined);
86
+ }
85
87
  async getBalance(owner, coinSymbol) {
86
88
  return this.suiGrpcClient.stateService
87
89
  .getBalance({
@@ -137,10 +139,6 @@ export class ZingClient {
137
139
  return await importFileKey(decryptedKey);
138
140
  }
139
141
  // --- Transaction Builders ---
140
- /**
141
- * Constructs the transaction for subscribing to a studio.
142
- * Does not execute; returns the Transaction object to be signed.
143
- */
144
142
  subscribeToStudioTransaction({ sender, creatorAddress, subscriptionAmount, level, }) {
145
143
  return (tx) => {
146
144
  const usdcCoin = tx.add(coinWithBalance({
@@ -22,7 +22,7 @@ export declare function useWalrusUpload(): (zingClient: ZingClient, fileKey: Cry
22
22
  "content-type": string;
23
23
  };
24
24
  size: number;
25
- }[], signer: ZKLoginSignerState, gasPoolBearerToken: string, onProgress?: (stage: WalrusUploadFlowStage) => void) => Promise<typeof PublishArticleEvent.$inferType>;
25
+ }[], signer: ZKLoginSignerState, onProgress?: (stage: WalrusUploadFlowStage) => void) => Promise<typeof PublishArticleEvent.$inferType>;
26
26
  export declare function useWalrusQuiltSize(): (walrusSystem: WalrusSystemState, files: Array<{
27
27
  size: number;
28
28
  identifier: string;
@@ -27,7 +27,7 @@ export const WalrusProvider = ({ walrusClient, sealClient, children, autoInit =
27
27
  }
28
28
  // eslint-disable-next-line react-hooks/exhaustive-deps
29
29
  }, [store]);
30
- const uploadFile = useCallback(async (zingClient, fileKey, walrusSystem, walTreasury, storageByEpoch, walrusFiles, subscriptionLevel, metadata, signer, gasPoolBearerToken, onProgress) => {
30
+ const uploadFile = useCallback(async (zingClient, fileKey, walrusSystem, walTreasury, storageByEpoch, walrusFiles, subscriptionLevel, metadata, signer, onProgress) => {
31
31
  const config = zingClient.config;
32
32
  return uploadFileToWalrus({
33
33
  zingStudioPackageId: config.zing.ZING_STUDIO_PACKAGE_ADDRESS,
@@ -38,7 +38,7 @@ export const WalrusProvider = ({ walrusClient, sealClient, children, autoInit =
38
38
  zingStorageTreasurySharedObjectRef: config.zing.ZING_STORAGE_TREASURY_SHARED_OBJECT_REF,
39
39
  blobRegisteredEventType: config.walrus.EVENT_TYPES.blobRegistered,
40
40
  publishArticleEventType: config.zing.EVENT_TYPES.publishArticleEvent,
41
- }, zingClient.suiGrpcClient, zingClient.suiJsonRpcClient, walrusClient, walrusSystem, walTreasury, storageByEpoch, fileKey, walrusFiles, subscriptionLevel, metadata, signer, gasPoolBearerToken, onProgress);
41
+ }, zingClient.suiGrpcClient, zingClient.suiJsonRpcClient, walrusClient, walrusSystem, walTreasury, storageByEpoch, fileKey, walrusFiles, subscriptionLevel, metadata, signer, onProgress);
42
42
  }, [walrusClient]);
43
43
  const calculateQuiltSize = useCallback((walrusSystem, files, ivSize = 12) => {
44
44
  const numShards = walrusSystem.committee.n_shards;
@@ -7,7 +7,6 @@ interface ZingClientProviderProps {
7
7
  network: SuiNetwork;
8
8
  suiGrpcClient: SuiGrpcClient;
9
9
  suiJsonRpcClient: SuiJsonRpcClient;
10
- gasPoolBearerToken: string;
11
10
  children: ReactNode;
12
11
  }
13
12
  export declare const ZingClientProvider: React.FC<ZingClientProviderProps>;
@@ -4,13 +4,12 @@ import { createContext, useContext, useMemo } from "react";
4
4
  const ZingClientContext = createContext({
5
5
  client: null,
6
6
  });
7
- export const ZingClientProvider = ({ network, suiGrpcClient, suiJsonRpcClient, children, gasPoolBearerToken, }) => {
7
+ export const ZingClientProvider = ({ network, suiGrpcClient, suiJsonRpcClient, children, }) => {
8
8
  const client = useMemo(() => new ZingClient({
9
9
  network,
10
10
  suiGrpcClient,
11
11
  suiJsonRpcClient,
12
- gasPoolBearerToken,
13
- }), [network, suiGrpcClient, suiJsonRpcClient, gasPoolBearerToken]);
12
+ }), [network, suiGrpcClient, suiJsonRpcClient]);
14
13
  return (_jsx(ZingClientContext.Provider, { value: { client }, children: children }));
15
14
  };
16
15
  export const useZingClient = () => {
@@ -17,7 +17,7 @@ export type ProviderInfo = {
17
17
  };
18
18
  export declare const PLATFORM_PROVIDER_INFO: Record<PlatformType, ProviderInfo>;
19
19
  export declare const PLATFORMS_HOSTNAME: Record<PlatformType, string>;
20
- export declare const LEVEL_FEATURES: Record<number, {
21
- name: string;
22
- features: string[];
20
+ export declare const MEMBERSHIP_LEVELS: Record<number, {
21
+ nameKey: string;
22
+ featureKeys: string[];
23
23
  }>;
@@ -43,19 +43,26 @@ export const PLATFORMS_HOSTNAME = {
43
43
  // substack: 'https://substack.com',
44
44
  // instagram: 'https://www.instagram.com',
45
45
  };
46
- export const LEVEL_FEATURES = {
47
- 0: { name: "Supporter", features: ["Basic Support", "Standard Features"] },
46
+ export const MEMBERSHIP_LEVELS = {
47
+ 0: {
48
+ nameKey: "membershipTier.0.name",
49
+ featureKeys: ["membershipTier.0.features.0", "membershipTier.0.features.1"],
50
+ },
48
51
  1: {
49
- name: "Premium",
50
- features: ["Priority Support", "Advanced Features", "Analytics"],
52
+ nameKey: "membershipTier.1.name",
53
+ featureKeys: [
54
+ "membershipTier.1.features.0",
55
+ "membershipTier.1.features.1",
56
+ "membershipTier.1.features.2",
57
+ ],
51
58
  },
52
59
  2: {
53
- name: "VIP",
54
- features: [
55
- "24/7 Support",
56
- "All Features",
57
- "Custom Integration",
58
- "White Label",
60
+ nameKey: "membershipTier.2.name",
61
+ featureKeys: [
62
+ "membershipTier.2.features.0",
63
+ "membershipTier.2.features.1",
64
+ "membershipTier.2.features.2",
65
+ "membershipTier.2.features.3",
59
66
  ],
60
67
  },
61
68
  };
package/dist/getters.d.ts CHANGED
@@ -188,6 +188,44 @@ export declare function getWorks(suiGrpcClient: SuiGrpcClient, workTableId: stri
188
188
  nextCursor: string | undefined;
189
189
  hasNextPage: boolean;
190
190
  }>;
191
+ export declare function getWorksByObjectIds(suiGrpcClient: SuiGrpcClient, workObjectIds: string[], workType?: string): Promise<{
192
+ id: {
193
+ id: string;
194
+ };
195
+ owner: string;
196
+ deleted: boolean;
197
+ created_at: string;
198
+ subscription_level: number | null;
199
+ blobs: {
200
+ id: {
201
+ id: string;
202
+ };
203
+ registered_epoch: number;
204
+ blob_id: string;
205
+ size: string;
206
+ encoding_type: number;
207
+ certified_epoch: number | null;
208
+ storage: {
209
+ id: {
210
+ id: string;
211
+ };
212
+ start_epoch: number;
213
+ end_epoch: number;
214
+ storage_size: string;
215
+ };
216
+ deletable: boolean;
217
+ }[];
218
+ files: {
219
+ contents: {
220
+ key: string;
221
+ value: {
222
+ blob_index: string;
223
+ mime_type: string;
224
+ size: string;
225
+ };
226
+ }[];
227
+ };
228
+ }[]>;
191
229
  export declare function getPublishedArticleAndBlobId(suiGrpcClient: SuiGrpcClient, suiClient: SuiJsonRpcClient, walrusClient: WalrusClient, digest: string, blobRegisteredEventType: string, publishArticleEventType: string): Promise<{
192
230
  parsedPublishArticleEvent: {
193
231
  article_id: string;
package/dist/getters.js CHANGED
@@ -218,6 +218,26 @@ export async function getWorks(suiGrpcClient, workTableId, workType, cursor, lim
218
218
  hasNextPage: res.response.nextPageToken !== undefined,
219
219
  };
220
220
  }
221
+ export async function getWorksByObjectIds(suiGrpcClient, workObjectIds, workType) {
222
+ const res = await suiGrpcClient.ledgerService.batchGetObjects({
223
+ requests: workObjectIds.map((id) => ({ objectId: id })),
224
+ readMask: {
225
+ paths: ["bcs"],
226
+ },
227
+ });
228
+ const suiMoveObjects = [];
229
+ res.response.objects.forEach((obj) => {
230
+ if (obj.result.oneofKind === "object" && obj.result.object.bcs?.value) {
231
+ const suiMoveObject = SuiMoveObject.parse(obj.result.object.bcs.value);
232
+ const type = suiMoveObject.data.MoveObject
233
+ .type;
234
+ const workType_ = normalizeStructTag(type.Other);
235
+ if (type.$kind === "Other" && workType_ === workType)
236
+ suiMoveObjects.push(suiMoveObject);
237
+ }
238
+ });
239
+ return suiMoveObjects.map((obj) => Article.parse(obj.data.MoveObject.contents));
240
+ }
221
241
  export async function getPublishedArticleAndBlobId(suiGrpcClient, suiClient, walrusClient, digest, blobRegisteredEventType, publishArticleEventType) {
222
242
  // suiGrpcClient waitForTransaction calling core.getTransaction which is broken
223
243
  await suiClient.waitForTransaction({
@@ -294,14 +314,6 @@ export function encodedSliverSize(unencodedLength, nShards, encodingType = "RS2"
294
314
  symbolSize = symbolSize + 1;
295
315
  }
296
316
  const singleShardSize = (primarySymbols + secondarySymbols) * symbolSize;
297
- console.log("encodedSliverSize breakdown:", {
298
- unencodedLength,
299
- primarySymbols,
300
- secondarySymbols,
301
- calculatedSymbolSize: symbolSize,
302
- singleShardSize,
303
- totalSliverSize: singleShardSize * nShards,
304
- });
305
317
  return singleShardSize * nShards;
306
318
  }
307
319
  export function encodedBlobLength(unencodedLength, nShards, encodingType = "RS2") {
@@ -5,7 +5,6 @@ export * from "./useZingMutation.js";
5
5
  export * from "./useZingQuery.js";
6
6
  export * from "./useZingQueries.js";
7
7
  export * from "./useZingInfiniteQueries.js";
8
- export * from "./useGetTierPlan.js";
9
8
  export * from "./useSignPersonalMessage.js";
10
9
  export type InfiniteQueryResult<TData> = {
11
10
  pages: TData[];
@@ -5,5 +5,4 @@ export * from "./useZingMutation.js";
5
5
  export * from "./useZingQuery.js";
6
6
  export * from "./useZingQueries.js";
7
7
  export * from "./useZingInfiniteQueries.js";
8
- export * from "./useGetTierPlan.js";
9
8
  export * from "./useSignPersonalMessage.js";
@@ -6,7 +6,6 @@ interface CommitProofParams {
6
6
  walletAddress: string;
7
7
  platform: PlatformType;
8
8
  proof: ReclaimProof;
9
- gasPoolBearerToken: string;
10
9
  }
11
10
  export declare function useCommitProof(): import("@tanstack/react-query").UseMutationResult<any, Error, CommitProofParams, unknown>;
12
11
  export {};
@@ -11,7 +11,7 @@ export function useCommitProof() {
11
11
  const zingClient = useZingClient();
12
12
  const config = zingClient.config;
13
13
  return useMutation({
14
- mutationFn: async ({ suiClient, walletAddress, platform, proof, gasPoolBearerToken, }) => {
14
+ mutationFn: async ({ suiClient, walletAddress, platform, proof, }) => {
15
15
  const nonce = generateCommitNonce(walletAddress, proof.identifier);
16
16
  const commitmentHash = generateCommitmentHash(proof, nonce);
17
17
  const identifierHash = hexToBytes(sha3.keccak256(textToBytes(proof.identifier)));
@@ -65,7 +65,6 @@ export function useCommitProof() {
65
65
  nonce: revealTransaction.pure(bcs.vector(bcs.u8()).serialize(nonce)),
66
66
  },
67
67
  }));
68
- console.log({ signers });
69
68
  // Call extract parameters customizaed functions; this interface should identical for different platforms
70
69
  revealTransaction.moveCall({
71
70
  target: identityPlatform.PLATFORM_UPDATE_PROOF_TARGET,
@@ -80,7 +79,6 @@ export function useCommitProof() {
80
79
  const transactionResponse = await signAndExecuteTransaction({
81
80
  transaction: revealTransaction,
82
81
  });
83
- console.log({ transactionResponse });
84
82
  return transactionResponse;
85
83
  },
86
84
  });
@@ -33,7 +33,7 @@ export const useSignAndExecuteTransaction = () => {
33
33
  }
34
34
  },
35
35
  onError: (error, variables) => {
36
- console.log({ transaction: variables.transaction });
36
+ console.error("Transaction Variables", variables);
37
37
  console.error("Transaction execution failed:", error);
38
38
  },
39
39
  });
@@ -66,7 +66,7 @@ type UseZingInfiniteQueryParams<K extends keyof InfiniteMethodParamsMap> = {
66
66
  params: InfiniteMethodParamsMap[K];
67
67
  limit?: number;
68
68
  };
69
- type ExtraInfiniteQueryOptions<TData = unknown> = Partial<Pick<UseInfiniteQueryOptions<TData, Error, InfiniteData<TData>, readonly unknown[], string | undefined>, "enabled" | "gcTime" | "staleTime" | "retry">>;
69
+ type ExtraInfiniteQueryOptions<TData = unknown> = Partial<Pick<UseInfiniteQueryOptions<TData, Error, InfiniteData<TData>, readonly unknown[], string | undefined>, "enabled" | "gcTime" | "staleTime" | "retry" | "refetchOnWindowFocus" | "refetchOnReconnect" | "refetchOnMount">>;
70
70
  export type InfiniteMethodReturnMap = {
71
71
  [K in keyof ZingInfiniteQueryMethods]: UnwrapPromise<ExtractReturnType<ZingInfiniteQueryMethods[K]>>;
72
72
  };
@@ -1,10 +1,7 @@
1
1
  import type { ExcludeValuesFromBaseArrayType } from "./types.js";
2
2
  export declare const excludeValuesFromBaseArray: <B extends string[], E extends (string | number)[]>(baseArray: B, excludeArray: E) => ExcludeValuesFromBaseArrayType<B, E>;
3
3
  export declare const sleep: (time: number) => Promise<unknown>;
4
- export declare const formatDate: (date: Date) => string;
5
4
  export declare const formatBalance: (balance: string | number | bigint, decimal: number, digits?: number) => string;
6
- export declare const formatTimeAgo: (date: Date) => string;
7
- export declare function formatDaysAuto(days: number): string;
8
5
  export declare const formatBytes: (bytes: number) => string;
9
6
  export declare const getDaysRemaining: (comp: number) => number;
10
7
  export declare const bytesToGB: (bytes: number) => number;
@@ -1,44 +1,20 @@
1
1
  export const excludeValuesFromBaseArray = (baseArray, excludeArray) => baseArray.filter((value) => !excludeArray.includes(value));
2
2
  export const sleep = async (time) => new Promise((r) => setTimeout(r, time));
3
- export const formatDate = (date) => date.toLocaleDateString("en-US", {
4
- year: "numeric",
5
- month: "short",
6
- day: "numeric",
7
- });
8
3
  export const formatBalance = (balance, decimal, digits = 4) => {
9
4
  const normalizedBalance = Number(balance) / Math.pow(10, decimal);
10
5
  const fixed = normalizedBalance.toFixed(digits);
11
6
  return fixed.replace(/\.?0+$/, "");
12
7
  };
13
- export const formatTimeAgo = (date) => {
14
- const now = new Date();
15
- const diffInHours = Math.floor((now.getTime() - date.getTime()) / (1000 * 60 * 60));
16
- if (diffInHours < 1)
17
- return "Just now";
18
- if (diffInHours < 24)
19
- return `${diffInHours}h ago`;
20
- if (diffInHours < 168)
21
- return `${Math.floor(diffInHours / 24)}d ago`;
22
- return formatDate(date);
23
- };
24
- export function formatDaysAuto(days) {
25
- if (days < 30)
26
- return `${days} day${days === 1 ? "" : "s"}`;
27
- const months = days / 30;
28
- if (months < 12) {
29
- const rounded = Math.floor(months);
30
- return `${rounded} month${rounded === 1 ? "" : "s"}`;
31
- }
32
- const years = Math.floor(days / 365);
33
- return `${years} year${years === 1 ? "" : "s"}`;
34
- }
35
8
  export const formatBytes = (bytes) => {
36
- if (bytes === 0)
37
- return "0 B";
38
- const k = 1024;
39
- const sizes = ["B", "KB", "MB", "GB", "TB"];
40
- const i = Math.floor(Math.log(bytes) / Math.log(k));
41
- return `${(bytes / Math.pow(k, i)).toFixed(2)} ${sizes[i]}`;
9
+ // 62.97 MB base (62.97 * 1024 * 1024)
10
+ const BASE_UNIT_BYTES = 66028830.72;
11
+ if (!bytes || bytes <= 0)
12
+ return "0";
13
+ const points = bytes / BASE_UNIT_BYTES;
14
+ return new Intl.NumberFormat("en-US", {
15
+ minimumFractionDigits: 0,
16
+ maximumFractionDigits: 2,
17
+ }).format(points);
42
18
  };
43
19
  export const getDaysRemaining = (comp) => {
44
20
  const now = new Date();
@@ -28,7 +28,6 @@ export async function startVerification({ reclaimAppId, reclaimAppSecret, reclai
28
28
  const proofs = await new Promise((resolve, reject) => {
29
29
  reclaimProofRequest.startSession({
30
30
  onSuccess: (proofs) => {
31
- console.log("Verification successful:", proofs);
32
31
  resolve(proofs);
33
32
  },
34
33
  onError: (error) => {
@@ -35,7 +35,6 @@ export async function decryptData(key, encrypted) {
35
35
  const bytes = encrypted instanceof Uint8Array ? encrypted : new Uint8Array(encrypted);
36
36
  const iv = bytes.slice(0, 12);
37
37
  const ciphertext = bytes.slice(12);
38
- console.log({ iv, ciphertext });
39
38
  const plaintext = await crypto.subtle.decrypt({ name: "AES-GCM", iv }, key, ciphertext);
40
39
  return new Uint8Array(plaintext);
41
40
  }
@@ -2,7 +2,9 @@ import { zkloginStorage } from "../stores/zkloginStore.js";
2
2
  import { Ed25519Keypair } from "@mysten/sui/keypairs/ed25519";
3
3
  import { fromBase64 } from "@mysten/sui/utils";
4
4
  import { decodeJwt } from "@mysten/sui/zklogin";
5
- const SALT_SERVER_BASE_URL = "https://salt-server-production.up.railway.app";
5
+ const SALT_SERVER_BASE_URL =
6
+ // "https://salt-server-production.up.railway.app";
7
+ "http://localhost:3001";
6
8
  export async function getSigner(suiClient) {
7
9
  const zkLoginStorage = await zkloginStorage.getState();
8
10
  const { epoch: currentEpoch } = await suiClient.getLatestSuiSystemState();
@@ -14,6 +16,7 @@ export async function getSigner(suiClient) {
14
16
  return {
15
17
  ephemeralKeyPair: null,
16
18
  suiAddress: null,
19
+ jwtTokenString: null,
17
20
  decodedJwt: null,
18
21
  zkProof: null,
19
22
  maxEpoch: null,
@@ -22,6 +25,7 @@ export async function getSigner(suiClient) {
22
25
  return {
23
26
  ephemeralKeyPair: null,
24
27
  suiAddress: null,
28
+ jwtTokenString: null,
25
29
  decodedJwt: null,
26
30
  zkProof: null,
27
31
  maxEpoch: null,
@@ -30,13 +34,14 @@ export async function getSigner(suiClient) {
30
34
  return {
31
35
  suiAddress: zkLoginStorage.suiAddress,
32
36
  ephemeralKeyPair,
37
+ jwtTokenString: zkLoginStorage.jwt,
33
38
  decodedJwt: decodeJwt(zkLoginStorage.jwt),
34
39
  zkProof: JSON.parse(zkLoginStorage.zkProof),
35
40
  maxEpoch: zkLoginStorage.maxEpoch,
36
41
  };
37
42
  }
38
43
  export async function signAndExecuteGasPoolTransaction(signer, suiClient, tx, gasBudget = 0.1 * 10 ** 9, reserveDurationSecs = 30) {
39
- const { ephemeralKeyPair, suiAddress, decodedJwt, zkProof, maxEpoch } = signer;
44
+ const { ephemeralKeyPair, suiAddress, decodedJwt, zkProof, maxEpoch, jwtTokenString, } = signer;
40
45
  if (!ephemeralKeyPair || !suiAddress || !decodedJwt || !zkProof || !maxEpoch)
41
46
  return;
42
47
  try {
@@ -47,12 +52,10 @@ export async function signAndExecuteGasPoolTransaction(signer, suiClient, tx, ga
47
52
  const prepareResponse = await fetch(`${SALT_SERVER_BASE_URL}/prepare_tx`, {
48
53
  method: "POST",
49
54
  headers: {
55
+ Authorization: `Bearer ${jwtTokenString}`,
50
56
  "Content-Type": "application/json",
51
57
  },
52
58
  body: JSON.stringify({
53
- sub: decodedJwt.sub,
54
- iss: decodedJwt.iss,
55
- aud: Array.isArray(decodedJwt.aud) ? decodedJwt.aud[0] : decodedJwt.aud,
56
59
  gasBudget,
57
60
  reserveDurationSecs,
58
61
  }),
@@ -78,12 +81,10 @@ export async function signAndExecuteGasPoolTransaction(signer, suiClient, tx, ga
78
81
  const executeResponse = await fetch(`${SALT_SERVER_BASE_URL}/execute_tx`, {
79
82
  method: "POST",
80
83
  headers: {
84
+ Authorization: `Bearer ${jwtTokenString}`,
81
85
  "Content-Type": "application/json",
82
86
  },
83
87
  body: JSON.stringify({
84
- sub: decodedJwt.sub,
85
- iss: decodedJwt.iss,
86
- aud: Array.isArray(decodedJwt.aud) ? decodedJwt.aud[0] : decodedJwt.aud,
87
88
  reservationId: prepareData.result.reservation_id,
88
89
  txBytes: bytes,
89
90
  ephemeralSignature,
@@ -106,13 +107,13 @@ export async function signAndExecuteGasPoolTransaction(signer, suiClient, tx, ga
106
107
  }
107
108
  }
108
109
  export async function signPersonalMessage(signer, message) {
109
- const { ephemeralKeyPair, decodedJwt, zkProof, maxEpoch } = signer;
110
+ const { ephemeralKeyPair, decodedJwt, zkProof, maxEpoch, jwtTokenString } = signer;
110
111
  if (!ephemeralKeyPair || !decodedJwt || !zkProof || !maxEpoch) {
111
112
  throw new Error("Missing required params");
112
113
  }
113
114
  try {
114
- if (!decodedJwt.sub || !decodedJwt.iss || !decodedJwt.aud) {
115
- throw new Error("JWT claims (sub, iss, aud) not found");
115
+ if (!jwtTokenString) {
116
+ throw new Error("jwtTokenString not found");
116
117
  }
117
118
  // Sign message with ephemeral key
118
119
  const { bytes, signature } = await ephemeralKeyPair.signPersonalMessage(message);
@@ -120,14 +121,10 @@ export async function signPersonalMessage(signer, message) {
120
121
  const response = await fetch(`${SALT_SERVER_BASE_URL}/sign_personal_message`, {
121
122
  method: "POST",
122
123
  headers: {
124
+ Authorization: `Bearer ${jwtTokenString}`,
123
125
  "Content-Type": "application/json",
124
126
  },
125
127
  body: JSON.stringify({
126
- sub: decodedJwt.sub,
127
- iss: decodedJwt.iss,
128
- aud: Array.isArray(decodedJwt.aud)
129
- ? decodedJwt.aud[0]
130
- : decodedJwt.aud,
131
128
  messageBytes: bytes,
132
129
  ephemeralSignature: signature,
133
130
  maxEpoch,
@@ -157,9 +154,14 @@ export async function createZkLoginProof(params) {
157
154
  const response = await fetch(`${SALT_SERVER_BASE_URL}/zklogin-proof`, {
158
155
  method: "POST",
159
156
  headers: {
157
+ Authorization: `Bearer ${params.jwtTokenString}`,
160
158
  "Content-Type": "application/json",
161
159
  },
162
- body: JSON.stringify(params),
160
+ body: JSON.stringify({
161
+ maxEpoch: params.maxEpoch,
162
+ extendedEphemeralPublicKey: params.extendedEphemeralPublicKey,
163
+ jwtRandomness: params.jwtRandomness,
164
+ }),
163
165
  });
164
166
  if (!response.ok) {
165
167
  const errorData = await response.json().catch(() => ({}));
@@ -69,7 +69,7 @@ export declare function uploadFileToWalrus(zingWriteFlowConfig: ZingWriteFlowCon
69
69
  "content-type": string;
70
70
  };
71
71
  size: number;
72
- }[], signer: ZKLoginSignerState, gasPoolBearerToken: string, onProgress?: (stage: WalrusUploadFlowStage) => void): Promise<typeof PublishArticleEvent.$inferType>;
72
+ }[], signer: ZKLoginSignerState, onProgress?: (stage: WalrusUploadFlowStage) => void): Promise<typeof PublishArticleEvent.$inferType>;
73
73
  export declare function downloadImagesFromMarkdown<T extends "blob" | "uint8array">(markdown: string, as?: T): Promise<{
74
74
  url: string;
75
75
  data: T extends "blob" ? Blob : Uint8Array;
@@ -17,7 +17,6 @@ export function buildPublishArticleTransaction(config, walrusSystem, walTreasury
17
17
  const { zingStudioPackageId, walrusPackageId, zingStudioConfigSharedObjectRef, walrusSystemSharedObjectRef, zingStorageTreasurySharedObjectRef, } = config;
18
18
  return (tx) => {
19
19
  const { encodedSize, writeCost } = storageCost(walrusSystem, fileSize, 2);
20
- console.log({ encodedSize });
21
20
  const currentEpoch = walrusSystem.committee.epoch;
22
21
  if (!storageByEpoch?.[currentEpoch]) {
23
22
  throw new Error(`No Epochs Found for ${currentEpoch}`);
@@ -34,8 +33,6 @@ export function buildPublishArticleTransaction(config, walrusSystem, walTreasury
34
33
  if (BigInt(walTreasury) < writeCost) {
35
34
  throw new Error(`Insufficient walTreasury Balance ${walTreasury} for writeCost: ${writeCost}`);
36
35
  }
37
- console.log({ fileSize, encodedSize });
38
- console.log({ articleMetadata });
39
36
  const [article, publishReceipt] = tx.add(startPublishArticle({
40
37
  package: zingStudioPackageId,
41
38
  arguments: {
@@ -148,8 +145,6 @@ export const zingWriteFlow = (config, suiGrpcClient, suiJsonRpcClient, walrusCli
148
145
  };
149
146
  })),
150
147
  });
151
- console.log({ walrus_system: await walrusClient.systemState() });
152
- console.log({ quiltlength: quilt.length });
153
148
  // store encryptedBytes
154
149
  const metadata = withUploadRelayClient
155
150
  ? await walrusClient.computeBlobMetadata({
@@ -176,7 +171,6 @@ export const zingWriteFlow = (config, suiGrpcClient, suiJsonRpcClient, walrusCli
176
171
  }
177
172
  // 1. rent storage space and publish article
178
173
  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
174
  return {
181
175
  registerTransaction: transaction,
182
176
  index,
@@ -226,7 +220,6 @@ export const zingWriteFlow = (config, suiGrpcClient, suiJsonRpcClient, walrusCli
226
220
  };
227
221
  };
228
222
  const certify = ({ index, metadata, confirmations, certificate, articleId, blobObjectId, deletable, }) => {
229
- console.log({ confirmations });
230
223
  const tx = new Transaction();
231
224
  if (confirmations) {
232
225
  tx.add(buildCertifyArticleBlobTransaction({
@@ -302,7 +295,7 @@ export const zingWriteFlow = (config, suiGrpcClient, suiJsonRpcClient, walrusCli
302
295
  listFiles: async () => listFiles(getResults("certify", "listFiles")),
303
296
  };
304
297
  };
305
- export async function uploadFileToWalrus(zingWriteFlowConfig, suiGrpcClient, suiJsonRpcClient, walrusClient, walrusSystem, walTreasury, storageByEpoch, fileKey, walrusFiles, subscriptionLevel, metadata, signer, gasPoolBearerToken, onProgress) {
298
+ export async function uploadFileToWalrus(zingWriteFlowConfig, suiGrpcClient, suiJsonRpcClient, walrusClient, walrusSystem, walTreasury, storageByEpoch, fileKey, walrusFiles, subscriptionLevel, metadata, signer, onProgress) {
306
299
  const report = (stage) => {
307
300
  if (onProgress)
308
301
  onProgress(stage);
@@ -21,7 +21,7 @@ export interface WalletState {
21
21
  account: WalletAccount | null;
22
22
  error: string | null;
23
23
  network: string;
24
- jwt: string | null;
24
+ jwtTokenString: string | null;
25
25
  decodedJwt: ReturnType<typeof decodeJwt> | null;
26
26
  authProvider: AuthProvider | null;
27
27
  ephemeralKeyPair: Ed25519Keypair | null;
@@ -15,7 +15,7 @@ export function createWalletStore(config) {
15
15
  account: null,
16
16
  error: null,
17
17
  network,
18
- jwt: null,
18
+ jwtTokenString: null,
19
19
  decodedJwt: null,
20
20
  authProvider: null,
21
21
  ephemeralKeyPair: null,
@@ -115,7 +115,7 @@ export function createWalletStore(config) {
115
115
  zkloginStorage.getState().setMaxEpoch(maxEpoch);
116
116
  const extendedEphemeralPublicKey = getExtendedEphemeralPublicKey(ephemeralKeyPair.getPublicKey());
117
117
  const zkProofResponse = await createZkLoginProof({
118
- jwt: idToken,
118
+ jwtTokenString: idToken,
119
119
  maxEpoch: String(maxEpoch),
120
120
  extendedEphemeralPublicKey,
121
121
  jwtRandomness: randomness,
@@ -129,7 +129,7 @@ export function createWalletStore(config) {
129
129
  zkloginStorage.getState().setSuiAddress(suiAddress);
130
130
  const account = { jwt: decoded };
131
131
  set({
132
- jwt: idToken,
132
+ jwtTokenString: idToken,
133
133
  decodedJwt: decoded,
134
134
  ephemeralKeyPair,
135
135
  suiAddress,
@@ -155,7 +155,7 @@ export function createWalletStore(config) {
155
155
  // ignore storage errors
156
156
  }
157
157
  set({
158
- jwt: null,
158
+ jwtTokenString: null,
159
159
  decodedJwt: null,
160
160
  ephemeralKeyPair: null,
161
161
  suiAddress: null,
@@ -169,13 +169,14 @@ export function createWalletStore(config) {
169
169
  });
170
170
  },
171
171
  getSigner() {
172
- const { jwt, maxEpoch, ephemeralKeyPair, zkProof, suiAddress, decodedJwt, } = get();
172
+ const { jwtTokenString: jwt, maxEpoch, ephemeralKeyPair, zkProof, suiAddress, decodedJwt, } = get();
173
173
  if (!jwt || !maxEpoch || !ephemeralKeyPair || !zkProof)
174
174
  return null;
175
175
  return {
176
176
  ephemeralKeyPair,
177
177
  suiAddress,
178
178
  decodedJwt,
179
+ jwtTokenString: jwt,
179
180
  zkProof,
180
181
  maxEpoch,
181
182
  };
@@ -203,8 +204,10 @@ export function createWalletStore(config) {
203
204
  const ephemeralKeyPair = Ed25519Keypair.fromSecretKey(fromBase64(stored.ephemeralSecretKey));
204
205
  const decoded = decodeJwt(stored.jwt);
205
206
  const zkProofParsed = JSON.parse(stored.zkProof);
207
+ console.log({ decodeJwt: decoded });
208
+ console.log({ zkProofParsed: zkProofParsed });
206
209
  set({
207
- jwt: stored.jwt,
210
+ jwtTokenString: stored.jwt,
208
211
  decodedJwt: decoded,
209
212
  ephemeralKeyPair,
210
213
  suiAddress: stored.suiAddress,
package/dist/types.d.ts CHANGED
@@ -7,6 +7,7 @@ export type PartialZkLoginSignature = Omit<Parameters<typeof getZkLoginSignature
7
7
  export interface ZKLoginSignerState {
8
8
  ephemeralKeyPair: Ed25519Keypair | null;
9
9
  suiAddress: string | null;
10
+ jwtTokenString: string | null;
10
11
  decodedJwt: ReturnType<typeof decodeJwt> | null;
11
12
  zkProof: PartialZkLoginSignature | null;
12
13
  maxEpoch: number | null;
@@ -74,7 +75,7 @@ export interface ExecuteSponsoredTxResponse {
74
75
  }
75
76
  export type PlatformIdentifiers = Record<PlatformType, string>;
76
77
  export interface ZkLoginProofParams {
77
- jwt: string;
78
+ jwtTokenString: string;
78
79
  maxEpoch: string;
79
80
  extendedEphemeralPublicKey: string;
80
81
  jwtRandomness: string;
package/package.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "name": "@zing-protocol/zing-sdk",
3
3
  "sideEffects": false,
4
4
  "type": "module",
5
- "version": "0.0.5",
5
+ "version": "0.0.6",
6
6
  "main": "./dist/index.js",
7
7
  "types": "./dist/index.d.ts",
8
8
  "exports": {
@@ -1,7 +0,0 @@
1
- import type { TierPlan } from "../types.js";
2
- export declare function useGetTierPlan(): {
3
- tierPlans: Record<number, TierPlan>;
4
- storageByEpoch: Record<number, number>;
5
- walTreasury: string;
6
- isLoading: boolean;
7
- };
@@ -1,85 +0,0 @@
1
- import { useZingQuery } from "./useZingQuery.js";
2
- import { useMemo } from "react";
3
- const tierInfos = {
4
- 0: {
5
- name: "Basic",
6
- features: ["Post/Article publishing", "Image protection"],
7
- },
8
- 1: {
9
- name: "Premium",
10
- features: [
11
- "Larger storage size",
12
- "Comments for post",
13
- "Analytics dashboard",
14
- ],
15
- },
16
- // 2: {
17
- // name: "Premium+",
18
- // features: [
19
- // "Advanced publishing",
20
- // "Priority support",
21
- // "Unlimited platforms",
22
- // "Analytics dashboard",
23
- // ],
24
- // },
25
- };
26
- export function useGetTierPlan() {
27
- const { data: storageTreasury, isPending } = useZingQuery({
28
- method: "getStorageTreasury",
29
- params: [],
30
- }, {
31
- staleTime: 0,
32
- refetchOnMount: "always",
33
- refetchOnWindowFocus: false,
34
- });
35
- return useMemo(() => {
36
- if (isPending || !storageTreasury) {
37
- return {
38
- tierPlans: {},
39
- storageByEpoch: {},
40
- walTreasury: "0",
41
- isLoading: isPending,
42
- };
43
- }
44
- if (!storageTreasury.tier_plan ||
45
- !Array.isArray(storageTreasury.tier_plan.contents) ||
46
- storageTreasury.tier_plan.contents.length === 0) {
47
- return {
48
- tierPlans: {},
49
- storageByEpoch: {},
50
- walTreasury: storageTreasury.wal_treasury?.balance?.value || "0",
51
- isLoading: isPending,
52
- };
53
- }
54
- const tierPlans = storageTreasury.tier_plan.contents.reduce((acc, tier) => {
55
- const tierIndex = Number(tier.key);
56
- const info = tierInfos?.[tierIndex];
57
- if (!info) {
58
- return acc;
59
- }
60
- acc[tierIndex] = {
61
- name: info.name,
62
- duration: tier.value.duration_days,
63
- price: Number(tier.value.price),
64
- storage: Number(tier.value.storage_limit),
65
- features: info.features,
66
- };
67
- return acc;
68
- }, {});
69
- // Process storageByEpoch
70
- const storageByEpoch = storageTreasury.storages_by_epoch?.contents?.reduce((acc, storage) => {
71
- const epoch = Number(storage.key);
72
- const size = Number(storage.value.storage_size);
73
- acc[epoch] = size;
74
- return acc;
75
- }, {}) || {};
76
- // Get walTreasury balance
77
- const walTreasury = storageTreasury.wal_treasury?.balance?.value || "0";
78
- return {
79
- tierPlans,
80
- storageByEpoch,
81
- walTreasury,
82
- isLoading: isPending,
83
- };
84
- }, [storageTreasury, isPending]);
85
- }