@mysten/zksend 0.1.1 → 0.2.1

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 (40) hide show
  1. package/CHANGELOG.md +43 -0
  2. package/dist/cjs/channel/events.d.ts +294 -0
  3. package/dist/cjs/channel/events.js +80 -0
  4. package/dist/cjs/channel/events.js.map +7 -0
  5. package/dist/cjs/channel/index.d.ts +38 -0
  6. package/dist/cjs/channel/index.js +172 -0
  7. package/dist/cjs/channel/index.js.map +7 -0
  8. package/dist/cjs/index.d.ts +3 -0
  9. package/dist/cjs/index.js +19 -0
  10. package/dist/cjs/index.js.map +3 -3
  11. package/dist/cjs/links.d.ts +80 -0
  12. package/dist/cjs/links.js +373 -0
  13. package/dist/cjs/links.js.map +7 -0
  14. package/dist/cjs/utils/withResolvers.d.ts +6 -0
  15. package/dist/cjs/utils/withResolvers.js +33 -0
  16. package/dist/cjs/utils/withResolvers.js.map +7 -0
  17. package/dist/cjs/wallet.d.ts +24 -0
  18. package/dist/cjs/wallet.js +227 -0
  19. package/dist/cjs/wallet.js.map +7 -0
  20. package/dist/esm/channel/events.d.ts +294 -0
  21. package/dist/esm/channel/events.js +60 -0
  22. package/dist/esm/channel/events.js.map +7 -0
  23. package/dist/esm/channel/index.d.ts +38 -0
  24. package/dist/esm/channel/index.js +152 -0
  25. package/dist/esm/channel/index.js.map +7 -0
  26. package/dist/esm/index.d.ts +3 -0
  27. package/dist/esm/index.js +3 -9
  28. package/dist/esm/index.js.map +2 -2
  29. package/dist/esm/links.d.ts +80 -0
  30. package/dist/esm/links.js +361 -0
  31. package/dist/esm/links.js.map +7 -0
  32. package/dist/esm/utils/withResolvers.d.ts +6 -0
  33. package/dist/esm/utils/withResolvers.js +13 -0
  34. package/dist/esm/utils/withResolvers.js.map +7 -0
  35. package/dist/esm/wallet.d.ts +24 -0
  36. package/dist/esm/wallet.js +197 -0
  37. package/dist/esm/wallet.js.map +7 -0
  38. package/dist/tsconfig.esm.tsbuildinfo +1 -1
  39. package/dist/tsconfig.tsbuildinfo +1 -1
  40. package/package.json +6 -2
@@ -0,0 +1,152 @@
1
+ var __accessCheck = (obj, member, msg) => {
2
+ if (!member.has(obj))
3
+ throw TypeError("Cannot " + msg);
4
+ };
5
+ var __privateGet = (obj, member, getter) => {
6
+ __accessCheck(obj, member, "read from private field");
7
+ return getter ? getter.call(obj) : member.get(obj);
8
+ };
9
+ var __privateAdd = (obj, member, value) => {
10
+ if (member.has(obj))
11
+ throw TypeError("Cannot add the same private member more than once");
12
+ member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
13
+ };
14
+ var __privateSet = (obj, member, value, setter) => {
15
+ __accessCheck(obj, member, "write to private field");
16
+ setter ? setter.call(obj, value) : member.set(obj, value);
17
+ return value;
18
+ };
19
+ var _id, _origin, _name, _close, _request;
20
+ import { parse, safeParse } from "valibot";
21
+ import { withResolvers } from "../utils/withResolvers.js";
22
+ import { ZkSendRequest, ZkSendResponse } from "./events.js";
23
+ const DEFAULT_ZKSEND_ORIGIN = "https://zksend.com";
24
+ class ZkSendPopup {
25
+ constructor({ origin = DEFAULT_ZKSEND_ORIGIN, name }) {
26
+ __privateAdd(this, _id, void 0);
27
+ __privateAdd(this, _origin, void 0);
28
+ __privateAdd(this, _name, void 0);
29
+ __privateAdd(this, _close, void 0);
30
+ __privateSet(this, _id, crypto.randomUUID());
31
+ __privateSet(this, _origin, origin);
32
+ __privateSet(this, _name, name);
33
+ }
34
+ async createRequest(request) {
35
+ const popup = window.open("about:blank", "_blank");
36
+ if (!popup) {
37
+ throw new Error("Failed to open new window");
38
+ }
39
+ const { promise, resolve, reject } = withResolvers();
40
+ let interval = null;
41
+ function cleanup() {
42
+ if (interval) {
43
+ clearInterval(interval);
44
+ }
45
+ window.removeEventListener("message", listener);
46
+ }
47
+ const listener = (event) => {
48
+ if (event.origin !== __privateGet(this, _origin)) {
49
+ return;
50
+ }
51
+ const { success, output } = safeParse(ZkSendResponse, event.data);
52
+ if (!success || output.id !== __privateGet(this, _id))
53
+ return;
54
+ cleanup();
55
+ if (output.payload.type === "reject") {
56
+ reject(new Error("User rejected the request"));
57
+ } else if (output.payload.type === "resolve") {
58
+ resolve(output.payload.data);
59
+ }
60
+ };
61
+ __privateSet(this, _close, () => {
62
+ cleanup();
63
+ popup?.close();
64
+ });
65
+ window.addEventListener("message", listener);
66
+ const { type, ...data } = request;
67
+ popup?.location.assign(
68
+ `${__privateGet(this, _origin)}/dapp/${type}?${new URLSearchParams({
69
+ id: __privateGet(this, _id),
70
+ origin: window.origin,
71
+ name: __privateGet(this, _name)
72
+ })}${data ? `#${new URLSearchParams(data)}` : ""}`
73
+ );
74
+ interval = setInterval(() => {
75
+ try {
76
+ if (popup?.closed) {
77
+ cleanup();
78
+ reject(new Error("User closed the zkSend window"));
79
+ }
80
+ } catch {
81
+ }
82
+ }, 1e3);
83
+ return promise;
84
+ }
85
+ close() {
86
+ var _a;
87
+ (_a = __privateGet(this, _close)) == null ? void 0 : _a.call(this);
88
+ }
89
+ }
90
+ _id = new WeakMap();
91
+ _origin = new WeakMap();
92
+ _name = new WeakMap();
93
+ _close = new WeakMap();
94
+ const _ZkSendHost = class {
95
+ constructor(request) {
96
+ __privateAdd(this, _request, void 0);
97
+ if (typeof window === "undefined" || !window.opener) {
98
+ throw new Error(
99
+ "ZkSendHost can only be used in a window opened through `window.open`. `window.opener` is not available."
100
+ );
101
+ }
102
+ __privateSet(this, _request, request);
103
+ }
104
+ static fromUrl(url = window.location.href) {
105
+ const parsed = new URL(url);
106
+ const urlHashData = parsed.hash ? Object.fromEntries(
107
+ [...new URLSearchParams(parsed.hash.slice(1))].map(([key, value]) => [
108
+ key,
109
+ value.replace(/ /g, "+")
110
+ ])
111
+ ) : {};
112
+ const request = parse(ZkSendRequest, {
113
+ id: parsed.searchParams.get("id"),
114
+ origin: parsed.searchParams.get("origin"),
115
+ name: parsed.searchParams.get("name"),
116
+ payload: {
117
+ type: parsed.pathname.split("/").pop(),
118
+ ...urlHashData
119
+ }
120
+ });
121
+ return new _ZkSendHost(request);
122
+ }
123
+ getRequestData() {
124
+ return __privateGet(this, _request);
125
+ }
126
+ sendMessage(payload) {
127
+ window.opener.postMessage(
128
+ {
129
+ id: __privateGet(this, _request).id,
130
+ source: "zksend-channel",
131
+ payload
132
+ },
133
+ __privateGet(this, _request).origin
134
+ );
135
+ }
136
+ close(payload) {
137
+ if (payload) {
138
+ this.sendMessage(payload);
139
+ }
140
+ window.close();
141
+ }
142
+ };
143
+ let ZkSendHost = _ZkSendHost;
144
+ _request = new WeakMap();
145
+ export {
146
+ DEFAULT_ZKSEND_ORIGIN,
147
+ ZkSendHost,
148
+ ZkSendPopup,
149
+ ZkSendRequest,
150
+ ZkSendResponse
151
+ };
152
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../src/channel/index.ts"],
4
+ "sourcesContent": ["// Copyright (c) Mysten Labs, Inc.\n// SPDX-License-Identifier: Apache-2.0\n\nimport type { Output } from 'valibot';\nimport { parse, safeParse } from 'valibot';\n\nimport { withResolvers } from '../utils/withResolvers.js';\nimport type { ZkSendRequestData, ZkSendResponsePayload, ZkSendResponseTypes } from './events.js';\nimport { ZkSendRequest, ZkSendResponse } from './events.js';\n\nexport const DEFAULT_ZKSEND_ORIGIN = 'https://zksend.com';\n\nexport { ZkSendRequest, ZkSendResponse };\n\ninterface ZkSendPopupOptions {\n\torigin?: string;\n\tname: string;\n}\n\nexport class ZkSendPopup {\n\t#id: string;\n\t#origin: string;\n\t#name: string;\n\n\t#close?: () => void;\n\n\tconstructor({ origin = DEFAULT_ZKSEND_ORIGIN, name }: ZkSendPopupOptions) {\n\t\tthis.#id = crypto.randomUUID();\n\t\tthis.#origin = origin;\n\t\tthis.#name = name;\n\t}\n\n\tasync createRequest<T extends ZkSendRequestData>(\n\t\trequest: T,\n\t): Promise<ZkSendResponseTypes[T['type']]> {\n\t\tconst popup = window.open('about:blank', '_blank');\n\n\t\tif (!popup) {\n\t\t\tthrow new Error('Failed to open new window');\n\t\t}\n\n\t\tconst { promise, resolve, reject } = withResolvers<ZkSendResponseTypes[T['type']]>();\n\n\t\tlet interval: NodeJS.Timer | null = null;\n\n\t\tfunction cleanup() {\n\t\t\tif (interval) {\n\t\t\t\tclearInterval(interval);\n\t\t\t}\n\t\t\twindow.removeEventListener('message', listener);\n\t\t}\n\n\t\tconst listener = (event: MessageEvent) => {\n\t\t\tif (event.origin !== this.#origin) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst { success, output } = safeParse(ZkSendResponse, event.data);\n\t\t\tif (!success || output.id !== this.#id) return;\n\n\t\t\tcleanup();\n\n\t\t\tif (output.payload.type === 'reject') {\n\t\t\t\treject(new Error('User rejected the request'));\n\t\t\t} else if (output.payload.type === 'resolve') {\n\t\t\t\tresolve(output.payload.data as ZkSendResponseTypes[T['type']]);\n\t\t\t}\n\t\t};\n\n\t\tthis.#close = () => {\n\t\t\tcleanup();\n\t\t\tpopup?.close();\n\t\t};\n\n\t\twindow.addEventListener('message', listener);\n\n\t\tconst { type, ...data } = request;\n\n\t\tpopup?.location.assign(\n\t\t\t`${this.#origin}/dapp/${type}?${new URLSearchParams({\n\t\t\t\tid: this.#id,\n\t\t\t\torigin: window.origin,\n\t\t\t\tname: this.#name,\n\t\t\t})}${data ? `#${new URLSearchParams(data as Record<string, string>)}` : ''}`,\n\t\t);\n\n\t\tinterval = setInterval(() => {\n\t\t\ttry {\n\t\t\t\tif (popup?.closed) {\n\t\t\t\t\tcleanup();\n\t\t\t\t\treject(new Error('User closed the zkSend window'));\n\t\t\t\t}\n\t\t\t} catch {\n\t\t\t\t// This can error during the login flow, but that's fine.\n\t\t\t}\n\t\t}, 1000);\n\n\t\treturn promise;\n\t}\n\n\tclose() {\n\t\tthis.#close?.();\n\t}\n}\n\nexport class ZkSendHost {\n\t#request: Output<typeof ZkSendRequest>;\n\n\tconstructor(request: Output<typeof ZkSendRequest>) {\n\t\tif (typeof window === 'undefined' || !window.opener) {\n\t\t\tthrow new Error(\n\t\t\t\t'ZkSendHost can only be used in a window opened through `window.open`. `window.opener` is not available.',\n\t\t\t);\n\t\t}\n\n\t\tthis.#request = request;\n\t}\n\n\tstatic fromUrl(url: string = window.location.href) {\n\t\tconst parsed = new URL(url);\n\n\t\tconst urlHashData = parsed.hash\n\t\t\t? Object.fromEntries(\n\t\t\t\t\t[...new URLSearchParams(parsed.hash.slice(1))].map(([key, value]) => [\n\t\t\t\t\t\tkey,\n\t\t\t\t\t\tvalue.replace(/ /g, '+'),\n\t\t\t\t\t]),\n\t\t\t )\n\t\t\t: {};\n\n\t\tconst request = parse(ZkSendRequest, {\n\t\t\tid: parsed.searchParams.get('id'),\n\t\t\torigin: parsed.searchParams.get('origin'),\n\t\t\tname: parsed.searchParams.get('name'),\n\t\t\tpayload: {\n\t\t\t\ttype: parsed.pathname.split('/').pop(),\n\t\t\t\t...urlHashData,\n\t\t\t},\n\t\t});\n\n\t\treturn new ZkSendHost(request);\n\t}\n\n\tgetRequestData() {\n\t\treturn this.#request;\n\t}\n\n\tsendMessage(payload: ZkSendResponsePayload) {\n\t\twindow.opener.postMessage(\n\t\t\t{\n\t\t\t\tid: this.#request.id,\n\t\t\t\tsource: 'zksend-channel',\n\t\t\t\tpayload,\n\t\t\t} satisfies ZkSendResponse,\n\t\t\tthis.#request.origin,\n\t\t);\n\t}\n\n\tclose(payload?: ZkSendResponsePayload) {\n\t\tif (payload) {\n\t\t\tthis.sendMessage(payload);\n\t\t}\n\t\twindow.close();\n\t}\n}\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAIA,SAAS,OAAO,iBAAiB;AAEjC,SAAS,qBAAqB;AAE9B,SAAS,eAAe,sBAAsB;AAEvC,MAAM,wBAAwB;AAS9B,MAAM,YAAY;AAAA,EAOxB,YAAY,EAAE,SAAS,uBAAuB,KAAK,GAAuB;AAN1E;AACA;AACA;AAEA;AAGC,uBAAK,KAAM,OAAO,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;AAAA,IACf;AAAA,EACD;AAAA,EAEA,MAAM,SAAiC;AACtC,QAAI,SAAS;AACZ,WAAK,YAAY,OAAO;AAAA,IACzB;AACA,WAAO,MAAM;AAAA,EACd;AACD;AA3DO,IAAM,aAAN;AACN;",
6
+ "names": []
7
+ }
@@ -0,0 +1,3 @@
1
+ export * from './links.js';
2
+ export * from './wallet.js';
3
+ export * from './channel/index.js';
package/dist/esm/index.js CHANGED
@@ -1,10 +1,4 @@
1
- var __getOwnPropNames = Object.getOwnPropertyNames;
2
- var __commonJS = (cb, mod) => function __require() {
3
- return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
4
- };
5
- var require_src = __commonJS({
6
- "src/index.ts"() {
7
- }
8
- });
9
- export default require_src();
1
+ export * from "./links.js";
2
+ export * from "./wallet.js";
3
+ export * from "./channel/index.js";
10
4
  //# sourceMappingURL=index.js.map
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../src/index.ts"],
4
- "sourcesContent": ["// Copyright (c) Mysten Labs, Inc.\n// SPDX-License-Identifier: Apache-2.0\n"],
5
- "mappings": ";;;;AAAA;AAAA;AAAA;AAAA;",
4
+ "sourcesContent": ["// Copyright (c) Mysten Labs, Inc.\n// SPDX-License-Identifier: Apache-2.0\n\nexport * from './links.js';\nexport * from './wallet.js';\nexport * from './channel/index.js';\n"],
5
+ "mappings": "AAGA,cAAc;AACd,cAAc;AACd,cAAc;",
6
6
  "names": []
7
7
  }
@@ -0,0 +1,80 @@
1
+ import { SuiClient } from '@mysten/sui.js/client';
2
+ import type { Keypair, Signer } from '@mysten/sui.js/cryptography';
3
+ import type { TransactionObjectInput } from '@mysten/sui.js/transactions';
4
+ import { TransactionBlock } from '@mysten/sui.js/transactions';
5
+ interface ZkSendLinkRedirect {
6
+ url: string;
7
+ name?: string;
8
+ }
9
+ export interface ZkSendLinkBuilderOptions {
10
+ host?: string;
11
+ path?: string;
12
+ mist?: number;
13
+ keypair?: Keypair;
14
+ client?: SuiClient;
15
+ sender: string;
16
+ redirect?: ZkSendLinkRedirect;
17
+ }
18
+ export interface ZkSendLinkOptions {
19
+ keypair?: Keypair;
20
+ client?: SuiClient;
21
+ }
22
+ interface CreateZkSendLinkOptions {
23
+ transactionBlock?: TransactionBlock;
24
+ calculateGas?: (options: {
25
+ balances: Map<string, bigint>;
26
+ objects: TransactionObjectInput[];
27
+ gasEstimateFromDryRun: bigint;
28
+ }) => Promise<bigint> | bigint;
29
+ }
30
+ export declare class ZkSendLinkBuilder {
31
+ #private;
32
+ constructor({ host, path, keypair, client, sender, redirect, }: ZkSendLinkBuilderOptions);
33
+ addClaimableMist(amount: bigint): void;
34
+ addClaimableBalance(coinType: string, amount: bigint): void;
35
+ addClaimableObject(id: string): void;
36
+ getLink(): string;
37
+ create({ signer, ...options }: CreateZkSendLinkOptions & {
38
+ signer: Signer;
39
+ }): Promise<import("@mysten/sui.js/client").SuiTransactionBlockResponse>;
40
+ createSendTransaction({ transactionBlock: txb, calculateGas, }?: CreateZkSendLinkOptions): Promise<TransactionBlock>;
41
+ }
42
+ export interface ZkSendLinkOptions {
43
+ keypair?: Keypair;
44
+ client?: SuiClient;
45
+ }
46
+ export declare class ZkSendLink {
47
+ #private;
48
+ constructor({ client, keypair, }: ZkSendLinkOptions & {
49
+ linkAddress?: string;
50
+ });
51
+ static fromUrl(url: string, options?: Omit<ZkSendLinkOptions, 'keypair'>): Promise<ZkSendLink>;
52
+ loadOwnedData(): Promise<void>;
53
+ listClaimableAssets(address: string, options?: {
54
+ claimObjectsAddedAfterCreation?: boolean;
55
+ coinTypes?: string[];
56
+ objects?: string[];
57
+ }): Promise<{
58
+ balances: {
59
+ coinType: string;
60
+ amount: bigint;
61
+ }[];
62
+ nfts: {
63
+ objectId: string;
64
+ type: string;
65
+ version: string;
66
+ digest: string;
67
+ }[];
68
+ }>;
69
+ claimAssets(address: string, options?: {
70
+ claimObjectsAddedAfterCreation?: boolean;
71
+ coinTypes?: string[];
72
+ objects?: string[];
73
+ }): Promise<import("@mysten/sui.js/client").SuiTransactionBlockResponse>;
74
+ createClaimTransaction(address: string, options?: {
75
+ claimObjectsAddedAfterCreation?: boolean;
76
+ coinTypes?: string[];
77
+ objects?: string[];
78
+ }): TransactionBlock;
79
+ }
80
+ export {};
@@ -0,0 +1,361 @@
1
+ var __accessCheck = (obj, member, msg) => {
2
+ if (!member.has(obj))
3
+ throw TypeError("Cannot " + msg);
4
+ };
5
+ var __privateGet = (obj, member, getter) => {
6
+ __accessCheck(obj, member, "read from private field");
7
+ return getter ? getter.call(obj) : member.get(obj);
8
+ };
9
+ var __privateAdd = (obj, member, value) => {
10
+ if (member.has(obj))
11
+ throw TypeError("Cannot add the same private member more than once");
12
+ member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
13
+ };
14
+ var __privateSet = (obj, member, value, setter) => {
15
+ __accessCheck(obj, member, "write to private field");
16
+ setter ? setter.call(obj, value) : member.set(obj, value);
17
+ return value;
18
+ };
19
+ var __privateMethod = (obj, member, method) => {
20
+ __accessCheck(obj, member, "access private method");
21
+ return method;
22
+ };
23
+ var _host, _path, _keypair, _client, _redirect, _objects, _balances, _sender, _coinsByType, _estimateClaimGasFee, estimateClaimGasFee_fn, _getCoinsByType, getCoinsByType_fn, _client2, _keypair2, _initiallyOwnedObjects, _ownedObjects, _gasCoin, _hasSui, _creatorAddress, _loadOwnedObjects, loadOwnedObjects_fn, _loadInitialTransactionData, loadInitialTransactionData_fn;
24
+ import { getFullnodeUrl, SuiClient } from "@mysten/sui.js/client";
25
+ import { decodeSuiPrivateKey } from "@mysten/sui.js/cryptography";
26
+ import { Ed25519Keypair } from "@mysten/sui.js/keypairs/ed25519";
27
+ import { TransactionBlock } from "@mysten/sui.js/transactions";
28
+ import {
29
+ fromB64,
30
+ normalizeStructTag,
31
+ normalizeSuiAddress,
32
+ normalizeSuiObjectId,
33
+ parseStructTag,
34
+ SUI_TYPE_ARG,
35
+ toB64
36
+ } from "@mysten/sui.js/utils";
37
+ const DEFAULT_ZK_SEND_LINK_OPTIONS = {
38
+ host: "https://zksend.com",
39
+ path: "/claim",
40
+ client: new SuiClient({ url: getFullnodeUrl("mainnet") })
41
+ };
42
+ const SUI_COIN_TYPE = normalizeStructTag(SUI_TYPE_ARG);
43
+ const SUI_COIN_OBJECT_TYPE = normalizeStructTag("0x2::coin::Coin<0x2::sui::SUI>");
44
+ class ZkSendLinkBuilder {
45
+ constructor({
46
+ host = DEFAULT_ZK_SEND_LINK_OPTIONS.host,
47
+ path = DEFAULT_ZK_SEND_LINK_OPTIONS.path,
48
+ keypair = new Ed25519Keypair(),
49
+ client = DEFAULT_ZK_SEND_LINK_OPTIONS.client,
50
+ sender,
51
+ redirect
52
+ }) {
53
+ __privateAdd(this, _estimateClaimGasFee);
54
+ __privateAdd(this, _getCoinsByType);
55
+ __privateAdd(this, _host, void 0);
56
+ __privateAdd(this, _path, void 0);
57
+ __privateAdd(this, _keypair, void 0);
58
+ __privateAdd(this, _client, void 0);
59
+ __privateAdd(this, _redirect, void 0);
60
+ __privateAdd(this, _objects, /* @__PURE__ */ new Set());
61
+ __privateAdd(this, _balances, /* @__PURE__ */ new Map());
62
+ __privateAdd(this, _sender, void 0);
63
+ __privateAdd(this, _coinsByType, /* @__PURE__ */ new Map());
64
+ __privateSet(this, _host, host);
65
+ __privateSet(this, _path, path);
66
+ __privateSet(this, _redirect, redirect);
67
+ __privateSet(this, _keypair, keypair);
68
+ __privateSet(this, _client, client);
69
+ __privateSet(this, _sender, normalizeSuiAddress(sender));
70
+ }
71
+ addClaimableMist(amount) {
72
+ this.addClaimableBalance(SUI_COIN_TYPE, amount);
73
+ }
74
+ addClaimableBalance(coinType, amount) {
75
+ __privateGet(this, _balances).set(normalizeStructTag(coinType), (__privateGet(this, _balances).get(coinType) ?? 0n) + amount);
76
+ }
77
+ addClaimableObject(id) {
78
+ __privateGet(this, _objects).add(id);
79
+ }
80
+ getLink() {
81
+ const link = new URL(__privateGet(this, _host));
82
+ link.pathname = __privateGet(this, _path);
83
+ link.hash = toB64(decodeSuiPrivateKey(__privateGet(this, _keypair).getSecretKey()).secretKey);
84
+ if (__privateGet(this, _redirect)) {
85
+ link.searchParams.set("redirect_url", __privateGet(this, _redirect).url);
86
+ if (__privateGet(this, _redirect).name) {
87
+ link.searchParams.set("name", __privateGet(this, _redirect).name);
88
+ }
89
+ }
90
+ return link.toString();
91
+ }
92
+ async create({
93
+ signer,
94
+ ...options
95
+ }) {
96
+ const txb = await this.createSendTransaction(options);
97
+ return __privateGet(this, _client).signAndExecuteTransactionBlock({
98
+ transactionBlock: await txb.build({ client: __privateGet(this, _client) }),
99
+ signer
100
+ });
101
+ }
102
+ async createSendTransaction({
103
+ transactionBlock: txb = new TransactionBlock(),
104
+ calculateGas
105
+ } = {}) {
106
+ const gasEstimateFromDryRun = await __privateMethod(this, _estimateClaimGasFee, estimateClaimGasFee_fn).call(this);
107
+ const baseGasAmount = calculateGas ? await calculateGas({
108
+ balances: __privateGet(this, _balances),
109
+ objects: [...__privateGet(this, _objects)],
110
+ gasEstimateFromDryRun
111
+ }) : gasEstimateFromDryRun * 2n;
112
+ const gasWithBuffer = baseGasAmount + 1013n;
113
+ const roundedGasAmount = gasWithBuffer - gasWithBuffer % 1000n - 13n;
114
+ const address = __privateGet(this, _keypair).toSuiAddress();
115
+ const objectsToTransfer = [...__privateGet(this, _objects)].map((id) => txb.object(id));
116
+ const [gas] = txb.splitCoins(txb.gas, [roundedGasAmount]);
117
+ objectsToTransfer.push(gas);
118
+ txb.setSenderIfNotSet(__privateGet(this, _sender));
119
+ for (const [coinType, amount] of __privateGet(this, _balances)) {
120
+ if (coinType === SUI_COIN_TYPE) {
121
+ const [sui] = txb.splitCoins(txb.gas, [amount]);
122
+ objectsToTransfer.push(sui);
123
+ } else {
124
+ const coins = (await __privateMethod(this, _getCoinsByType, getCoinsByType_fn).call(this, coinType)).map((coin) => coin.coinObjectId);
125
+ if (coins.length > 1) {
126
+ txb.mergeCoins(coins[0], coins.slice(1));
127
+ }
128
+ const [split] = txb.splitCoins(coins[0], [amount]);
129
+ objectsToTransfer.push(split);
130
+ }
131
+ }
132
+ txb.transferObjects(objectsToTransfer, address);
133
+ return txb;
134
+ }
135
+ }
136
+ _host = new WeakMap();
137
+ _path = new WeakMap();
138
+ _keypair = new WeakMap();
139
+ _client = new WeakMap();
140
+ _redirect = new WeakMap();
141
+ _objects = new WeakMap();
142
+ _balances = new WeakMap();
143
+ _sender = new WeakMap();
144
+ _coinsByType = new WeakMap();
145
+ _estimateClaimGasFee = new WeakSet();
146
+ estimateClaimGasFee_fn = async function() {
147
+ const txb = new TransactionBlock();
148
+ txb.setSender(__privateGet(this, _sender));
149
+ txb.setGasPayment([]);
150
+ txb.transferObjects([txb.gas], __privateGet(this, _keypair).toSuiAddress());
151
+ const idsToTransfer = [...__privateGet(this, _objects)];
152
+ for (const [coinType] of __privateGet(this, _balances)) {
153
+ const coins = await __privateMethod(this, _getCoinsByType, getCoinsByType_fn).call(this, coinType);
154
+ if (!coins.length) {
155
+ throw new Error(`Sending account does not contain any coins of type ${coinType}`);
156
+ }
157
+ idsToTransfer.push(coins[0].coinObjectId);
158
+ }
159
+ if (idsToTransfer.length > 0) {
160
+ txb.transferObjects(
161
+ idsToTransfer.map((id) => txb.object(id)),
162
+ __privateGet(this, _keypair).toSuiAddress()
163
+ );
164
+ }
165
+ const result = await __privateGet(this, _client).dryRunTransactionBlock({
166
+ transactionBlock: await txb.build({ client: __privateGet(this, _client) })
167
+ });
168
+ return BigInt(result.effects.gasUsed.computationCost) + BigInt(result.effects.gasUsed.storageCost) - BigInt(result.effects.gasUsed.storageRebate);
169
+ };
170
+ _getCoinsByType = new WeakSet();
171
+ getCoinsByType_fn = async function(coinType) {
172
+ if (__privateGet(this, _coinsByType).has(coinType)) {
173
+ return __privateGet(this, _coinsByType).get(coinType);
174
+ }
175
+ const coins = await __privateGet(this, _client).getCoins({
176
+ coinType,
177
+ owner: __privateGet(this, _sender)
178
+ });
179
+ __privateGet(this, _coinsByType).set(coinType, coins.data);
180
+ return coins.data;
181
+ };
182
+ const _ZkSendLink = class {
183
+ constructor({
184
+ client = DEFAULT_ZK_SEND_LINK_OPTIONS.client,
185
+ keypair = new Ed25519Keypair()
186
+ }) {
187
+ __privateAdd(this, _loadOwnedObjects);
188
+ __privateAdd(this, _loadInitialTransactionData);
189
+ __privateAdd(this, _client2, void 0);
190
+ __privateAdd(this, _keypair2, void 0);
191
+ __privateAdd(this, _initiallyOwnedObjects, /* @__PURE__ */ new Set());
192
+ __privateAdd(this, _ownedObjects, []);
193
+ __privateAdd(this, _gasCoin, void 0);
194
+ __privateAdd(this, _hasSui, false);
195
+ __privateAdd(this, _creatorAddress, void 0);
196
+ __privateSet(this, _client2, client);
197
+ __privateSet(this, _keypair2, keypair);
198
+ }
199
+ static async fromUrl(url, options) {
200
+ const parsed = new URL(url);
201
+ const keypair = Ed25519Keypair.fromSecretKey(fromB64(parsed.hash.slice(1)));
202
+ const link = new _ZkSendLink({
203
+ ...options,
204
+ keypair
205
+ });
206
+ await link.loadOwnedData();
207
+ return link;
208
+ }
209
+ async loadOwnedData() {
210
+ await Promise.all([__privateMethod(this, _loadInitialTransactionData, loadInitialTransactionData_fn).call(this), __privateMethod(this, _loadOwnedObjects, loadOwnedObjects_fn).call(this)]);
211
+ }
212
+ async listClaimableAssets(address, options) {
213
+ const normalizedAddress = normalizeSuiAddress(address);
214
+ const txb = this.createClaimTransaction(normalizedAddress, options);
215
+ if (__privateGet(this, _gasCoin) || !__privateGet(this, _hasSui)) {
216
+ txb.setGasPayment([]);
217
+ }
218
+ const dryRun = await __privateGet(this, _client2).dryRunTransactionBlock({
219
+ transactionBlock: await txb.build({ client: __privateGet(this, _client2) })
220
+ });
221
+ const balances = [];
222
+ const nfts = [];
223
+ dryRun.balanceChanges.forEach((balanceChange) => {
224
+ if (BigInt(balanceChange.amount) > 0n && isOwner(balanceChange.owner, normalizedAddress)) {
225
+ balances.push({ coinType: balanceChange.coinType, amount: BigInt(balanceChange.amount) });
226
+ }
227
+ });
228
+ dryRun.objectChanges.forEach((objectChange) => {
229
+ if ("objectType" in objectChange) {
230
+ const type = parseStructTag(objectChange.objectType);
231
+ if (type.address === normalizeSuiAddress("0x2") && type.module === "coin" && type.name === "Coin") {
232
+ return;
233
+ }
234
+ }
235
+ if (ownedAfterChange(objectChange, normalizedAddress)) {
236
+ nfts.push(objectChange);
237
+ }
238
+ });
239
+ return {
240
+ balances,
241
+ nfts
242
+ };
243
+ }
244
+ async claimAssets(address, options) {
245
+ return __privateGet(this, _client2).signAndExecuteTransactionBlock({
246
+ transactionBlock: await this.createClaimTransaction(address, options),
247
+ signer: __privateGet(this, _keypair2)
248
+ });
249
+ }
250
+ createClaimTransaction(address, options) {
251
+ const claimAll = !options?.coinTypes && !options?.objects;
252
+ const txb = new TransactionBlock();
253
+ txb.setSender(__privateGet(this, _keypair2).toSuiAddress());
254
+ const coinTypes = new Set(
255
+ options?.coinTypes?.map((type) => normalizeStructTag(`0x2::coin::Coin<${type}>`)) ?? []
256
+ );
257
+ const objectsToTransfer = __privateGet(this, _ownedObjects).filter((object) => {
258
+ if (__privateGet(this, _gasCoin)) {
259
+ if (object.objectId === __privateGet(this, _gasCoin).coinObjectId) {
260
+ return false;
261
+ }
262
+ } else if (object.type === SUI_COIN_OBJECT_TYPE) {
263
+ return false;
264
+ }
265
+ if (coinTypes?.has(object.type) || options?.objects?.includes(object.objectId)) {
266
+ return true;
267
+ }
268
+ if (!options?.claimObjectsAddedAfterCreation && !__privateGet(this, _initiallyOwnedObjects).has(object.objectId)) {
269
+ return false;
270
+ }
271
+ return claimAll;
272
+ }).map((object) => txb.object(object.objectId));
273
+ if (__privateGet(this, _gasCoin) && __privateGet(this, _creatorAddress)) {
274
+ txb.transferObjects([txb.gas], __privateGet(this, _creatorAddress));
275
+ } else if (claimAll || coinTypes?.has(SUI_COIN_TYPE)) {
276
+ objectsToTransfer.push(txb.gas);
277
+ }
278
+ if (objectsToTransfer.length > 0) {
279
+ txb.transferObjects(objectsToTransfer, address);
280
+ }
281
+ return txb;
282
+ }
283
+ };
284
+ let ZkSendLink = _ZkSendLink;
285
+ _client2 = new WeakMap();
286
+ _keypair2 = new WeakMap();
287
+ _initiallyOwnedObjects = new WeakMap();
288
+ _ownedObjects = new WeakMap();
289
+ _gasCoin = new WeakMap();
290
+ _hasSui = new WeakMap();
291
+ _creatorAddress = new WeakMap();
292
+ _loadOwnedObjects = new WeakSet();
293
+ loadOwnedObjects_fn = async function() {
294
+ __privateSet(this, _ownedObjects, []);
295
+ let nextCursor;
296
+ const owner = __privateGet(this, _keypair2).toSuiAddress();
297
+ do {
298
+ const ownedObjects = await __privateGet(this, _client2).getOwnedObjects({
299
+ cursor: nextCursor,
300
+ owner,
301
+ options: {
302
+ showType: true
303
+ }
304
+ });
305
+ nextCursor = ownedObjects.hasNextPage ? ownedObjects.nextCursor : null;
306
+ for (const object of ownedObjects.data) {
307
+ if (object.data) {
308
+ __privateGet(this, _ownedObjects).push({
309
+ objectId: normalizeSuiObjectId(object.data.objectId),
310
+ version: object.data.version,
311
+ digest: object.data.digest,
312
+ type: normalizeStructTag(object.data.type)
313
+ });
314
+ }
315
+ }
316
+ } while (nextCursor);
317
+ const coins = await __privateGet(this, _client2).getCoins({
318
+ coinType: SUI_COIN_TYPE,
319
+ owner
320
+ });
321
+ __privateSet(this, _hasSui, coins.data.length > 0);
322
+ __privateSet(this, _gasCoin, coins.data.find((coin) => BigInt(coin.balance) % 1000n === 987n));
323
+ };
324
+ _loadInitialTransactionData = new WeakSet();
325
+ loadInitialTransactionData_fn = async function() {
326
+ const address = __privateGet(this, _keypair2).toSuiAddress();
327
+ const result = await __privateGet(this, _client2).queryTransactionBlocks({
328
+ limit: 1,
329
+ order: "ascending",
330
+ filter: {
331
+ ToAddress: address
332
+ },
333
+ options: {
334
+ showObjectChanges: true,
335
+ showInput: true
336
+ }
337
+ });
338
+ result.data[0]?.objectChanges?.forEach((objectChange) => {
339
+ if (ownedAfterChange(objectChange, address)) {
340
+ __privateGet(this, _initiallyOwnedObjects).add(normalizeSuiObjectId(objectChange.objectId));
341
+ }
342
+ });
343
+ __privateSet(this, _creatorAddress, result.data[0]?.transaction?.data.sender);
344
+ };
345
+ function ownedAfterChange(objectChange, address) {
346
+ if (objectChange.type === "transferred" && isOwner(objectChange.recipient, address)) {
347
+ return true;
348
+ }
349
+ if ((objectChange.type === "created" || objectChange.type === "mutated") && isOwner(objectChange.owner, address)) {
350
+ return true;
351
+ }
352
+ return false;
353
+ }
354
+ function isOwner(owner, address) {
355
+ return owner && typeof owner === "object" && "AddressOwner" in owner && normalizeSuiAddress(owner.AddressOwner) === address;
356
+ }
357
+ export {
358
+ ZkSendLink,
359
+ ZkSendLinkBuilder
360
+ };
361
+ //# sourceMappingURL=links.js.map