@mysten/enoki 0.13.0 → 1.0.0

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 (168) hide show
  1. package/CHANGELOG.md +35 -2
  2. package/README.md +76 -0
  3. package/dist/EnokiClient/index.d.mts +41 -0
  4. package/dist/EnokiClient/index.d.mts.map +1 -0
  5. package/dist/EnokiClient/index.mjs +136 -0
  6. package/dist/EnokiClient/index.mjs.map +1 -0
  7. package/dist/EnokiClient/type.d.mts +119 -0
  8. package/dist/EnokiClient/type.d.mts.map +1 -0
  9. package/dist/EnokiFlow.d.mts +103 -0
  10. package/dist/EnokiFlow.d.mts.map +1 -0
  11. package/dist/EnokiFlow.mjs +205 -0
  12. package/dist/EnokiFlow.mjs.map +1 -0
  13. package/dist/EnokiKeypair.d.mts +23 -0
  14. package/dist/EnokiKeypair.d.mts.map +1 -0
  15. package/dist/EnokiKeypair.mjs +53 -0
  16. package/dist/EnokiKeypair.mjs.map +1 -0
  17. package/dist/encryption.d.mts +15 -0
  18. package/dist/encryption.d.mts.map +1 -0
  19. package/dist/encryption.mjs +53 -0
  20. package/dist/encryption.mjs.map +1 -0
  21. package/dist/index.d.mts +13 -0
  22. package/dist/index.mjs +11 -0
  23. package/dist/react.d.mts +28 -0
  24. package/dist/react.d.mts.map +1 -0
  25. package/dist/react.mjs +61 -0
  26. package/dist/react.mjs.map +1 -0
  27. package/dist/stores.d.mts +25 -0
  28. package/dist/stores.d.mts.map +1 -0
  29. package/dist/stores.mjs +56 -0
  30. package/dist/stores.mjs.map +1 -0
  31. package/dist/utils.d.mts +7 -0
  32. package/dist/utils.d.mts.map +1 -0
  33. package/dist/utils.mjs +8 -0
  34. package/dist/utils.mjs.map +1 -0
  35. package/dist/wallet/features.d.mts +55 -0
  36. package/dist/wallet/features.d.mts.map +1 -0
  37. package/dist/wallet/features.mjs +9 -0
  38. package/dist/wallet/features.mjs.map +1 -0
  39. package/dist/wallet/initializer.d.mts +19 -0
  40. package/dist/wallet/initializer.d.mts.map +1 -0
  41. package/dist/wallet/initializer.mjs +20 -0
  42. package/dist/wallet/initializer.mjs.map +1 -0
  43. package/dist/wallet/providers.mjs +32 -0
  44. package/dist/wallet/providers.mjs.map +1 -0
  45. package/dist/wallet/register.d.mts +16 -0
  46. package/dist/wallet/register.d.mts.map +1 -0
  47. package/dist/wallet/register.mjs +43 -0
  48. package/dist/wallet/register.mjs.map +1 -0
  49. package/dist/wallet/state.mjs +101 -0
  50. package/dist/wallet/state.mjs.map +1 -0
  51. package/dist/wallet/types.d.mts +72 -0
  52. package/dist/wallet/types.d.mts.map +1 -0
  53. package/dist/wallet/utils.d.mts +16 -0
  54. package/dist/wallet/utils.d.mts.map +1 -0
  55. package/dist/wallet/utils.mjs +44 -0
  56. package/dist/wallet/utils.mjs.map +1 -0
  57. package/dist/wallet/wallet.d.mts +33 -0
  58. package/dist/wallet/wallet.d.mts.map +1 -0
  59. package/dist/wallet/wallet.mjs +345 -0
  60. package/dist/wallet/wallet.mjs.map +1 -0
  61. package/package.json +26 -28
  62. package/dist/cjs/EnokiClient/index.d.ts +0 -36
  63. package/dist/cjs/EnokiClient/index.js +0 -196
  64. package/dist/cjs/EnokiClient/index.js.map +0 -7
  65. package/dist/cjs/EnokiClient/type.d.ts +0 -119
  66. package/dist/cjs/EnokiClient/type.js +0 -17
  67. package/dist/cjs/EnokiClient/type.js.map +0 -7
  68. package/dist/cjs/EnokiFlow.d.ts +0 -74
  69. package/dist/cjs/EnokiFlow.js +0 -279
  70. package/dist/cjs/EnokiFlow.js.map +0 -7
  71. package/dist/cjs/EnokiKeypair.d.ts +0 -20
  72. package/dist/cjs/EnokiKeypair.js +0 -87
  73. package/dist/cjs/EnokiKeypair.js.map +0 -7
  74. package/dist/cjs/encryption.d.ts +0 -15
  75. package/dist/cjs/encryption.js +0 -96
  76. package/dist/cjs/encryption.js.map +0 -7
  77. package/dist/cjs/index.d.ts +0 -12
  78. package/dist/cjs/index.js +0 -50
  79. package/dist/cjs/index.js.map +0 -7
  80. package/dist/cjs/package.json +0 -4
  81. package/dist/cjs/react.d.ts +0 -20
  82. package/dist/cjs/react.js +0 -76
  83. package/dist/cjs/react.js.map +0 -7
  84. package/dist/cjs/stores.d.ts +0 -21
  85. package/dist/cjs/stores.js +0 -67
  86. package/dist/cjs/stores.js.map +0 -7
  87. package/dist/cjs/utils.d.ts +0 -2
  88. package/dist/cjs/utils.js +0 -27
  89. package/dist/cjs/utils.js.map +0 -7
  90. package/dist/cjs/wallet/features.d.ts +0 -50
  91. package/dist/cjs/wallet/features.js +0 -27
  92. package/dist/cjs/wallet/features.js.map +0 -7
  93. package/dist/cjs/wallet/initializer.d.ts +0 -11
  94. package/dist/cjs/wallet/initializer.js +0 -41
  95. package/dist/cjs/wallet/initializer.js.map +0 -7
  96. package/dist/cjs/wallet/providers.d.ts +0 -7
  97. package/dist/cjs/wallet/providers.js +0 -51
  98. package/dist/cjs/wallet/providers.js.map +0 -7
  99. package/dist/cjs/wallet/register.d.ts +0 -7
  100. package/dist/cjs/wallet/register.js +0 -68
  101. package/dist/cjs/wallet/register.js.map +0 -7
  102. package/dist/cjs/wallet/state.d.ts +0 -18
  103. package/dist/cjs/wallet/state.js +0 -142
  104. package/dist/cjs/wallet/state.js.map +0 -7
  105. package/dist/cjs/wallet/types.d.ts +0 -82
  106. package/dist/cjs/wallet/types.js +0 -17
  107. package/dist/cjs/wallet/types.js.map +0 -7
  108. package/dist/cjs/wallet/utils.d.ts +0 -11
  109. package/dist/cjs/wallet/utils.js +0 -83
  110. package/dist/cjs/wallet/utils.js.map +0 -7
  111. package/dist/cjs/wallet/wallet.d.ts +0 -16
  112. package/dist/cjs/wallet/wallet.js +0 -466
  113. package/dist/cjs/wallet/wallet.js.map +0 -7
  114. package/dist/esm/EnokiClient/index.d.ts +0 -36
  115. package/dist/esm/EnokiClient/index.js +0 -176
  116. package/dist/esm/EnokiClient/index.js.map +0 -7
  117. package/dist/esm/EnokiClient/type.d.ts +0 -119
  118. package/dist/esm/EnokiClient/type.js +0 -1
  119. package/dist/esm/EnokiClient/type.js.map +0 -7
  120. package/dist/esm/EnokiFlow.d.ts +0 -74
  121. package/dist/esm/EnokiFlow.js +0 -259
  122. package/dist/esm/EnokiFlow.js.map +0 -7
  123. package/dist/esm/EnokiKeypair.d.ts +0 -20
  124. package/dist/esm/EnokiKeypair.js +0 -67
  125. package/dist/esm/EnokiKeypair.js.map +0 -7
  126. package/dist/esm/encryption.d.ts +0 -15
  127. package/dist/esm/encryption.js +0 -76
  128. package/dist/esm/encryption.js.map +0 -7
  129. package/dist/esm/index.d.ts +0 -12
  130. package/dist/esm/index.js +0 -41
  131. package/dist/esm/index.js.map +0 -7
  132. package/dist/esm/package.json +0 -4
  133. package/dist/esm/react.d.ts +0 -20
  134. package/dist/esm/react.js +0 -56
  135. package/dist/esm/react.js.map +0 -7
  136. package/dist/esm/stores.d.ts +0 -21
  137. package/dist/esm/stores.js +0 -47
  138. package/dist/esm/stores.js.map +0 -7
  139. package/dist/esm/utils.d.ts +0 -2
  140. package/dist/esm/utils.js +0 -7
  141. package/dist/esm/utils.js.map +0 -7
  142. package/dist/esm/wallet/features.d.ts +0 -50
  143. package/dist/esm/wallet/features.js +0 -7
  144. package/dist/esm/wallet/features.js.map +0 -7
  145. package/dist/esm/wallet/initializer.d.ts +0 -11
  146. package/dist/esm/wallet/initializer.js +0 -21
  147. package/dist/esm/wallet/initializer.js.map +0 -7
  148. package/dist/esm/wallet/providers.d.ts +0 -7
  149. package/dist/esm/wallet/providers.js +0 -31
  150. package/dist/esm/wallet/providers.js.map +0 -7
  151. package/dist/esm/wallet/register.d.ts +0 -7
  152. package/dist/esm/wallet/register.js +0 -48
  153. package/dist/esm/wallet/register.js.map +0 -7
  154. package/dist/esm/wallet/state.d.ts +0 -18
  155. package/dist/esm/wallet/state.js +0 -122
  156. package/dist/esm/wallet/state.js.map +0 -7
  157. package/dist/esm/wallet/types.d.ts +0 -82
  158. package/dist/esm/wallet/types.js +0 -1
  159. package/dist/esm/wallet/types.js.map +0 -7
  160. package/dist/esm/wallet/utils.d.ts +0 -11
  161. package/dist/esm/wallet/utils.js +0 -63
  162. package/dist/esm/wallet/utils.js.map +0 -7
  163. package/dist/esm/wallet/wallet.d.ts +0 -16
  164. package/dist/esm/wallet/wallet.js +0 -444
  165. package/dist/esm/wallet/wallet.js.map +0 -7
  166. package/dist/tsconfig.esm.tsbuildinfo +0 -1
  167. package/dist/tsconfig.tsbuildinfo +0 -1
  168. package/react/package.json +0 -5
@@ -0,0 +1,205 @@
1
+ import { EnokiClient } from "./EnokiClient/index.mjs";
2
+ import { createDefaultEncryption } from "./encryption.mjs";
3
+ import { EnokiKeypair } from "./EnokiKeypair.mjs";
4
+ import { createSessionStorage } from "./stores.mjs";
5
+ import { WebCryptoSigner } from "@mysten/signers/webcrypto";
6
+ import { decodeSuiPrivateKey } from "@mysten/sui/cryptography";
7
+ import { Ed25519Keypair } from "@mysten/sui/keypairs/ed25519";
8
+ import { fromBase64, toBase64 } from "@mysten/sui/utils";
9
+ import { decodeJwt } from "@mysten/sui/zklogin";
10
+ import { clear, createStore, get, set } from "idb-keyval";
11
+ import { atom, onMount, onSet } from "nanostores";
12
+
13
+ //#region src/EnokiFlow.ts
14
+ const createStorageKeys = (apiKey) => ({
15
+ STATE: `@enoki/flow/state/${apiKey}`,
16
+ SESSION: `@enoki/flow/session/${apiKey}`
17
+ });
18
+ /**
19
+ * @deprecated Use `registerEnokiWallets` instead
20
+ */
21
+ var EnokiFlow = class {
22
+ #storageKeys;
23
+ #enokiClient;
24
+ #encryption;
25
+ #encryptionKey;
26
+ #store;
27
+ #useNativeCryptoSigner;
28
+ #idbStore;
29
+ constructor(config) {
30
+ this.#enokiClient = new EnokiClient({
31
+ apiKey: config.apiKey,
32
+ apiUrl: config.apiUrl,
33
+ additionalEpochs: config.additionalEpochs
34
+ });
35
+ this.#encryptionKey = config.apiKey;
36
+ if (config.experimental_nativeCryptoSigner) {
37
+ this.#useNativeCryptoSigner = true;
38
+ this.#idbStore = createStore(config.apiKey, "enoki");
39
+ } else this.#useNativeCryptoSigner = false;
40
+ this.#encryption = config.encryption ?? createDefaultEncryption();
41
+ this.#store = config.store ?? createSessionStorage();
42
+ this.#storageKeys = createStorageKeys(config.apiKey);
43
+ let storedState = null;
44
+ try {
45
+ const rawStoredValue = this.#store.get(this.#storageKeys.STATE);
46
+ if (rawStoredValue) storedState = JSON.parse(rawStoredValue);
47
+ } catch {}
48
+ this.$zkLoginState = atom(storedState || {});
49
+ this.$zkLoginSession = atom({
50
+ initialized: false,
51
+ value: null
52
+ });
53
+ onMount(this.$zkLoginSession, () => {
54
+ this.getSession();
55
+ });
56
+ onSet(this.$zkLoginState, ({ newValue }) => {
57
+ this.#store.set(this.#storageKeys.STATE, JSON.stringify(newValue));
58
+ });
59
+ }
60
+ get enokiClient() {
61
+ return this.#enokiClient;
62
+ }
63
+ async createAuthorizationURL(input) {
64
+ const ephemeralKeyPair = this.#useNativeCryptoSigner ? await WebCryptoSigner.generate() : new Ed25519Keypair();
65
+ const { nonce, randomness, maxEpoch, estimatedExpiration } = await this.#enokiClient.createZkLoginNonce({
66
+ network: input.network,
67
+ ephemeralPublicKey: ephemeralKeyPair.getPublicKey()
68
+ });
69
+ const params = new URLSearchParams({
70
+ ...input.extraParams,
71
+ nonce,
72
+ client_id: input.clientId,
73
+ redirect_uri: input.redirectUrl,
74
+ response_type: "id_token",
75
+ scope: ["openid", ...input.extraParams && "scope" in input.extraParams ? input.extraParams.scope : []].filter(Boolean).join(" ")
76
+ });
77
+ let oauthUrl;
78
+ switch (input.provider) {
79
+ case "google":
80
+ oauthUrl = `https://accounts.google.com/o/oauth2/v2/auth?${params}`;
81
+ break;
82
+ case "facebook":
83
+ oauthUrl = `https://www.facebook.com/v17.0/dialog/oauth?${params}`;
84
+ break;
85
+ case "twitch":
86
+ params.set("force_verify", "true");
87
+ oauthUrl = `https://id.twitch.tv/oauth2/authorize?${params}`;
88
+ break;
89
+ default: throw new Error(`Invalid provider: ${input.provider}`);
90
+ }
91
+ this.$zkLoginState.set({ provider: input.provider });
92
+ if (this.#useNativeCryptoSigner) await set("ephemeralKeyPair", ephemeralKeyPair.export(), this.#idbStore);
93
+ await this.#setSession({
94
+ expiresAt: estimatedExpiration,
95
+ maxEpoch,
96
+ randomness,
97
+ ephemeralKeyPair: this.#useNativeCryptoSigner ? "@@native" : toBase64(decodeSuiPrivateKey(ephemeralKeyPair.getSecretKey()).secretKey)
98
+ });
99
+ return oauthUrl;
100
+ }
101
+ async handleAuthCallback(hash = window.location.hash) {
102
+ const params = new URLSearchParams(hash.startsWith("#") ? hash.slice(1) : hash);
103
+ const zkp = await this.getSession();
104
+ if (!zkp || !zkp.ephemeralKeyPair || !zkp.maxEpoch || !zkp.randomness) throw new Error("Start of sign-in flow could not be found. Ensure you have started the sign-in flow before calling this.");
105
+ const jwt = params.get("id_token");
106
+ if (!jwt) throw new Error("Missing ID Token");
107
+ decodeJwt(jwt);
108
+ const { address, salt, publicKey } = await this.#enokiClient.getZkLogin({ jwt });
109
+ this.$zkLoginState.set({
110
+ ...this.$zkLoginState.get(),
111
+ salt,
112
+ address,
113
+ publicKey
114
+ });
115
+ await this.#setSession({
116
+ ...zkp,
117
+ jwt
118
+ });
119
+ return params.get("state");
120
+ }
121
+ async #setSession(newValue) {
122
+ if (newValue) {
123
+ const storedValue = await this.#encryption.encrypt(this.#encryptionKey, JSON.stringify(newValue));
124
+ this.#store.set(this.#storageKeys.SESSION, storedValue);
125
+ } else this.#store.delete(this.#storageKeys.SESSION);
126
+ this.$zkLoginSession.set({
127
+ initialized: true,
128
+ value: newValue
129
+ });
130
+ }
131
+ async getSession() {
132
+ if (this.$zkLoginSession.get().initialized) return this.$zkLoginSession.get().value;
133
+ try {
134
+ const storedValue = this.#store.get(this.#storageKeys.SESSION);
135
+ if (!storedValue) return null;
136
+ const state = JSON.parse(await this.#encryption.decrypt(this.#encryptionKey, storedValue));
137
+ if (state?.expiresAt && Date.now() > state.expiresAt) await this.logout();
138
+ else this.$zkLoginSession.set({
139
+ initialized: true,
140
+ value: state
141
+ });
142
+ } catch {
143
+ this.$zkLoginSession.set({
144
+ initialized: true,
145
+ value: null
146
+ });
147
+ }
148
+ return this.$zkLoginSession.get().value;
149
+ }
150
+ async logout() {
151
+ this.$zkLoginState.set({});
152
+ this.#store.delete(this.#storageKeys.STATE);
153
+ if (this.#useNativeCryptoSigner) await clear(this.#idbStore);
154
+ await this.#setSession(null);
155
+ }
156
+ async getProof({ network } = {}) {
157
+ const zkp = await this.getSession();
158
+ const { salt } = this.$zkLoginState.get();
159
+ if (zkp?.proof) {
160
+ if (zkp.expiresAt && Date.now() > zkp.expiresAt) throw new Error("Stored proof is expired.");
161
+ return zkp.proof;
162
+ }
163
+ if (!salt || !zkp || !zkp.jwt) throw new Error("Missing required parameters for proof generation");
164
+ let storedNativeSigner = void 0;
165
+ if (this.#useNativeCryptoSigner && zkp.ephemeralKeyPair === "@@native") {
166
+ storedNativeSigner = await get("ephemeralKeyPair", this.#idbStore);
167
+ if (!storedNativeSigner) throw new Error("Native signer not found in store.");
168
+ }
169
+ const ephemeralKeyPair = zkp.ephemeralKeyPair === "@@native" ? WebCryptoSigner.import(storedNativeSigner) : Ed25519Keypair.fromSecretKey(fromBase64(zkp.ephemeralKeyPair));
170
+ const proof = await this.#enokiClient.createZkLoginZkp({
171
+ network,
172
+ jwt: zkp.jwt,
173
+ maxEpoch: zkp.maxEpoch,
174
+ randomness: zkp.randomness,
175
+ ephemeralPublicKey: ephemeralKeyPair.getPublicKey()
176
+ });
177
+ await this.#setSession({
178
+ ...zkp,
179
+ proof
180
+ });
181
+ return proof;
182
+ }
183
+ async getKeypair({ network } = {}) {
184
+ await this.getProof({ network });
185
+ const zkp = await this.getSession();
186
+ const { address } = this.$zkLoginState.get();
187
+ if (!address || !zkp || !zkp.proof) throw new Error("Missing required data for keypair generation.");
188
+ if (Date.now() > zkp.expiresAt) throw new Error("Stored proof is expired.");
189
+ let storedNativeSigner = void 0;
190
+ if (this.#useNativeCryptoSigner && zkp.ephemeralKeyPair === "@@native") {
191
+ storedNativeSigner = await get("ephemeralKeyPair", this.#idbStore);
192
+ if (!storedNativeSigner) throw new Error("Native signer not found in store.");
193
+ }
194
+ return new EnokiKeypair({
195
+ address,
196
+ ephemeralKeypair: zkp.ephemeralKeyPair === "@@native" ? WebCryptoSigner.import(storedNativeSigner) : Ed25519Keypair.fromSecretKey(fromBase64(zkp.ephemeralKeyPair)),
197
+ maxEpoch: zkp.maxEpoch,
198
+ proof: zkp.proof
199
+ });
200
+ }
201
+ };
202
+
203
+ //#endregion
204
+ export { EnokiFlow };
205
+ //# sourceMappingURL=EnokiFlow.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"EnokiFlow.mjs","names":["#enokiClient","#encryptionKey","#useNativeCryptoSigner","#idbStore","#encryption","#store","#storageKeys","#setSession"],"sources":["../src/EnokiFlow.ts"],"sourcesContent":["// Copyright (c) Mysten Labs, Inc.\n// SPDX-License-Identifier: Apache-2.0\n\nimport type { ExportedWebCryptoKeypair } from '@mysten/signers/webcrypto';\nimport { WebCryptoSigner } from '@mysten/signers/webcrypto';\nimport { decodeSuiPrivateKey } from '@mysten/sui/cryptography';\nimport { Ed25519Keypair } from '@mysten/sui/keypairs/ed25519';\nimport { fromBase64, toBase64 } from '@mysten/sui/utils';\nimport { decodeJwt } from '@mysten/sui/zklogin';\nimport type { ZkLoginSignatureInputs } from '@mysten/sui/zklogin';\nimport type { UseStore } from 'idb-keyval';\nimport { clear, createStore, get, set } from 'idb-keyval';\nimport type { WritableAtom } from 'nanostores';\nimport { atom, onMount, onSet } from 'nanostores';\n\nimport type { Encryption } from './encryption.js';\nimport { createDefaultEncryption } from './encryption.js';\nimport type { EnokiClientConfig } from './EnokiClient/index.js';\nimport { EnokiClient } from './EnokiClient/index.js';\nimport type { AuthProvider, EnokiNetwork } from './EnokiClient/type.js';\nimport { EnokiKeypair } from './EnokiKeypair.js';\nimport type { SyncStore } from './stores.js';\nimport { createSessionStorage } from './stores.js';\n\n/**\n * @deprecated Use `RegisterEnokiWalletsOptions` instead\n */\nexport type EnokiFlowConfig = EnokiClientConfig &\n\t(\n\t\t| {\n\t\t\t\texperimental_nativeCryptoSigner?: unknown;\n\t\t\t\t/**\n\t\t\t\t * The storage interface to persist Enoki data locally.\n\t\t\t\t * If not provided, it will use a sessionStorage-backed store.\n\t\t\t\t */\n\t\t\t\tstore?: SyncStore;\n\t\t\t\t/**\n\t\t\t\t * The encryption interface that will be used to encrypt data before storing it locally.\n\t\t\t\t * If not provided, it will use a default encryption interface.\n\t\t\t\t */\n\t\t\t\tencryption?: Encryption;\n\t\t }\n\t\t| {\n\t\t\t\tstore?: never;\n\t\t\t\tencryption?: never;\n\t\t\t\t/**\n\t\t\t\t * Enables the new native crypto signer for the EnokiFlow, which is more secure.\n\t\t\t\t */\n\t\t\t\texperimental_nativeCryptoSigner: true;\n\t\t }\n\t);\n\n// State that is not bound to a session, and is encrypted.\nexport interface ZkLoginState {\n\tprovider?: AuthProvider;\n\taddress?: string;\n\tsalt?: string;\n\tpublicKey?: string;\n}\n\n// State that session-bound, and is encrypted in storage.\nexport interface ZkLoginSession {\n\tephemeralKeyPair: string;\n\tmaxEpoch: number;\n\trandomness: string;\n\texpiresAt: number;\n\n\tjwt?: string;\n\tproof?: ZkLoginSignatureInputs;\n}\n\nconst createStorageKeys = (apiKey: string) => ({\n\tSTATE: `@enoki/flow/state/${apiKey}`,\n\tSESSION: `@enoki/flow/session/${apiKey}`,\n});\n\n/**\n * @deprecated Use `registerEnokiWallets` instead\n */\nexport class EnokiFlow {\n\t#storageKeys: { STATE: string; SESSION: string };\n\t#enokiClient: EnokiClient;\n\t#encryption: Encryption;\n\t#encryptionKey: string;\n\t#store: SyncStore;\n\t#useNativeCryptoSigner: boolean;\n\t#idbStore?: UseStore;\n\n\t$zkLoginSession: WritableAtom<{ initialized: boolean; value: ZkLoginSession | null }>;\n\t$zkLoginState: WritableAtom<ZkLoginState>;\n\n\tconstructor(config: EnokiFlowConfig) {\n\t\tthis.#enokiClient = new EnokiClient({\n\t\t\tapiKey: config.apiKey,\n\t\t\tapiUrl: config.apiUrl,\n\t\t\tadditionalEpochs: config.additionalEpochs,\n\t\t});\n\t\tthis.#encryptionKey = config.apiKey;\n\n\t\tif (config.experimental_nativeCryptoSigner) {\n\t\t\tthis.#useNativeCryptoSigner = true;\n\t\t\tthis.#idbStore = createStore(config.apiKey, 'enoki');\n\t\t} else {\n\t\t\tthis.#useNativeCryptoSigner = false;\n\t\t}\n\n\t\tthis.#encryption = config.encryption ?? createDefaultEncryption();\n\t\tthis.#store = config.store ?? createSessionStorage();\n\t\tthis.#storageKeys = createStorageKeys(config.apiKey);\n\n\t\tlet storedState = null;\n\t\ttry {\n\t\t\tconst rawStoredValue = this.#store.get(this.#storageKeys.STATE);\n\t\t\tif (rawStoredValue) {\n\t\t\t\tstoredState = JSON.parse(rawStoredValue);\n\t\t\t}\n\t\t} catch {\n\t\t\t// Ignore errors\n\t\t}\n\n\t\tthis.$zkLoginState = atom(storedState || {});\n\t\tthis.$zkLoginSession = atom({ initialized: false, value: null });\n\n\t\t// Hydrate the session on mount:\n\t\tonMount(this.$zkLoginSession, () => {\n\t\t\tthis.getSession();\n\t\t});\n\n\t\tonSet(this.$zkLoginState, ({ newValue }) => {\n\t\t\tthis.#store.set(this.#storageKeys.STATE, JSON.stringify(newValue));\n\t\t});\n\t}\n\n\tget enokiClient() {\n\t\treturn this.#enokiClient;\n\t}\n\n\tasync createAuthorizationURL(input: {\n\t\tprovider: AuthProvider;\n\t\tclientId: string;\n\t\tredirectUrl: string;\n\t\tnetwork?: 'mainnet' | 'testnet' | 'devnet';\n\t\textraParams?: Record<string, unknown>;\n\t}) {\n\t\tconst ephemeralKeyPair = this.#useNativeCryptoSigner\n\t\t\t? await WebCryptoSigner.generate()\n\t\t\t: new Ed25519Keypair();\n\n\t\tconst { nonce, randomness, maxEpoch, estimatedExpiration } =\n\t\t\tawait this.#enokiClient.createZkLoginNonce({\n\t\t\t\tnetwork: input.network,\n\t\t\t\tephemeralPublicKey: ephemeralKeyPair.getPublicKey(),\n\t\t\t});\n\n\t\tconst params = new URLSearchParams({\n\t\t\t...input.extraParams,\n\t\t\tnonce,\n\t\t\tclient_id: input.clientId,\n\t\t\tredirect_uri: input.redirectUrl,\n\t\t\tresponse_type: 'id_token',\n\t\t\t// TODO: Eventually fetch the scopes for this client ID from the Enoki service:\n\t\t\tscope: [\n\t\t\t\t'openid',\n\t\t\t\t// Merge the requested scopes in with the required openid scopes:\n\t\t\t\t...(input.extraParams && 'scope' in input.extraParams\n\t\t\t\t\t? (input.extraParams.scope as string[])\n\t\t\t\t\t: []),\n\t\t\t]\n\t\t\t\t.filter(Boolean)\n\t\t\t\t.join(' '),\n\t\t});\n\n\t\tlet oauthUrl: string;\n\t\tswitch (input.provider) {\n\t\t\tcase 'google': {\n\t\t\t\toauthUrl = `https://accounts.google.com/o/oauth2/v2/auth?${params}`;\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase 'facebook': {\n\t\t\t\toauthUrl = `https://www.facebook.com/v17.0/dialog/oauth?${params}`;\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase 'twitch': {\n\t\t\t\tparams.set('force_verify', 'true');\n\t\t\t\toauthUrl = `https://id.twitch.tv/oauth2/authorize?${params}`;\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tdefault:\n\t\t\t\tthrow new Error(`Invalid provider: ${input.provider}`);\n\t\t}\n\n\t\tthis.$zkLoginState.set({ provider: input.provider });\n\t\tif (this.#useNativeCryptoSigner) {\n\t\t\tawait set('ephemeralKeyPair', (ephemeralKeyPair as WebCryptoSigner).export(), this.#idbStore);\n\t\t}\n\n\t\tawait this.#setSession({\n\t\t\texpiresAt: estimatedExpiration,\n\t\t\tmaxEpoch,\n\t\t\trandomness,\n\t\t\tephemeralKeyPair: this.#useNativeCryptoSigner\n\t\t\t\t? '@@native'\n\t\t\t\t: toBase64(\n\t\t\t\t\t\tdecodeSuiPrivateKey((ephemeralKeyPair as Ed25519Keypair).getSecretKey()).secretKey,\n\t\t\t\t\t),\n\t\t});\n\n\t\treturn oauthUrl;\n\t}\n\n\t// TODO: Should our SDK manage this automatically in addition to exposing a method?\n\tasync handleAuthCallback(hash: string = window.location.hash) {\n\t\tconst params = new URLSearchParams(hash.startsWith('#') ? hash.slice(1) : hash);\n\n\t\t// Before we handle the auth redirect and get the state, we need to restore it:\n\t\tconst zkp = await this.getSession();\n\n\t\tif (!zkp || !zkp.ephemeralKeyPair || !zkp.maxEpoch || !zkp.randomness) {\n\t\t\tthrow new Error(\n\t\t\t\t'Start of sign-in flow could not be found. Ensure you have started the sign-in flow before calling this.',\n\t\t\t);\n\t\t}\n\n\t\tconst jwt = params.get('id_token');\n\t\tif (!jwt) {\n\t\t\tthrow new Error('Missing ID Token');\n\t\t}\n\n\t\tdecodeJwt(jwt);\n\n\t\tconst { address, salt, publicKey } = await this.#enokiClient.getZkLogin({ jwt });\n\n\t\tthis.$zkLoginState.set({\n\t\t\t...this.$zkLoginState.get(),\n\t\t\tsalt,\n\t\t\taddress,\n\t\t\tpublicKey,\n\t\t});\n\t\tawait this.#setSession({\n\t\t\t...zkp,\n\t\t\tjwt,\n\t\t});\n\n\t\treturn params.get('state');\n\t}\n\n\tasync #setSession(newValue: ZkLoginSession | null) {\n\t\tif (newValue) {\n\t\t\tconst storedValue = await this.#encryption.encrypt(\n\t\t\t\tthis.#encryptionKey,\n\t\t\t\tJSON.stringify(newValue),\n\t\t\t);\n\n\t\t\tthis.#store.set(this.#storageKeys.SESSION, storedValue);\n\t\t} else {\n\t\t\tthis.#store.delete(this.#storageKeys.SESSION);\n\t\t}\n\n\t\tthis.$zkLoginSession.set({ initialized: true, value: newValue });\n\t}\n\n\tasync getSession() {\n\t\tif (this.$zkLoginSession.get().initialized) {\n\t\t\treturn this.$zkLoginSession.get().value;\n\t\t}\n\n\t\ttry {\n\t\t\tconst storedValue = this.#store.get(this.#storageKeys.SESSION);\n\t\t\tif (!storedValue) return null;\n\n\t\t\tconst state: ZkLoginSession = JSON.parse(\n\t\t\t\tawait this.#encryption.decrypt(this.#encryptionKey, storedValue),\n\t\t\t);\n\n\t\t\t// TODO: Rather than having expiration act as a logout, we should keep the state that still is relevant,\n\t\t\t// and just clear out the expired session, but keep the other zkLogin state.\n\t\t\tif (state?.expiresAt && Date.now() > state.expiresAt) {\n\t\t\t\tawait this.logout();\n\t\t\t} else {\n\t\t\t\tthis.$zkLoginSession.set({ initialized: true, value: state });\n\t\t\t}\n\t\t} catch {\n\t\t\tthis.$zkLoginSession.set({ initialized: true, value: null });\n\t\t}\n\n\t\treturn this.$zkLoginSession.get().value;\n\t}\n\n\tasync logout() {\n\t\tthis.$zkLoginState.set({});\n\t\tthis.#store.delete(this.#storageKeys.STATE);\n\n\t\tif (this.#useNativeCryptoSigner) {\n\t\t\tawait clear(this.#idbStore);\n\t\t}\n\t\tawait this.#setSession(null);\n\t}\n\n\t// TODO: Should this return the proof if it already exists?\n\tasync getProof({ network }: { network?: EnokiNetwork } = {}) {\n\t\tconst zkp = await this.getSession();\n\t\tconst { salt } = this.$zkLoginState.get();\n\n\t\tif (zkp?.proof) {\n\t\t\tif (zkp.expiresAt && Date.now() > zkp.expiresAt) {\n\t\t\t\tthrow new Error('Stored proof is expired.');\n\t\t\t}\n\n\t\t\treturn zkp.proof;\n\t\t}\n\n\t\tif (!salt || !zkp || !zkp.jwt) {\n\t\t\tthrow new Error('Missing required parameters for proof generation');\n\t\t}\n\n\t\tlet storedNativeSigner: ExportedWebCryptoKeypair | undefined = undefined;\n\t\tif (this.#useNativeCryptoSigner && zkp.ephemeralKeyPair === '@@native') {\n\t\t\tstoredNativeSigner = await get('ephemeralKeyPair', this.#idbStore);\n\t\t\tif (!storedNativeSigner) {\n\t\t\t\tthrow new Error('Native signer not found in store.');\n\t\t\t}\n\t\t}\n\n\t\tconst ephemeralKeyPair =\n\t\t\tzkp.ephemeralKeyPair === '@@native'\n\t\t\t\t? WebCryptoSigner.import(storedNativeSigner!)\n\t\t\t\t: Ed25519Keypair.fromSecretKey(fromBase64(zkp.ephemeralKeyPair));\n\n\t\tconst proof = await this.#enokiClient.createZkLoginZkp({\n\t\t\tnetwork,\n\t\t\tjwt: zkp.jwt,\n\t\t\tmaxEpoch: zkp.maxEpoch,\n\t\t\trandomness: zkp.randomness,\n\t\t\tephemeralPublicKey: ephemeralKeyPair.getPublicKey(),\n\t\t});\n\n\t\tawait this.#setSession({\n\t\t\t...zkp,\n\t\t\tproof,\n\t\t});\n\n\t\treturn proof;\n\t}\n\n\tasync getKeypair({ network }: { network?: EnokiNetwork } = {}) {\n\t\t// Get the proof, so that we ensure it exists in state:\n\t\tawait this.getProof({ network });\n\n\t\tconst zkp = await this.getSession();\n\n\t\t// Check to see if we have the essentials for a keypair:\n\t\tconst { address } = this.$zkLoginState.get();\n\t\tif (!address || !zkp || !zkp.proof) {\n\t\t\tthrow new Error('Missing required data for keypair generation.');\n\t\t}\n\n\t\tif (Date.now() > zkp.expiresAt) {\n\t\t\tthrow new Error('Stored proof is expired.');\n\t\t}\n\n\t\tlet storedNativeSigner: ExportedWebCryptoKeypair | undefined = undefined;\n\t\tif (this.#useNativeCryptoSigner && zkp.ephemeralKeyPair === '@@native') {\n\t\t\tstoredNativeSigner = await get('ephemeralKeyPair', this.#idbStore);\n\t\t\tif (!storedNativeSigner) {\n\t\t\t\tthrow new Error('Native signer not found in store.');\n\t\t\t}\n\t\t}\n\n\t\tconst ephemeralKeypair =\n\t\t\tzkp.ephemeralKeyPair === '@@native'\n\t\t\t\t? WebCryptoSigner.import(storedNativeSigner!)\n\t\t\t\t: Ed25519Keypair.fromSecretKey(fromBase64(zkp.ephemeralKeyPair));\n\n\t\treturn new EnokiKeypair({\n\t\t\taddress,\n\t\t\tephemeralKeypair,\n\t\t\tmaxEpoch: zkp.maxEpoch,\n\t\t\tproof: zkp.proof,\n\t\t});\n\t}\n}\n"],"mappings":";;;;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C;;AAStD,SAAO,IAAI,aAAa;GACvB;GACA,kBANA,IAAI,qBAAqB,aACtB,gBAAgB,OAAO,mBAAoB,GAC3C,eAAe,cAAc,WAAW,IAAI,iBAAiB,CAAC;GAKjE,UAAU,IAAI;GACd,OAAO,IAAI;GACX,CAAC"}
@@ -0,0 +1,23 @@
1
+ import * as _mysten_sui_cryptography0 from "@mysten/sui/cryptography";
2
+ import { SignatureWithBytes, Signer } from "@mysten/sui/cryptography";
3
+ import { ZkLoginPublicIdentifier, ZkLoginSignatureInputs } from "@mysten/sui/zklogin";
4
+
5
+ //#region src/EnokiKeypair.d.ts
6
+ declare class EnokiPublicKey extends ZkLoginPublicIdentifier {}
7
+ declare class EnokiKeypair extends Signer {
8
+ #private;
9
+ constructor(input: {
10
+ address: string;
11
+ maxEpoch: number;
12
+ proof: ZkLoginSignatureInputs;
13
+ ephemeralKeypair: Signer;
14
+ });
15
+ sign(data: Uint8Array): Promise<Uint8Array<ArrayBuffer>>;
16
+ signPersonalMessage(bytes: Uint8Array): Promise<SignatureWithBytes>;
17
+ signTransaction(bytes: Uint8Array): Promise<SignatureWithBytes>;
18
+ getKeyScheme(): _mysten_sui_cryptography0.SignatureScheme;
19
+ getPublicKey(): EnokiPublicKey;
20
+ }
21
+ //#endregion
22
+ export { EnokiKeypair, EnokiPublicKey };
23
+ //# sourceMappingURL=EnokiKeypair.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"EnokiKeypair.d.mts","names":[],"sources":["../src/EnokiKeypair.ts"],"sourcesContent":[],"mappings":";;;;;cAQa,cAAA,SAAuB,uBAAA;AAEvB,cAAA,YAAA,SAAqB,MAAA,CAAR;EASjB,CAAA,OAAA;EACW,WAAA,CAAA,KAAA,EAAA;IASF,OAAA,EAAA,MAAA;IAAU,QAAA,EAAA,MAAA;IAAA,KAAA,EAVnB,sBAUmB;IAAA,gBAAA,EATR,MASQ;EAIM,CAAA;EAAqB,IAAA,CAAA,IAAA,EAJrC,UAIqC,CAAA,EAJ3B,OAI2B,CAJ3B,UAI2B,CAJ3B,WAI2B,CAAA,CAAA;EAAR,mBAAA,CAAA,KAAA,EAAb,UAAa,CAAA,EAAA,OAAA,CAAQ,kBAAR,CAAA;EAgBjB,eAAA,CAAA,KAAA,EAAA,UAAA,CAAA,EAAa,OAAb,CAAqB,kBAArB,CAAA;EAAqB,YAAA,CAAA,CAAA,EAAD,yBAAA,CAgBrC,eAhBsC;EAAR,YAAA,CAAA,CAAA,EAoB9B,cApB8B"}
@@ -0,0 +1,53 @@
1
+ import { Signer } from "@mysten/sui/cryptography";
2
+ import { ZkLoginPublicIdentifier, getZkLoginSignature } from "@mysten/sui/zklogin";
3
+
4
+ //#region src/EnokiKeypair.ts
5
+ var EnokiPublicKey = class extends ZkLoginPublicIdentifier {};
6
+ var EnokiKeypair = class extends Signer {
7
+ #proof;
8
+ #maxEpoch;
9
+ #ephemeralKeypair;
10
+ #publicKey;
11
+ constructor(input) {
12
+ super();
13
+ this.#proof = input.proof;
14
+ this.#maxEpoch = input.maxEpoch;
15
+ this.#ephemeralKeypair = input.ephemeralKeypair;
16
+ this.#publicKey = EnokiPublicKey.fromProof(input.address, input.proof);
17
+ }
18
+ async sign(data) {
19
+ return this.#ephemeralKeypair.sign(data);
20
+ }
21
+ async signPersonalMessage(bytes) {
22
+ const { bytes: signedBytes, signature: userSignature } = await this.#ephemeralKeypair.signPersonalMessage(bytes);
23
+ return {
24
+ bytes: signedBytes,
25
+ signature: getZkLoginSignature({
26
+ inputs: this.#proof,
27
+ maxEpoch: this.#maxEpoch,
28
+ userSignature
29
+ })
30
+ };
31
+ }
32
+ async signTransaction(bytes) {
33
+ const { bytes: signedBytes, signature: userSignature } = await this.#ephemeralKeypair.signTransaction(bytes);
34
+ return {
35
+ bytes: signedBytes,
36
+ signature: getZkLoginSignature({
37
+ inputs: this.#proof,
38
+ maxEpoch: this.#maxEpoch,
39
+ userSignature
40
+ })
41
+ };
42
+ }
43
+ getKeyScheme() {
44
+ return this.#ephemeralKeypair.getKeyScheme();
45
+ }
46
+ getPublicKey() {
47
+ return this.#publicKey;
48
+ }
49
+ };
50
+
51
+ //#endregion
52
+ export { EnokiKeypair, EnokiPublicKey };
53
+ //# sourceMappingURL=EnokiKeypair.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"EnokiKeypair.mjs","names":["#proof","#maxEpoch","#ephemeralKeypair","#publicKey"],"sources":["../src/EnokiKeypair.ts"],"sourcesContent":["// Copyright (c) Mysten Labs, Inc.\n// SPDX-License-Identifier: Apache-2.0\n\nimport type { SignatureWithBytes } from '@mysten/sui/cryptography';\nimport { Signer } from '@mysten/sui/cryptography';\nimport type { ZkLoginSignatureInputs } from '@mysten/sui/zklogin';\nimport { getZkLoginSignature, ZkLoginPublicIdentifier } from '@mysten/sui/zklogin';\n\nexport class EnokiPublicKey extends ZkLoginPublicIdentifier {}\n\nexport class EnokiKeypair extends Signer {\n\t#proof: ZkLoginSignatureInputs;\n\t#maxEpoch: number;\n\t#ephemeralKeypair: Signer;\n\t#publicKey: EnokiPublicKey;\n\n\tconstructor(input: {\n\t\taddress: string;\n\t\tmaxEpoch: number;\n\t\tproof: ZkLoginSignatureInputs;\n\t\tephemeralKeypair: Signer;\n\t}) {\n\t\tsuper();\n\t\tthis.#proof = input.proof;\n\t\tthis.#maxEpoch = input.maxEpoch;\n\t\tthis.#ephemeralKeypair = input.ephemeralKeypair;\n\t\tthis.#publicKey = EnokiPublicKey.fromProof(input.address, input.proof);\n\t}\n\n\tasync sign(data: Uint8Array) {\n\t\treturn this.#ephemeralKeypair.sign(data);\n\t}\n\n\tasync signPersonalMessage(bytes: Uint8Array): Promise<SignatureWithBytes> {\n\t\tconst { bytes: signedBytes, signature: userSignature } =\n\t\t\tawait this.#ephemeralKeypair.signPersonalMessage(bytes);\n\n\t\tconst zkSignature = getZkLoginSignature({\n\t\t\tinputs: this.#proof,\n\t\t\tmaxEpoch: this.#maxEpoch,\n\t\t\tuserSignature,\n\t\t});\n\n\t\treturn {\n\t\t\tbytes: signedBytes,\n\t\t\tsignature: zkSignature,\n\t\t};\n\t}\n\n\tasync signTransaction(bytes: Uint8Array): Promise<SignatureWithBytes> {\n\t\tconst { bytes: signedBytes, signature: userSignature } =\n\t\t\tawait this.#ephemeralKeypair.signTransaction(bytes);\n\n\t\tconst zkSignature = getZkLoginSignature({\n\t\t\tinputs: this.#proof,\n\t\t\tmaxEpoch: this.#maxEpoch,\n\t\t\tuserSignature,\n\t\t});\n\n\t\treturn {\n\t\t\tbytes: signedBytes,\n\t\t\tsignature: zkSignature,\n\t\t};\n\t}\n\n\tgetKeyScheme() {\n\t\treturn this.#ephemeralKeypair.getKeyScheme();\n\t}\n\n\tgetPublicKey() {\n\t\treturn this.#publicKey;\n\t}\n}\n"],"mappings":";;;;AAQA,IAAa,iBAAb,cAAoC,wBAAwB;AAE5D,IAAa,eAAb,cAAkC,OAAO;CACxC;CACA;CACA;CACA;CAEA,YAAY,OAKT;AACF,SAAO;AACP,QAAKA,QAAS,MAAM;AACpB,QAAKC,WAAY,MAAM;AACvB,QAAKC,mBAAoB,MAAM;AAC/B,QAAKC,YAAa,eAAe,UAAU,MAAM,SAAS,MAAM,MAAM;;CAGvE,MAAM,KAAK,MAAkB;AAC5B,SAAO,MAAKD,iBAAkB,KAAK,KAAK;;CAGzC,MAAM,oBAAoB,OAAgD;EACzE,MAAM,EAAE,OAAO,aAAa,WAAW,kBACtC,MAAM,MAAKA,iBAAkB,oBAAoB,MAAM;AAQxD,SAAO;GACN,OAAO;GACP,WARmB,oBAAoB;IACvC,QAAQ,MAAKF;IACb,UAAU,MAAKC;IACf;IACA,CAAC;GAKD;;CAGF,MAAM,gBAAgB,OAAgD;EACrE,MAAM,EAAE,OAAO,aAAa,WAAW,kBACtC,MAAM,MAAKC,iBAAkB,gBAAgB,MAAM;AAQpD,SAAO;GACN,OAAO;GACP,WARmB,oBAAoB;IACvC,QAAQ,MAAKF;IACb,UAAU,MAAKC;IACf;IACA,CAAC;GAKD;;CAGF,eAAe;AACd,SAAO,MAAKC,iBAAkB,cAAc;;CAG7C,eAAe;AACd,SAAO,MAAKC"}
@@ -0,0 +1,15 @@
1
+ //#region src/encryption.d.ts
2
+ /**
3
+ * A general interface for specifying how data should be encrypted and decrypted.
4
+ */
5
+ interface Encryption {
6
+ encrypt(password: string, data: string): Promise<string>;
7
+ decrypt(password: string, data: string): Promise<string>;
8
+ }
9
+ /**
10
+ * Create the default encryption interface, which uses the browsers built-in crypto primitives.
11
+ */
12
+ declare function createDefaultEncryption(): Encryption;
13
+ //#endregion
14
+ export { Encryption, createDefaultEncryption };
15
+ //# sourceMappingURL=encryption.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"encryption.d.mts","names":[],"sources":["../src/encryption.ts"],"sourcesContent":[],"mappings":";;AAQA;AAQA;UARiB,UAAA;2CACyB;2CACA;;;;;iBAM1B,uBAAA,CAAA,GAA2B"}
@@ -0,0 +1,53 @@
1
+ import { fromBase64, toBase64 } from "@mysten/sui/utils";
2
+
3
+ //#region src/encryption.ts
4
+ /**
5
+ * Create the default encryption interface, which uses the browsers built-in crypto primitives.
6
+ */
7
+ function createDefaultEncryption() {
8
+ async function keyFromPassword(password, salt) {
9
+ const key = await crypto.subtle.importKey("raw", new TextEncoder().encode(password), { name: "PBKDF2" }, false, ["deriveBits", "deriveKey"]);
10
+ return {
11
+ key,
12
+ derivedKey: await crypto.subtle.deriveKey({
13
+ name: "PBKDF2",
14
+ salt,
15
+ iterations: 9e5,
16
+ hash: "SHA-256"
17
+ }, key, {
18
+ name: "AES-GCM",
19
+ length: 256
20
+ }, false, ["encrypt", "decrypt"])
21
+ };
22
+ }
23
+ return {
24
+ async encrypt(password, data) {
25
+ const salt = crypto.getRandomValues(new Uint8Array(16));
26
+ const iv = crypto.getRandomValues(new Uint8Array(12));
27
+ const { derivedKey } = await keyFromPassword(password, salt);
28
+ const payload = await crypto.subtle.encrypt({
29
+ name: "AES-GCM",
30
+ iv
31
+ }, derivedKey, new TextEncoder().encode(data));
32
+ return JSON.stringify({
33
+ payload: toBase64(new Uint8Array(payload)),
34
+ iv: toBase64(iv),
35
+ salt: toBase64(salt)
36
+ });
37
+ },
38
+ async decrypt(password, data) {
39
+ const parsed = JSON.parse(data);
40
+ if (!parsed.payload || !parsed.iv || !parsed.salt) throw new Error("Invalid encrypted data");
41
+ const { derivedKey } = await keyFromPassword(password, fromBase64(parsed.salt));
42
+ const decryptedContent = await crypto.subtle.decrypt({
43
+ name: "AES-GCM",
44
+ iv: fromBase64(parsed.iv)
45
+ }, derivedKey, fromBase64(parsed.payload));
46
+ return new TextDecoder().decode(decryptedContent);
47
+ }
48
+ };
49
+ }
50
+
51
+ //#endregion
52
+ export { createDefaultEncryption };
53
+ //# sourceMappingURL=encryption.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"encryption.mjs","names":[],"sources":["../src/encryption.ts"],"sourcesContent":["// Copyright (c) Mysten Labs, Inc.\n// SPDX-License-Identifier: Apache-2.0\n\nimport { fromBase64, toBase64 } from '@mysten/sui/utils';\n\n/**\n * A general interface for specifying how data should be encrypted and decrypted.\n */\nexport interface Encryption {\n\tencrypt(password: string, data: string): Promise<string>;\n\tdecrypt(password: string, data: string): Promise<string>;\n}\n\n/**\n * Create the default encryption interface, which uses the browsers built-in crypto primitives.\n */\nexport function createDefaultEncryption(): Encryption {\n\ttype EncryptedJSON = {\n\t\tpayload: string;\n\t\tiv: string;\n\t\tsalt: string;\n\t};\n\n\tasync function keyFromPassword(password: string, salt: Uint8Array) {\n\t\tconst key = await crypto.subtle.importKey(\n\t\t\t'raw',\n\t\t\tnew TextEncoder().encode(password),\n\t\t\t{ name: 'PBKDF2' },\n\t\t\tfalse,\n\t\t\t['deriveBits', 'deriveKey'],\n\t\t);\n\n\t\tconst derivedKey = await crypto.subtle.deriveKey(\n\t\t\t{\n\t\t\t\tname: 'PBKDF2',\n\t\t\t\tsalt: salt as BufferSource,\n\t\t\t\titerations: 900_000,\n\t\t\t\thash: 'SHA-256',\n\t\t\t},\n\t\t\tkey,\n\t\t\t{ name: 'AES-GCM', length: 256 },\n\t\t\tfalse,\n\t\t\t['encrypt', 'decrypt'],\n\t\t);\n\n\t\treturn { key, derivedKey };\n\t}\n\n\treturn {\n\t\tasync encrypt(password, data) {\n\t\t\tconst salt = crypto.getRandomValues(new Uint8Array(16));\n\t\t\tconst iv = crypto.getRandomValues(new Uint8Array(12));\n\n\t\t\tconst { derivedKey } = await keyFromPassword(password, salt);\n\n\t\t\tconst payload = await crypto.subtle.encrypt(\n\t\t\t\t{\n\t\t\t\t\tname: 'AES-GCM',\n\t\t\t\t\tiv,\n\t\t\t\t},\n\t\t\t\tderivedKey,\n\t\t\t\tnew TextEncoder().encode(data),\n\t\t\t);\n\n\t\t\treturn JSON.stringify({\n\t\t\t\tpayload: toBase64(new Uint8Array(payload)),\n\t\t\t\tiv: toBase64(iv),\n\t\t\t\tsalt: toBase64(salt),\n\t\t\t} satisfies EncryptedJSON);\n\t\t},\n\t\tasync decrypt(password, data) {\n\t\t\tconst parsed = JSON.parse(data) as EncryptedJSON;\n\t\t\tif (!parsed.payload || !parsed.iv || !parsed.salt) {\n\t\t\t\tthrow new Error('Invalid encrypted data');\n\t\t\t}\n\n\t\t\tconst { derivedKey } = await keyFromPassword(password, fromBase64(parsed.salt));\n\n\t\t\tconst decryptedContent = await crypto.subtle.decrypt(\n\t\t\t\t{\n\t\t\t\t\tname: 'AES-GCM',\n\t\t\t\t\tiv: fromBase64(parsed.iv),\n\t\t\t\t},\n\t\t\t\tderivedKey,\n\t\t\t\tfromBase64(parsed.payload),\n\t\t\t);\n\n\t\t\treturn new TextDecoder().decode(decryptedContent);\n\t\t},\n\t};\n}\n\n/**\n * Create a passthrough encryption interface, which does not encrypt or decrypt data.\n */\nexport function createPassthroughEncryption(): Encryption {\n\treturn {\n\t\tasync encrypt(_password, data) {\n\t\t\treturn data;\n\t\t},\n\t\tasync decrypt(_password, data) {\n\t\t\treturn data;\n\t\t},\n\t};\n}\n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AC,OAAO,iBAAiB;;EAElD"}
@@ -0,0 +1,13 @@
1
+ import { AuthProvider, EnokiNetwork } from "./EnokiClient/type.mjs";
2
+ import { EnokiClient, EnokiClientConfig, EnokiClientError } from "./EnokiClient/index.mjs";
3
+ import { Encryption, createDefaultEncryption } from "./encryption.mjs";
4
+ import { EnokiKeypair, EnokiPublicKey } from "./EnokiKeypair.mjs";
5
+ import { SyncStore, createInMemoryStorage, createLocalStorage, createSessionStorage } from "./stores.mjs";
6
+ import { EnokiFlow, EnokiFlowConfig } from "./EnokiFlow.mjs";
7
+ import { RegisterEnokiWalletsOptions } from "./wallet/types.mjs";
8
+ import { EnokiWallet } from "./wallet/wallet.mjs";
9
+ import { registerEnokiWallets } from "./wallet/register.mjs";
10
+ import { enokiWalletsInitializer } from "./wallet/initializer.mjs";
11
+ import { getSession, getWalletMetadata, isEnokiWallet, isFacebookWallet, isGoogleWallet, isTwitchWallet } from "./wallet/utils.mjs";
12
+ import { isEnokiNetwork } from "./utils.mjs";
13
+ export { type AuthProvider, type Encryption, EnokiClient, type EnokiClientConfig, EnokiClientError, EnokiFlow, type EnokiFlowConfig, EnokiKeypair, type EnokiNetwork, EnokiPublicKey, type EnokiWallet, type RegisterEnokiWalletsOptions, type SyncStore, createDefaultEncryption, createInMemoryStorage, createLocalStorage, createSessionStorage, enokiWalletsInitializer, getSession, getWalletMetadata, isEnokiNetwork, isEnokiWallet, isFacebookWallet, isGoogleWallet, isTwitchWallet, registerEnokiWallets };
package/dist/index.mjs ADDED
@@ -0,0 +1,11 @@
1
+ import { EnokiClient, EnokiClientError } from "./EnokiClient/index.mjs";
2
+ import { createDefaultEncryption } from "./encryption.mjs";
3
+ import { EnokiKeypair, EnokiPublicKey } from "./EnokiKeypair.mjs";
4
+ import { createInMemoryStorage, createLocalStorage, createSessionStorage } from "./stores.mjs";
5
+ import { EnokiFlow } from "./EnokiFlow.mjs";
6
+ import { isEnokiNetwork } from "./utils.mjs";
7
+ import { registerEnokiWallets } from "./wallet/register.mjs";
8
+ import { enokiWalletsInitializer } from "./wallet/initializer.mjs";
9
+ import { getSession, getWalletMetadata, isEnokiWallet, isFacebookWallet, isGoogleWallet, isTwitchWallet } from "./wallet/utils.mjs";
10
+
11
+ export { EnokiClient, EnokiClientError, EnokiFlow, EnokiKeypair, EnokiPublicKey, createDefaultEncryption, createInMemoryStorage, createLocalStorage, createSessionStorage, enokiWalletsInitializer, getSession, getWalletMetadata, isEnokiNetwork, isEnokiWallet, isFacebookWallet, isGoogleWallet, isTwitchWallet, registerEnokiWallets };
@@ -0,0 +1,28 @@
1
+ import { EnokiFlow, EnokiFlowConfig, ZkLoginSession, ZkLoginState } from "./EnokiFlow.mjs";
2
+ import { ReactNode } from "react";
3
+ import * as react_jsx_runtime0 from "react/jsx-runtime";
4
+
5
+ //#region src/react.d.ts
6
+ /** @deprecated use `registerEnokiWallets` instead */
7
+ type EnokiFlowProviderProps = EnokiFlowConfig & {
8
+ children: ReactNode;
9
+ };
10
+ /** @deprecated use `registerEnokiWallets` instead */
11
+ declare function EnokiFlowProvider({
12
+ children,
13
+ ...config
14
+ }: EnokiFlowProviderProps): react_jsx_runtime0.JSX.Element;
15
+ /** @deprecated use `registerEnokiWallets` and dapp-kit wallet hooks instead */
16
+ declare function useEnokiFlow(): EnokiFlow;
17
+ /** @deprecated use `registerEnokiWallets` and dapp-kit wallet hooks instead */
18
+ declare function useZkLogin(): ZkLoginState;
19
+ /** @deprecated use `registerEnokiWallets` and dapp-kit wallet hooks instead */
20
+ declare function useZkLoginSession(): ZkLoginSession | null;
21
+ /** @deprecated use `registerEnokiWallets` and dapp-kit wallet hooks instead */
22
+ declare function useAuthCallback(): {
23
+ handled: boolean;
24
+ state: string | null;
25
+ };
26
+ //#endregion
27
+ export { EnokiFlowProvider, EnokiFlowProviderProps, useAuthCallback, useEnokiFlow, useZkLogin, useZkLoginSession };
28
+ //# sourceMappingURL=react.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"react.d.mts","names":[],"sources":["../src/react.tsx"],"sourcesContent":[],"mappings":";;;;;;KAaY,sBAAA,GAAyB;EAAzB,QAAA,EACD,SADC;AAKZ,CAAA;;AAA2D,iBAA3C,iBAAA,CAA2C;EAAA,QAAA;EAAA,GAAA;AAAA,CAAA,EAAA,sBAAA,CAAA,EAAsB,kBAAA,CAAA,GAAA,CAAA,OAAtB;;AAAsB,iBAMjE,YAAA,CAAA,CANiE,EAMrD,SANqD;AAMjF;AASgB,iBAAA,UAAA,CAAA,CAAU,EAAA,YAAA;AAM1B;AAMgB,iBANA,iBAAA,CAAA,CAMe,EANE,cAAA,GAMF,IAAA;;iBAAf,eAAA,CAAA"}
package/dist/react.mjs ADDED
@@ -0,0 +1,61 @@
1
+ import { EnokiFlow } from "./EnokiFlow.mjs";
2
+ import { useStore } from "@nanostores/react";
3
+ import { createContext, useContext, useEffect, useState } from "react";
4
+ import { jsx } from "react/jsx-runtime";
5
+
6
+ //#region src/react.tsx
7
+ const EnokiFlowContext = createContext(null);
8
+ /** @deprecated use `registerEnokiWallets` instead */
9
+ function EnokiFlowProvider({ children, ...config }) {
10
+ const [enokiFlow] = useState(() => new EnokiFlow(config));
11
+ return /* @__PURE__ */ jsx(EnokiFlowContext.Provider, {
12
+ value: enokiFlow,
13
+ children
14
+ });
15
+ }
16
+ /** @deprecated use `registerEnokiWallets` and dapp-kit wallet hooks instead */
17
+ function useEnokiFlow() {
18
+ const context = useContext(EnokiFlowContext);
19
+ if (!context) throw new Error("Missing `EnokiFlowContext` provider");
20
+ return context;
21
+ }
22
+ /** @deprecated use `registerEnokiWallets` and dapp-kit wallet hooks instead */
23
+ function useZkLogin() {
24
+ return useStore(useEnokiFlow().$zkLoginState);
25
+ }
26
+ /** @deprecated use `registerEnokiWallets` and dapp-kit wallet hooks instead */
27
+ function useZkLoginSession() {
28
+ return useStore(useEnokiFlow().$zkLoginSession).value;
29
+ }
30
+ /** @deprecated use `registerEnokiWallets` and dapp-kit wallet hooks instead */
31
+ function useAuthCallback() {
32
+ const flow = useEnokiFlow();
33
+ const [state, setState] = useState(null);
34
+ const [handled, setHandled] = useState(false);
35
+ const [hash, setHash] = useState(null);
36
+ useEffect(() => {
37
+ const listener = () => setHash(window.location.hash.slice(1).trim());
38
+ listener();
39
+ window.addEventListener("hashchange", listener);
40
+ return () => window.removeEventListener("hashchange", listener);
41
+ }, []);
42
+ useEffect(() => {
43
+ if (!hash) return;
44
+ (async () => {
45
+ try {
46
+ setState(await flow.handleAuthCallback(hash));
47
+ window.location.hash = "";
48
+ } finally {
49
+ setHandled(true);
50
+ }
51
+ })();
52
+ }, [hash, flow]);
53
+ return {
54
+ handled,
55
+ state
56
+ };
57
+ }
58
+
59
+ //#endregion
60
+ export { EnokiFlowProvider, useAuthCallback, useEnokiFlow, useZkLogin, useZkLoginSession };
61
+ //# sourceMappingURL=react.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"react.mjs","names":[],"sources":["../src/react.tsx"],"sourcesContent":["// Copyright (c) Mysten Labs, Inc.\n// SPDX-License-Identifier: Apache-2.0\n\nimport { useStore } from '@nanostores/react';\nimport type { ReactNode } from 'react';\nimport { createContext, useContext, useEffect, useState } from 'react';\n\nimport type { EnokiFlowConfig } from './EnokiFlow.js';\nimport { EnokiFlow } from './EnokiFlow.js';\n\nconst EnokiFlowContext = createContext<EnokiFlow | null>(null);\n\n/** @deprecated use `registerEnokiWallets` instead */\nexport type EnokiFlowProviderProps = EnokiFlowConfig & {\n\tchildren: ReactNode;\n};\n\n/** @deprecated use `registerEnokiWallets` instead */\nexport function EnokiFlowProvider({ children, ...config }: EnokiFlowProviderProps) {\n\tconst [enokiFlow] = useState(() => new EnokiFlow(config));\n\treturn <EnokiFlowContext.Provider value={enokiFlow}>{children}</EnokiFlowContext.Provider>;\n}\n\n/** @deprecated use `registerEnokiWallets` and dapp-kit wallet hooks instead */\nexport function useEnokiFlow() {\n\tconst context = useContext(EnokiFlowContext);\n\tif (!context) {\n\t\tthrow new Error('Missing `EnokiFlowContext` provider');\n\t}\n\treturn context;\n}\n\n/** @deprecated use `registerEnokiWallets` and dapp-kit wallet hooks instead */\nexport function useZkLogin() {\n\tconst flow = useEnokiFlow();\n\treturn useStore(flow.$zkLoginState);\n}\n\n/** @deprecated use `registerEnokiWallets` and dapp-kit wallet hooks instead */\nexport function useZkLoginSession() {\n\tconst flow = useEnokiFlow();\n\treturn useStore(flow.$zkLoginSession).value;\n}\n\n/** @deprecated use `registerEnokiWallets` and dapp-kit wallet hooks instead */\nexport function useAuthCallback() {\n\tconst flow = useEnokiFlow();\n\tconst [state, setState] = useState<string | null>(null);\n\tconst [handled, setHandled] = useState(false);\n\tconst [hash, setHash] = useState<string | null>(null);\n\n\tuseEffect(() => {\n\t\tconst listener = () => setHash(window.location.hash.slice(1).trim());\n\t\tlistener();\n\n\t\twindow.addEventListener('hashchange', listener);\n\t\treturn () => window.removeEventListener('hashchange', listener);\n\t}, []);\n\n\tuseEffect(() => {\n\t\tif (!hash) return;\n\n\t\t(async () => {\n\t\t\ttry {\n\t\t\t\tsetState(await flow.handleAuthCallback(hash));\n\n\t\t\t\twindow.location.hash = '';\n\t\t\t} finally {\n\t\t\t\tsetHandled(true);\n\t\t\t}\n\t\t})();\n\t}, [hash, flow]);\n\n\treturn { handled, state };\n}\n"],"mappings":";;;;;;AAUA,MAAM,mBAAmB,cAAgC,KAAK;;AAQ9D,SAAgB,kBAAkB,EAAE,UAAU,GAAG,UAAkC;CAClF,MAAM,CAAC,aAAa,eAAe,IAAI,UAAU,OAAO,CAAC;AACzD,QAAO,oBAAC,iBAAiB;EAAS,OAAO;EAAY;GAAqC;;;AAI3F,SAAgB,eAAe;CAC9B,MAAM,UAAU,WAAW,iBAAiB;AAC5C,KAAI,CAAC,QACJ,OAAM,IAAI,MAAM,sCAAsC;AAEvD,QAAO;;;AAIR,SAAgB,aAAa;AAE5B,QAAO,SADM,cAAc,CACN,cAAc;;;AAIpC,SAAgB,oBAAoB;AAEnC,QAAO,SADM,cAAc,CACN,gBAAgB,CAAC;;;AAIvC,SAAgB,kBAAkB;CACjC,MAAM,OAAO,cAAc;CAC3B,MAAM,CAAC,OAAO,YAAY,SAAwB,KAAK;CACvD,MAAM,CAAC,SAAS,cAAc,SAAS,MAAM;CAC7C,MAAM,CAAC,MAAM,WAAW,SAAwB,KAAK;AAErD,iBAAgB;EACf,MAAM,iBAAiB,QAAQ,OAAO,SAAS,KAAK,MAAM,EAAE,CAAC,MAAM,CAAC;AACpE,YAAU;AAEV,SAAO,iBAAiB,cAAc,SAAS;AAC/C,eAAa,OAAO,oBAAoB,cAAc,SAAS;IAC7D,EAAE,CAAC;AAEN,iBAAgB;AACf,MAAI,CAAC,KAAM;AAEX,GAAC,YAAY;AACZ,OAAI;AACH,aAAS,MAAM,KAAK,mBAAmB,KAAK,CAAC;AAE7C,WAAO,SAAS,OAAO;aACd;AACT,eAAW,KAAK;;MAEd;IACF,CAAC,MAAM,KAAK,CAAC;AAEhB,QAAO;EAAE;EAAS;EAAO"}
@@ -0,0 +1,25 @@
1
+ //#region src/stores.d.ts
2
+ /**
3
+ * An sync key-value store.
4
+ */
5
+ interface SyncStore {
6
+ get(key: string): string | null;
7
+ set(key: string, value: string): void;
8
+ delete(key: string): void;
9
+ }
10
+ /**
11
+ * Create a storage interface backed by memory.
12
+ * This is generally useful for server-side rendering, and test environments.
13
+ */
14
+ declare function createInMemoryStorage(): SyncStore;
15
+ /**
16
+ * Create a store backed by `localStorage`.
17
+ */
18
+ declare function createLocalStorage(): SyncStore;
19
+ /**
20
+ * Create a store backed by `sessionStorage`.
21
+ */
22
+ declare function createSessionStorage(): SyncStore;
23
+ //#endregion
24
+ export { SyncStore, createInMemoryStorage, createLocalStorage, createSessionStorage };
25
+ //# sourceMappingURL=stores.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"stores.d.mts","names":[],"sources":["../src/stores.ts"],"sourcesContent":[],"mappings":";;AAMA;AAwBA;AAkBgB,UA1CC,SAAA,CA0CiB;EAYlB,GAAA,CAAA,GAAA,EAAA,MAAA,CAAA,EAAA,MAAoB,GAAA,IAAA;;;;;;;;iBA9BpB,qBAAA,CAAA,GAAyB;;;;iBAkBzB,kBAAA,CAAA,GAAsB;;;;iBAYtB,oBAAA,CAAA,GAAwB"}
@@ -0,0 +1,56 @@
1
+ //#region src/stores.ts
2
+ function createWebStorage(storage) {
3
+ return {
4
+ get(key) {
5
+ return storage.getItem(key);
6
+ },
7
+ set(key, value) {
8
+ storage.setItem(key, value);
9
+ },
10
+ delete(key) {
11
+ storage.removeItem(key);
12
+ }
13
+ };
14
+ }
15
+ /**
16
+ * Create a storage interface backed by memory.
17
+ * This is generally useful for server-side rendering, and test environments.
18
+ */
19
+ function createInMemoryStorage() {
20
+ const store = /* @__PURE__ */ new Map();
21
+ return {
22
+ get(key) {
23
+ return store.get(key) ?? null;
24
+ },
25
+ set(key, value) {
26
+ store.set(key, value);
27
+ },
28
+ delete(key) {
29
+ store.delete(key);
30
+ }
31
+ };
32
+ }
33
+ /**
34
+ * Create a store backed by `localStorage`.
35
+ */
36
+ function createLocalStorage() {
37
+ if (typeof window === "undefined") {
38
+ console.warn("`window.localStorage` is not available, falling back to in-memory storage");
39
+ return createInMemoryStorage();
40
+ }
41
+ return createWebStorage(window.localStorage);
42
+ }
43
+ /**
44
+ * Create a store backed by `sessionStorage`.
45
+ */
46
+ function createSessionStorage() {
47
+ if (typeof window === "undefined") {
48
+ console.warn("`window.sessionStorage` is not available, falling back to in-memory storage");
49
+ return createInMemoryStorage();
50
+ }
51
+ return createWebStorage(window.sessionStorage);
52
+ }
53
+
54
+ //#endregion
55
+ export { createInMemoryStorage, createLocalStorage, createSessionStorage };
56
+ //# sourceMappingURL=stores.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"stores.mjs","names":[],"sources":["../src/stores.ts"],"sourcesContent":["// Copyright (c) Mysten Labs, Inc.\n// SPDX-License-Identifier: Apache-2.0\n\n/**\n * An sync key-value store.\n */\nexport interface SyncStore {\n\tget(key: string): string | null;\n\tset(key: string, value: string): void;\n\tdelete(key: string): void;\n}\n\nfunction createWebStorage(storage: Storage): SyncStore {\n\treturn {\n\t\tget(key: string) {\n\t\t\treturn storage.getItem(key);\n\t\t},\n\t\tset(key: string, value: string) {\n\t\t\tstorage.setItem(key, value);\n\t\t},\n\t\tdelete(key: string) {\n\t\t\tstorage.removeItem(key);\n\t\t},\n\t};\n}\n\n/**\n * Create a storage interface backed by memory.\n * This is generally useful for server-side rendering, and test environments.\n */\nexport function createInMemoryStorage(): SyncStore {\n\tconst store = new Map<string, string>();\n\treturn {\n\t\tget(key) {\n\t\t\treturn store.get(key) ?? null;\n\t\t},\n\t\tset(key, value) {\n\t\t\tstore.set(key, value);\n\t\t},\n\t\tdelete(key) {\n\t\t\tstore.delete(key);\n\t\t},\n\t};\n}\n\n/**\n * Create a store backed by `localStorage`.\n */\nexport function createLocalStorage(): SyncStore {\n\tif (typeof window === 'undefined') {\n\t\tconsole.warn('`window.localStorage` is not available, falling back to in-memory storage');\n\t\treturn createInMemoryStorage();\n\t}\n\n\treturn createWebStorage(window.localStorage);\n}\n\n/**\n * Create a store backed by `sessionStorage`.\n */\nexport function createSessionStorage(): SyncStore {\n\tif (typeof window === 'undefined') {\n\t\tconsole.warn('`window.sessionStorage` is not available, falling back to in-memory storage');\n\t\treturn createInMemoryStorage();\n\t}\n\n\treturn createWebStorage(window.sessionStorage);\n}\n"],"mappings":";AAYA,SAAS,iBAAiB,SAA6B;AACtD,QAAO;EACN,IAAI,KAAa;AAChB,UAAO,QAAQ,QAAQ,IAAI;;EAE5B,IAAI,KAAa,OAAe;AAC/B,WAAQ,QAAQ,KAAK,MAAM;;EAE5B,OAAO,KAAa;AACnB,WAAQ,WAAW,IAAI;;EAExB;;;;;;AAOF,SAAgB,wBAAmC;CAClD,MAAM,wBAAQ,IAAI,KAAqB;AACvC,QAAO;EACN,IAAI,KAAK;AACR,UAAO,MAAM,IAAI,IAAI,IAAI;;EAE1B,IAAI,KAAK,OAAO;AACf,SAAM,IAAI,KAAK,MAAM;;EAEtB,OAAO,KAAK;AACX,SAAM,OAAO,IAAI;;EAElB;;;;;AAMF,SAAgB,qBAAgC;AAC/C,KAAI,OAAO,WAAW,aAAa;AAClC,UAAQ,KAAK,4EAA4E;AACzF,SAAO,uBAAuB;;AAG/B,QAAO,iBAAiB,OAAO,aAAa;;;;;AAM7C,SAAgB,uBAAkC;AACjD,KAAI,OAAO,WAAW,aAAa;AAClC,UAAQ,KAAK,8EAA8E;AAC3F,SAAO,uBAAuB;;AAG/B,QAAO,iBAAiB,OAAO,eAAe"}
@@ -0,0 +1,7 @@
1
+ import { EnokiNetwork } from "./EnokiClient/type.mjs";
2
+
3
+ //#region src/utils.d.ts
4
+ declare function isEnokiNetwork(network: string): network is EnokiNetwork;
5
+ //#endregion
6
+ export { isEnokiNetwork };
7
+ //# sourceMappingURL=utils.d.mts.map