@mysten/enoki 1.3.3 → 1.4.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.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,23 @@
1
1
  # @mysten/enoki
2
2
 
3
+ ## 1.4.0
4
+
5
+ ### Minor Changes
6
+
7
+ - 83ab0c5: Add Enoki sponsorship in one request:
8
+
9
+ - `enoki()` client extension: `client.enoki.sponsorAndExecuteTransaction({ transaction, signer })`
10
+ builds the transaction with Enoki as gas owner, signs it, and has Enoki sponsor and execute it.
11
+ It also accepts already-built bytes with a `signature`.
12
+ `client.enoki.prepareSponsoredTransaction({ transaction })` sets Enoki as gas owner without
13
+ building, for signing with a wallet or running your own checks first, and
14
+ `client.enoki.getSponsorAddress()` returns the sponsor address.
15
+ - `EnokiClient.sponsorAndExecuteTransaction`, and `sponsorAddresses` on `getApp`'s response.
16
+ - `EnokiClientError#requiresRebuild` and `isStaleTransactionError`, for errors where the
17
+ transaction must be built and signed again before retrying.
18
+
19
+ ## 1.3.4
20
+
3
21
  ## 1.3.3
4
22
 
5
23
  ## 1.3.2
@@ -1,4 +1,4 @@
1
- import { CreateSponsoredTransactionApiInput, CreateSponsoredTransactionApiResponse, CreateSubnameApiInput, CreateSubnameApiResponse, CreateZkLoginNonceApiInput, CreateZkLoginNonceApiResponse, CreateZkLoginZkpApiInput, CreateZkLoginZkpApiResponse, DeleteSubnameApiInput, ExecuteSponsoredTransactionApiInput, ExecuteSponsoredTransactionApiResponse, GetAppApiInput, GetAppApiResponse, GetSubnamesApiInput, GetSubnamesApiResponse, GetZkLoginAddressesApiInput, GetZkLoginAddressesApiResponse, GetZkLoginApiInput, GetZkLoginApiResponse } from "./type.mjs";
1
+ import { CreateSponsoredTransactionApiInput, CreateSponsoredTransactionApiResponse, CreateSubnameApiInput, CreateSubnameApiResponse, CreateZkLoginNonceApiInput, CreateZkLoginNonceApiResponse, CreateZkLoginZkpApiInput, CreateZkLoginZkpApiResponse, DeleteSubnameApiInput, ExecuteSponsoredTransactionApiInput, ExecuteSponsoredTransactionApiResponse, GetAppApiInput, GetAppApiResponse, GetSubnamesApiInput, GetSubnamesApiResponse, GetZkLoginAddressesApiInput, GetZkLoginAddressesApiResponse, GetZkLoginApiInput, GetZkLoginApiResponse, SponsorAndExecuteTransactionApiInput, SponsorAndExecuteTransactionApiResponse } from "./type.mjs";
2
2
 
3
3
  //#region src/EnokiClient/index.d.ts
4
4
  interface EnokiClientConfig {
@@ -18,7 +18,17 @@ declare class EnokiClientError extends Error {
18
18
  status: number;
19
19
  code: string;
20
20
  constructor(status: number, response: string);
21
+ /**
22
+ * True when the transaction must be built and signed again before retrying, because Enoki's
23
+ * sponsor address or the reference gas price changed since it was built.
24
+ */
25
+ get requiresRebuild(): boolean;
21
26
  }
27
+ /**
28
+ * Whether a sponsorship failed because the transaction was built with a sponsor address or
29
+ * reference gas price that's no longer current. Build it again, have the sender sign it, and retry.
30
+ */
31
+ declare function isStaleTransactionError(error: unknown): error is EnokiClientError;
22
32
  /**
23
33
  * A low-level client for interacting with the Enoki API.
24
34
  */
@@ -32,10 +42,19 @@ declare class EnokiClient {
32
42
  createZkLoginZkp(input: CreateZkLoginZkpApiInput): Promise<CreateZkLoginZkpApiResponse>;
33
43
  createSponsoredTransaction(input: CreateSponsoredTransactionApiInput): Promise<CreateSponsoredTransactionApiResponse>;
34
44
  executeSponsoredTransaction(input: ExecuteSponsoredTransactionApiInput): Promise<ExecuteSponsoredTransactionApiResponse>;
45
+ /**
46
+ * Sponsors and executes a transaction in one request. Build it with the sponsor address from
47
+ * `getApp` as gas owner and an empty gas payment, and have the sender sign it. Requires a private
48
+ * API key.
49
+ *
50
+ * On `invalid_gas_owner` or `invalid_gas_price`, rebuild with the value in the error's `data`,
51
+ * sign again and retry. `already_sponsored` means Enoki has already sponsored this transaction.
52
+ */
53
+ sponsorAndExecuteTransaction(input: SponsorAndExecuteTransactionApiInput): Promise<SponsorAndExecuteTransactionApiResponse>;
35
54
  getSubnames(input: GetSubnamesApiInput): Promise<GetSubnamesApiResponse>;
36
55
  createSubname(input: CreateSubnameApiInput): Promise<CreateSubnameApiResponse>;
37
56
  deleteSubname(input: DeleteSubnameApiInput): void;
38
57
  }
39
58
  //#endregion
40
- export { EnokiClient, EnokiClientConfig, EnokiClientError };
59
+ export { EnokiClient, EnokiClientConfig, EnokiClientError, isStaleTransactionError };
41
60
  //# sourceMappingURL=index.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.mts","names":[],"sources":["../../src/EnokiClient/index.ts"],"mappings":";;;UA6BiB,iBAAA;;EAEhB,MAAA;EAFiC;EAKjC,MAAA;EALiC;EAQjC,gBAAA;AAAA;AAAA,cAGY,gBAAA,SAAyB,KAAA;EACrC,MAAA;IAAU,IAAA;IAAc,OAAA;IAAiB,IAAA;EAAA;EACzC,MAAA;EACA,IAAA;cAEY,MAAA,UAAgB,QAAA;AAAA;;;;cAwBhB,WAAA;EAAA;cAMA,MAAA,EAAQ,iBAAA;EAOpB,MAAA,CAAO,MAAA,GAAS,cAAA,GAAc,OAAA,CAAA,iBAAA;EAM9B,UAAA,CAAW,KAAA,EAAO,kBAAA,GAAkB,OAAA,CAAA,qBAAA;EASpC,mBAAA,CAAoB,KAAA,EAAO,2BAAA,GAA2B,OAAA,CAAA,8BAAA;EAStD,kBAAA,CAAmB,KAAA,EAAO,0BAAA,GAA0B,OAAA,CAAA,6BAAA;EAWpD,gBAAA,CAAiB,KAAA,EAAO,wBAAA,GAAwB,OAAA,CAAA,2BAAA;EAehD,0BAAA,CAA2B,KAAA,EAAO,kCAAA,GAAkC,OAAA,CAAA,qCAAA;EAkBpE,2BAAA,CAA4B,KAAA,EAAO,mCAAA,GAAmC,OAAA,CAAA,sCAAA;EAYtE,WAAA,CAAY,KAAA,EAAO,mBAAA,GAAmB,OAAA,CAAA,sBAAA;EAmBtC,aAAA,CAAc,KAAA,EAAO,qBAAA,GAAqB,OAAA,CAAA,wBAAA;EA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EnokiClientError = class extends Error {
15
15
  this.status = status;
16
16
  this.code = errors?.[0]?.code ?? "unknown_error";
17
17
  }
18
+ /**
19
+ * True when the transaction must be built and signed again before retrying, because Enoki's
20
+ * sponsor address or the reference gas price changed since it was built.
21
+ */
22
+ get requiresRebuild() {
23
+ return this.code === "invalid_gas_owner" || this.code === "invalid_gas_price";
24
+ }
18
25
  };
19
26
  /**
27
+ * Whether a sponsorship failed because the transaction was built with a sponsor address or
28
+ * reference gas price that's no longer current. Build it again, have the sender sign it, and retry.
29
+ */
30
+ function isStaleTransactionError(error) {
31
+ return error instanceof EnokiClientError && error.requiresRebuild;
32
+ }
33
+ /**
20
34
  * A low-level client for interacting with the Enoki API.
21
35
  */
22
36
  var EnokiClient = class {
@@ -86,6 +100,26 @@ var EnokiClient = class {
86
100
  body: JSON.stringify({ signature: input.signature })
87
101
  });
88
102
  }
103
+ /**
104
+ * Sponsors and executes a transaction in one request. Build it with the sponsor address from
105
+ * `getApp` as gas owner and an empty gas payment, and have the sender sign it. Requires a private
106
+ * API key.
107
+ *
108
+ * On `invalid_gas_owner` or `invalid_gas_price`, rebuild with the value in the error's `data`,
109
+ * sign again and retry. `already_sponsored` means Enoki has already sponsored this transaction.
110
+ */
111
+ sponsorAndExecuteTransaction(input) {
112
+ return this.#fetch("transaction-blocks/sponsor/execute", {
113
+ method: "POST",
114
+ body: JSON.stringify({
115
+ network: input.network,
116
+ transactionBytes: input.transactionBytes,
117
+ signature: input.signature,
118
+ allowedAddresses: input.allowedAddresses,
119
+ allowedMoveCallTargets: input.allowedMoveCallTargets
120
+ })
121
+ });
122
+ }
89
123
  getSubnames(input) {
90
124
  const query = new URLSearchParams();
91
125
  if (input.address) query.set("address", input.address);
@@ -132,5 +166,5 @@ var EnokiClient = class {
132
166
  };
133
167
 
134
168
  //#endregion
135
- export { EnokiClient, EnokiClientError };
169
+ export { EnokiClient, EnokiClientError, isStaleTransactionError };
136
170
  //# sourceMappingURL=index.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":["#version","#apiUrl","#apiKey","#additionalEpochs","#fetch"],"sources":["../../src/EnokiClient/index.ts"],"sourcesContent":["// Copyright (c) Mysten Labs, Inc.\n// SPDX-License-Identifier: Apache-2.0\n\nimport type {\n\tCreateSponsoredTransactionApiInput,\n\tCreateSponsoredTransactionApiResponse,\n\tCreateSubnameApiInput,\n\tCreateSubnameApiResponse,\n\tCreateZkLoginNonceApiInput,\n\tCreateZkLoginNonceApiResponse,\n\tCreateZkLoginZkpApiInput,\n\tCreateZkLoginZkpApiResponse,\n\tDeleteSubnameApiInput,\n\tDeleteSubnameApiResponse,\n\tExecuteSponsoredTransactionApiInput,\n\tExecuteSponsoredTransactionApiResponse,\n\tGetAppApiInput,\n\tGetAppApiResponse,\n\tGetSubnamesApiInput,\n\tGetSubnamesApiResponse,\n\tGetZkLoginAddressesApiInput,\n\tGetZkLoginAddressesApiResponse,\n\tGetZkLoginApiInput,\n\tGetZkLoginApiResponse,\n} from './type.js';\n\nconst DEFAULT_API_URL = 'https://api.enoki.mystenlabs.com';\nconst ZKLOGIN_HEADER = 'zklogin-jwt';\n\nexport interface EnokiClientConfig {\n\t/** The API key for the Enoki app, available in the Enoki Portal. */\n\tapiKey: string;\n\n\t/** The API URL for Enoki. In most cases, this should not be set. */\n\tapiUrl?: string;\n\n\t/** The amount of epochs that you would like to have the nonce be valid for. Range: `0 <= value <= 30` */\n\tadditionalEpochs?: number;\n}\n\nexport class EnokiClientError extends Error {\n\terrors: { code: string; message: string; data: unknown }[] = [];\n\tstatus: number;\n\tcode: string;\n\n\tconstructor(status: number, response: string) {\n\t\tlet errors;\n\t\ttry {\n\t\t\tconst parsedResponse = JSON.parse(response) as {\n\t\t\t\terrors: { code: string; message: string; data: unknown }[];\n\t\t\t};\n\t\t\terrors = parsedResponse.errors;\n\t\t} catch {\n\t\t\t// Ignore\n\t\t}\n\t\tconst cause = errors?.[0] ? new Error(errors[0].message) : undefined;\n\t\tsuper(`Request to Enoki API failed (status: ${status})`, {\n\t\t\tcause,\n\t\t});\n\t\tthis.errors = errors ?? [];\n\t\tthis.name = 'EnokiClientError';\n\t\tthis.status = status;\n\t\tthis.code = errors?.[0]?.code ?? 'unknown_error';\n\t}\n}\n\n/**\n * A low-level client for interacting with the Enoki API.\n */\nexport class EnokiClient {\n\t#version: string;\n\t#apiUrl: string;\n\t#apiKey: string;\n\t#additionalEpochs: number | undefined;\n\n\tconstructor(config: EnokiClientConfig) {\n\t\tthis.#version = 'v1';\n\t\tthis.#apiUrl = config.apiUrl ?? DEFAULT_API_URL;\n\t\tthis.#apiKey = config.apiKey;\n\t\tthis.#additionalEpochs = config.additionalEpochs;\n\t}\n\n\tgetApp(_input?: GetAppApiInput) {\n\t\treturn this.#fetch<GetAppApiResponse>('app', {\n\t\t\tmethod: 'GET',\n\t\t});\n\t}\n\n\tgetZkLogin(input: GetZkLoginApiInput) {\n\t\treturn this.#fetch<GetZkLoginApiResponse>('zklogin', {\n\t\t\tmethod: 'GET',\n\t\t\theaders: {\n\t\t\t\t[ZKLOGIN_HEADER]: input.jwt,\n\t\t\t},\n\t\t});\n\t}\n\n\tgetZkLoginAddresses(input: GetZkLoginAddressesApiInput) {\n\t\treturn this.#fetch<GetZkLoginAddressesApiResponse>('zklogin/addresses', {\n\t\t\tmethod: 'GET',\n\t\t\theaders: {\n\t\t\t\t[ZKLOGIN_HEADER]: input.jwt,\n\t\t\t},\n\t\t});\n\t}\n\n\tcreateZkLoginNonce(input: CreateZkLoginNonceApiInput) {\n\t\treturn this.#fetch<CreateZkLoginNonceApiResponse>('zklogin/nonce', {\n\t\t\tmethod: 'POST',\n\t\t\tbody: JSON.stringify({\n\t\t\t\tnetwork: input.network,\n\t\t\t\tephemeralPublicKey: input.ephemeralPublicKey.toSuiPublicKey(),\n\t\t\t\tadditionalEpochs: input.additionalEpochs ?? this.#additionalEpochs,\n\t\t\t}),\n\t\t});\n\t}\n\n\tcreateZkLoginZkp(input: CreateZkLoginZkpApiInput) {\n\t\treturn this.#fetch<CreateZkLoginZkpApiResponse>('zklogin/zkp', {\n\t\t\tmethod: 'POST',\n\t\t\theaders: {\n\t\t\t\t[ZKLOGIN_HEADER]: input.jwt,\n\t\t\t},\n\t\t\tbody: JSON.stringify({\n\t\t\t\tnetwork: input.network,\n\t\t\t\tephemeralPublicKey: input.ephemeralPublicKey.toSuiPublicKey(),\n\t\t\t\tmaxEpoch: input.maxEpoch,\n\t\t\t\trandomness: input.randomness,\n\t\t\t}),\n\t\t});\n\t}\n\n\tcreateSponsoredTransaction(input: CreateSponsoredTransactionApiInput) {\n\t\treturn this.#fetch<CreateSponsoredTransactionApiResponse>('transaction-blocks/sponsor', {\n\t\t\tmethod: 'POST',\n\t\t\theaders: input.jwt\n\t\t\t\t? {\n\t\t\t\t\t\t[ZKLOGIN_HEADER]: input.jwt,\n\t\t\t\t\t}\n\t\t\t\t: {},\n\t\t\tbody: JSON.stringify({\n\t\t\t\tsender: input.sender,\n\t\t\t\tnetwork: input.network,\n\t\t\t\ttransactionBlockKindBytes: input.transactionKindBytes,\n\t\t\t\tallowedAddresses: input.allowedAddresses,\n\t\t\t\tallowedMoveCallTargets: input.allowedMoveCallTargets,\n\t\t\t}),\n\t\t});\n\t}\n\n\texecuteSponsoredTransaction(input: ExecuteSponsoredTransactionApiInput) {\n\t\treturn this.#fetch<ExecuteSponsoredTransactionApiResponse>(\n\t\t\t`transaction-blocks/sponsor/${input.digest}`,\n\t\t\t{\n\t\t\t\tmethod: 'POST',\n\t\t\t\tbody: JSON.stringify({\n\t\t\t\t\tsignature: input.signature,\n\t\t\t\t}),\n\t\t\t},\n\t\t);\n\t}\n\n\tgetSubnames(input: GetSubnamesApiInput) {\n\t\tconst query = new URLSearchParams();\n\t\tif (input.address) {\n\t\t\tquery.set('address', input.address);\n\t\t}\n\t\tif (input.network) {\n\t\t\tquery.set('network', input.network);\n\t\t}\n\t\tif (input.domain) {\n\t\t\tquery.set('domain', input.domain);\n\t\t}\n\t\treturn this.#fetch<GetSubnamesApiResponse>(\n\t\t\t'subnames' + (query.size > 0 ? `?${query.toString()}` : ''),\n\t\t\t{\n\t\t\t\tmethod: 'GET',\n\t\t\t},\n\t\t);\n\t}\n\n\tcreateSubname(input: CreateSubnameApiInput) {\n\t\treturn this.#fetch<CreateSubnameApiResponse>('subnames', {\n\t\t\tmethod: 'POST',\n\t\t\theaders: input.jwt\n\t\t\t\t? {\n\t\t\t\t\t\t[ZKLOGIN_HEADER]: input.jwt,\n\t\t\t\t\t}\n\t\t\t\t: {},\n\t\t\tbody: JSON.stringify({\n\t\t\t\tnetwork: input.network,\n\t\t\t\tdomain: input.domain,\n\t\t\t\tsubname: input.subname,\n\t\t\t\ttargetAddress: input.targetAddress,\n\t\t\t}),\n\t\t});\n\t}\n\n\tdeleteSubname(input: DeleteSubnameApiInput) {\n\t\tthis.#fetch<DeleteSubnameApiResponse>('subnames', {\n\t\t\tmethod: 'DELETE',\n\t\t\tbody: JSON.stringify({\n\t\t\t\tnetwork: input.network,\n\t\t\t\tdomain: input.domain,\n\t\t\t\tsubname: input.subname,\n\t\t\t}),\n\t\t});\n\t}\n\n\tasync #fetch<T = unknown>(path: string, init: RequestInit): Promise<T> {\n\t\tconst res = await fetch(`${this.#apiUrl}/${this.#version}/${path}`, {\n\t\t\t...init,\n\t\t\theaders: {\n\t\t\t\t...init.headers,\n\t\t\t\tAuthorization: `Bearer ${this.#apiKey}`,\n\t\t\t\t'Content-Type': 'application/json',\n\t\t\t\t'Request-Id': crypto.randomUUID(),\n\t\t\t},\n\t\t});\n\n\t\tif (!res.ok) {\n\t\t\tthrow new EnokiClientError(res.status, await res.text());\n\t\t}\n\n\t\tconst { data } = await res.json();\n\n\t\treturn data as T;\n\t}\n}\n"],"mappings":";AA0BA,MAAM,kBAAkB;AACxB,MAAM,iBAAiB;AAavB,IAAa,mBAAb,cAAsC,MAAM;CAK3C,YAAY,QAAgB,UAAkB;EAC7C,IAAI;AACJ,MAAI;AAIH,YAHuB,KAAK,MAAM,SA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SAAS;IACR,GAAG,KAAK;IACR,eAAe,UAAU,MAAKE;IAC9B,gBAAgB;IAChB,cAAc,OAAO,YAAY;IACjC;GACD,CAAC;AAEF,MAAI,CAAC,IAAI,GACR,OAAM,IAAI,iBAAiB,IAAI,QAAQ,MAAM,IAAI,MAAM,CAAC;EAGzD,MAAM,EAAE,SAAS,MAAM,IAAI,MAAM;AAEjC,SAAO"}
1
+ {"version":3,"file":"index.mjs","names":["#version","#apiUrl","#apiKey","#additionalEpochs","#fetch"],"sources":["../../src/EnokiClient/index.ts"],"sourcesContent":["// Copyright (c) Mysten Labs, Inc.\n// SPDX-License-Identifier: Apache-2.0\n\nimport type {\n\tCreateSponsoredTransactionApiInput,\n\tCreateSponsoredTransactionApiResponse,\n\tCreateSubnameApiInput,\n\tCreateSubnameApiResponse,\n\tCreateZkLoginNonceApiInput,\n\tCreateZkLoginNonceApiResponse,\n\tCreateZkLoginZkpApiInput,\n\tCreateZkLoginZkpApiResponse,\n\tDeleteSubnameApiInput,\n\tDeleteSubnameApiResponse,\n\tExecuteSponsoredTransactionApiInput,\n\tExecuteSponsoredTransactionApiResponse,\n\tGetAppApiInput,\n\tGetAppApiResponse,\n\tGetSubnamesApiInput,\n\tGetSubnamesApiResponse,\n\tGetZkLoginAddressesApiInput,\n\tGetZkLoginAddressesApiResponse,\n\tGetZkLoginApiInput,\n\tGetZkLoginApiResponse,\n\tSponsorAndExecuteTransactionApiInput,\n\tSponsorAndExecuteTransactionApiResponse,\n} from './type.js';\n\nconst DEFAULT_API_URL = 'https://api.enoki.mystenlabs.com';\nconst ZKLOGIN_HEADER = 'zklogin-jwt';\n\nexport interface EnokiClientConfig {\n\t/** The API key for the Enoki app, available in the Enoki Portal. */\n\tapiKey: string;\n\n\t/** The API URL for Enoki. In most cases, this should not be set. */\n\tapiUrl?: string;\n\n\t/** The amount of epochs that you would like to have the nonce be valid for. Range: `0 <= value <= 30` */\n\tadditionalEpochs?: number;\n}\n\nexport class EnokiClientError extends Error {\n\terrors: { code: string; message: string; data: unknown }[] = [];\n\tstatus: number;\n\tcode: string;\n\n\tconstructor(status: number, response: string) {\n\t\tlet errors;\n\t\ttry {\n\t\t\tconst parsedResponse = JSON.parse(response) as {\n\t\t\t\terrors: { code: string; message: string; data: unknown }[];\n\t\t\t};\n\t\t\terrors = parsedResponse.errors;\n\t\t} catch {\n\t\t\t// Ignore\n\t\t}\n\t\tconst cause = errors?.[0] ? new Error(errors[0].message) : undefined;\n\t\tsuper(`Request to Enoki API failed (status: ${status})`, {\n\t\t\tcause,\n\t\t});\n\t\tthis.errors = errors ?? [];\n\t\tthis.name = 'EnokiClientError';\n\t\tthis.status = status;\n\t\tthis.code = errors?.[0]?.code ?? 'unknown_error';\n\t}\n\n\t/**\n\t * True when the transaction must be built and signed again before retrying, because Enoki's\n\t * sponsor address or the reference gas price changed since it was built.\n\t */\n\tget requiresRebuild(): boolean {\n\t\treturn this.code === 'invalid_gas_owner' || this.code === 'invalid_gas_price';\n\t}\n}\n\n/**\n * Whether a sponsorship failed because the transaction was built with a sponsor address or\n * reference gas price that's no longer current. Build it again, have the sender sign it, and retry.\n */\nexport function isStaleTransactionError(error: unknown): error is EnokiClientError {\n\treturn error instanceof EnokiClientError && error.requiresRebuild;\n}\n\n/**\n * A low-level client for interacting with the Enoki API.\n */\nexport class EnokiClient {\n\t#version: string;\n\t#apiUrl: string;\n\t#apiKey: string;\n\t#additionalEpochs: number | undefined;\n\n\tconstructor(config: EnokiClientConfig) {\n\t\tthis.#version = 'v1';\n\t\tthis.#apiUrl = config.apiUrl ?? DEFAULT_API_URL;\n\t\tthis.#apiKey = config.apiKey;\n\t\tthis.#additionalEpochs = config.additionalEpochs;\n\t}\n\n\tgetApp(_input?: GetAppApiInput) {\n\t\treturn this.#fetch<GetAppApiResponse>('app', {\n\t\t\tmethod: 'GET',\n\t\t});\n\t}\n\n\tgetZkLogin(input: GetZkLoginApiInput) {\n\t\treturn this.#fetch<GetZkLoginApiResponse>('zklogin', {\n\t\t\tmethod: 'GET',\n\t\t\theaders: {\n\t\t\t\t[ZKLOGIN_HEADER]: input.jwt,\n\t\t\t},\n\t\t});\n\t}\n\n\tgetZkLoginAddresses(input: GetZkLoginAddressesApiInput) {\n\t\treturn this.#fetch<GetZkLoginAddressesApiResponse>('zklogin/addresses', {\n\t\t\tmethod: 'GET',\n\t\t\theaders: {\n\t\t\t\t[ZKLOGIN_HEADER]: input.jwt,\n\t\t\t},\n\t\t});\n\t}\n\n\tcreateZkLoginNonce(input: CreateZkLoginNonceApiInput) {\n\t\treturn this.#fetch<CreateZkLoginNonceApiResponse>('zklogin/nonce', {\n\t\t\tmethod: 'POST',\n\t\t\tbody: JSON.stringify({\n\t\t\t\tnetwork: input.network,\n\t\t\t\tephemeralPublicKey: input.ephemeralPublicKey.toSuiPublicKey(),\n\t\t\t\tadditionalEpochs: input.additionalEpochs ?? this.#additionalEpochs,\n\t\t\t}),\n\t\t});\n\t}\n\n\tcreateZkLoginZkp(input: CreateZkLoginZkpApiInput) {\n\t\treturn this.#fetch<CreateZkLoginZkpApiResponse>('zklogin/zkp', {\n\t\t\tmethod: 'POST',\n\t\t\theaders: {\n\t\t\t\t[ZKLOGIN_HEADER]: input.jwt,\n\t\t\t},\n\t\t\tbody: JSON.stringify({\n\t\t\t\tnetwork: input.network,\n\t\t\t\tephemeralPublicKey: input.ephemeralPublicKey.toSuiPublicKey(),\n\t\t\t\tmaxEpoch: input.maxEpoch,\n\t\t\t\trandomness: input.randomness,\n\t\t\t}),\n\t\t});\n\t}\n\n\tcreateSponsoredTransaction(input: CreateSponsoredTransactionApiInput) {\n\t\treturn this.#fetch<CreateSponsoredTransactionApiResponse>('transaction-blocks/sponsor', {\n\t\t\tmethod: 'POST',\n\t\t\theaders: input.jwt\n\t\t\t\t? {\n\t\t\t\t\t\t[ZKLOGIN_HEADER]: input.jwt,\n\t\t\t\t\t}\n\t\t\t\t: {},\n\t\t\tbody: JSON.stringify({\n\t\t\t\tsender: input.sender,\n\t\t\t\tnetwork: input.network,\n\t\t\t\ttransactionBlockKindBytes: input.transactionKindBytes,\n\t\t\t\tallowedAddresses: input.allowedAddresses,\n\t\t\t\tallowedMoveCallTargets: input.allowedMoveCallTargets,\n\t\t\t}),\n\t\t});\n\t}\n\n\texecuteSponsoredTransaction(input: ExecuteSponsoredTransactionApiInput) {\n\t\treturn this.#fetch<ExecuteSponsoredTransactionApiResponse>(\n\t\t\t`transaction-blocks/sponsor/${input.digest}`,\n\t\t\t{\n\t\t\t\tmethod: 'POST',\n\t\t\t\tbody: JSON.stringify({\n\t\t\t\t\tsignature: input.signature,\n\t\t\t\t}),\n\t\t\t},\n\t\t);\n\t}\n\n\t/**\n\t * Sponsors and executes a transaction in one request. Build it with the sponsor address from\n\t * `getApp` as gas owner and an empty gas payment, and have the sender sign it. Requires a private\n\t * API key.\n\t *\n\t * On `invalid_gas_owner` or `invalid_gas_price`, rebuild with the value in the error's `data`,\n\t * sign again and retry. `already_sponsored` means Enoki has already sponsored this transaction.\n\t */\n\tsponsorAndExecuteTransaction(input: SponsorAndExecuteTransactionApiInput) {\n\t\treturn this.#fetch<SponsorAndExecuteTransactionApiResponse>(\n\t\t\t'transaction-blocks/sponsor/execute',\n\t\t\t{\n\t\t\t\tmethod: 'POST',\n\t\t\t\tbody: JSON.stringify({\n\t\t\t\t\tnetwork: input.network,\n\t\t\t\t\ttransactionBytes: input.transactionBytes,\n\t\t\t\t\tsignature: input.signature,\n\t\t\t\t\tallowedAddresses: input.allowedAddresses,\n\t\t\t\t\tallowedMoveCallTargets: input.allowedMoveCallTargets,\n\t\t\t\t}),\n\t\t\t},\n\t\t);\n\t}\n\n\tgetSubnames(input: GetSubnamesApiInput) {\n\t\tconst query = new URLSearchParams();\n\t\tif (input.address) {\n\t\t\tquery.set('address', input.address);\n\t\t}\n\t\tif (input.network) {\n\t\t\tquery.set('network', input.network);\n\t\t}\n\t\tif (input.domain) {\n\t\t\tquery.set('domain', input.domain);\n\t\t}\n\t\treturn this.#fetch<GetSubnamesApiResponse>(\n\t\t\t'subnames' + (query.size > 0 ? `?${query.toString()}` : ''),\n\t\t\t{\n\t\t\t\tmethod: 'GET',\n\t\t\t},\n\t\t);\n\t}\n\n\tcreateSubname(input: CreateSubnameApiInput) {\n\t\treturn this.#fetch<CreateSubnameApiResponse>('subnames', {\n\t\t\tmethod: 'POST',\n\t\t\theaders: input.jwt\n\t\t\t\t? {\n\t\t\t\t\t\t[ZKLOGIN_HEADER]: input.jwt,\n\t\t\t\t\t}\n\t\t\t\t: {},\n\t\t\tbody: JSON.stringify({\n\t\t\t\tnetwork: input.network,\n\t\t\t\tdomain: input.domain,\n\t\t\t\tsubname: input.subname,\n\t\t\t\ttargetAddress: input.targetAddress,\n\t\t\t}),\n\t\t});\n\t}\n\n\tdeleteSubname(input: DeleteSubnameApiInput) {\n\t\tthis.#fetch<DeleteSubnameApiResponse>('subnames', {\n\t\t\tmethod: 'DELETE',\n\t\t\tbody: JSON.stringify({\n\t\t\t\tnetwork: input.network,\n\t\t\t\tdomain: input.domain,\n\t\t\t\tsubname: input.subname,\n\t\t\t}),\n\t\t});\n\t}\n\n\tasync #fetch<T = unknown>(path: string, init: RequestInit): Promise<T> {\n\t\tconst res = await fetch(`${this.#apiUrl}/${this.#version}/${path}`, {\n\t\t\t...init,\n\t\t\theaders: {\n\t\t\t\t...init.headers,\n\t\t\t\tAuthorization: `Bearer ${this.#apiKey}`,\n\t\t\t\t'Content-Type': 'application/json',\n\t\t\t\t'Request-Id': crypto.randomUUID(),\n\t\t\t},\n\t\t});\n\n\t\tif (!res.ok) {\n\t\t\tthrow new EnokiClientError(res.status, await res.text());\n\t\t}\n\n\t\tconst { data } = await res.json();\n\n\t\treturn data as T;\n\t}\n}\n"],"mappings":";AA4BA,MAAM,kBAAkB;AACxB,MAAM,iBAAiB;AAavB,IAAa,mBAAb,cAAsC,MAAM;CAK3C,YAAY,QAAgB,UAAkB;EAC7C,IAAI;AACJ,MAAI;AAIH,YAHuB,KAAK,MAAM,SAAS,CAGn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AM;IACd,SAAS,MAAM;IACf,eAAe,MAAM;IACrB,CAAC;GACF,CAAC;;CAGH,cAAc,OAA8B;AAC3C,QAAKA,MAAiC,YAAY;GACjD,QAAQ;GACR,MAAM,KAAK,UAAU;IACpB,SAAS,MAAM;IACf,QAAQ,MAAM;IACd,SAAS,MAAM;IACf,CAAC;GACF,CAAC;;CAGH,OAAMA,MAAoB,MAAc,MAA+B;EACtE,MAAM,MAAM,MAAM,MAAM,GAAG,MAAKH,OAAQ,GAAG,MAAKD,QAAS,GAAG,QAAQ;GACnE,GAAG;GACH,SAAS;IACR,GAAG,KAAK;IACR,eAAe,UAAU,MAAKE;IAC9B,gBAAgB;IAChB,cAAc,OAAO,YAAY;IACjC;GACD,CAAC;AAEF,MAAI,CAAC,IAAI,GACR,OAAM,IAAI,iBAAiB,IAAI,QAAQ,MAAM,IAAI,MAAM,CAAC;EAGzD,MAAM,EAAE,SAAS,MAAM,IAAI,MAAM;AAEjC,SAAO"}
@@ -18,6 +18,11 @@ interface GetAppApiResponse {
18
18
  name: string;
19
19
  network: EnokiDomainNetwork;
20
20
  }[];
21
+ /**
22
+ * Enoki's sponsor address on each network it sponsors on. Use it as the gas owner for
23
+ * `sponsorAndExecuteTransaction`.
24
+ */
25
+ sponsorAddresses: Partial<Record<EnokiDomainNetwork, string>>;
21
26
  }
22
27
  interface GetZkLoginApiInput {
23
28
  jwt: string;
@@ -84,6 +89,21 @@ interface ExecuteSponsoredTransactionApiInput {
84
89
  interface ExecuteSponsoredTransactionApiResponse {
85
90
  digest: string;
86
91
  }
92
+ interface SponsorAndExecuteTransactionApiInput {
93
+ network?: EnokiNetwork;
94
+ /**
95
+ * Base64 BCS bytes of the built transaction, with the sponsor address from `getApp` as gas owner
96
+ * and an empty gas payment.
97
+ */
98
+ transactionBytes: string;
99
+ /** The sender's signature over `transactionBytes`. */
100
+ signature: string;
101
+ allowedAddresses?: string[];
102
+ allowedMoveCallTargets?: string[];
103
+ }
104
+ interface SponsorAndExecuteTransactionApiResponse {
105
+ digest: string;
106
+ }
87
107
  interface GetSubnamesApiInput {
88
108
  address?: string;
89
109
  network?: EnokiDomainNetwork;
@@ -115,5 +135,5 @@ interface DeleteSubnameApiInput {
115
135
  subname: string;
116
136
  }
117
137
  //#endregion
118
- export { AuthProvider, CreateSponsoredTransactionApiInput, CreateSponsoredTransactionApiResponse, CreateSubnameApiInput, CreateSubnameApiResponse, CreateZkLoginNonceApiInput, CreateZkLoginNonceApiResponse, CreateZkLoginZkpApiInput, CreateZkLoginZkpApiResponse, DeleteSubnameApiInput, EnokiNetwork, ExecuteSponsoredTransactionApiInput, ExecuteSponsoredTransactionApiResponse, GetAppApiInput, GetAppApiResponse, GetSubnamesApiInput, GetSubnamesApiResponse, GetZkLoginAddressesApiInput, GetZkLoginAddressesApiResponse, GetZkLoginApiInput, GetZkLoginApiResponse };
138
+ export { AuthProvider, CreateSponsoredTransactionApiInput, CreateSponsoredTransactionApiResponse, CreateSubnameApiInput, CreateSubnameApiResponse, CreateZkLoginNonceApiInput, CreateZkLoginNonceApiResponse, CreateZkLoginZkpApiInput, CreateZkLoginZkpApiResponse, DeleteSubnameApiInput, EnokiNetwork, ExecuteSponsoredTransactionApiInput, ExecuteSponsoredTransactionApiResponse, GetAppApiInput, GetAppApiResponse, GetSubnamesApiInput, GetSubnamesApiResponse, GetZkLoginAddressesApiInput, GetZkLoginAddressesApiResponse, GetZkLoginApiInput, GetZkLoginApiResponse, SponsorAndExecuteTransactionApiInput, SponsorAndExecuteTransactionApiResponse };
119
139
  //# sourceMappingURL=type.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"type.d.mts","names":[],"sources":["../../src/EnokiClient/type.ts"],"mappings":";;;;KAMY,YAAA;AAAA,KACA,YAAA;AAAA,KACA,kBAAA;AAAA,KACA,mBAAA;AAAA,UAEK,cAAA;AAAA,UACA,iBAAA;EAChB,cAAA;EACA,uBAAA;IACC,YAAA,EAAc,YAAA;IACd,QAAA;EAAA;EAED,OAAA;IACC,K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EACA,SAAA;AAAA;AAAA,UAGgB,sCAAA;EAChB,MAAA;AAAA;AAAA,UAGgB,oCAAA;EAChB,OAAA,GAAU,YAAA;EArDU;;;;EA0DpB,gBAAA;EAvD6C;EAyD7C,SAAA;EACA,gBAAA;EACA,sBAAA;AAAA;AAAA,UAGgB,uCAAA;EAChB,MAAA;AAAA;AAAA,UAGgB,mBAAA;EAChB,OAAA;EACA,OAAA,GAAU,kBAAA;EACV,MAAA;AAAA;AAAA,UAEgB,sBAAA;EAChB,QAAA;IACC,IAAA;IACA,MAAA,EAAQ,mBAAA;EAAA;AAAA;AAAA,KAIE,qBAAA;EACX,MAAA;EACA,OAAA,GAAU,kBAAA;EACV,OAAA;AAAA;EAGE,GAAA;EACA,aAAA;AAAA;EAGA,aAAA;EACA,GAAA;AAAA;AAAA,UAGc,wBAAA;EAChB,IAAA;AAAA;AAAA,UAGgB,qBAAA;EAChB,MAAA;EACA,OAAA,GAAU,kBAAA;EACV,OAAA;AAAA"}
@@ -1,4 +1,4 @@
1
- import { AuthProvider, EnokiNetwork } from "./EnokiClient/type.mjs";
1
+ import { AuthProvider, CreateZkLoginZkpApiResponse, EnokiNetwork } from "./EnokiClient/type.mjs";
2
2
  import { EnokiClient, EnokiClientConfig } from "./EnokiClient/index.mjs";
3
3
  import { Encryption } from "./encryption.mjs";
4
4
  import { EnokiKeypair } from "./EnokiKeypair.mjs";
@@ -70,27 +70,7 @@ declare class EnokiFlow {
70
70
  network
71
71
  }?: {
72
72
  network?: EnokiNetwork;
73
- }): Promise<{
74
- proofPoints: {
75
- a: Iterable<string> & {
76
- length: number;
77
- };
78
- b: Iterable<Iterable<string> & {
79
- length: number;
80
- }> & {
81
- length: number;
82
- };
83
- c: Iterable<string> & {
84
- length: number;
85
- };
86
- };
87
- issBase64Details: {
88
- value: string;
89
- indexMod4: number;
90
- };
91
- headerBase64: string;
92
- addressSeed: string;
93
- }>;
73
+ }): Promise<CreateZkLoginZkpApiResponse>;
94
74
  getKeypair({
95
75
  network
96
76
  }?: {
@@ -1 +1 @@
1
- {"version":3,"file":"EnokiFlow.d.mts","names":[],"sources":["../src/EnokiFlow.ts"],"mappings":";;;;;;;;;;AA2BA;;KAAY,eAAA,GAAkB,iBAAA;EAG1B,+BAAA;EAKQ;;;;EAAR,KAAA,GAAQ,SAAA;EALR;;;;EAUA,UAAA,GAAa,UAAA;AAAA;EAGb,KAAA;EACA,UAAA;EAI+B;;AAKnC;EALI,+BAAA;AAAA;AAAA,UAKa,YAAA;EAChB,QAAA,GAAW,YAAA;EACX,OAAA;EACA,IAAA;EACA,SAAA;AAAA;AAAA,UAIgB,cAAA;EAChB,gBAAA;EACA,QAAA;EACA,UAAA;EACA,SAAA;EAEA,GAAA;EACA,KAAA,GAAQ,sBAAA;AAAA;;;;cAWI,SAAA;EAAA;EASZ,eAAA,EAAiB,YAAA;IAAe,WAAA;IAAsB,KAAA,EAAO,cAAA;EAAA;EAC7D,aAAA,EAAe,YAAA,CAAa,YAAA;cAEhB,MAAA,EAAQ,eAAA;EAAA,IA0ChB,WAAA,CAAA,GAAW,WAAA;EAIT,sBAAA,CAAuB,KAAA;IAC5B,QAAA,EAAU,YAAA;IACV,QAAA;IACA,WAAA;IACA,OAAA;IACA,WAAA,GAAc,MAAA;EAAA,IACd,OAAA;EAuEK,kBAAA,CAAmB,IAAA,YAAmC,OAAA;EAkDtD,UAAA,CAAA,GAAU,OAAA,CAAA,cAAA;EA2BV,MAAA,CAAA,GAAM,OAAA;EAWN,QAAA,CAAA;IAAW;EAAA;IAAa,OAAA,GAAU,YAAA;EAAA,IAAmB,OAAA;;;;;;;;;;;;;;;;;;;;;EA6CrD,UAAA,CAAA;IAAa;EAAA;IAAa,OAAA,GAAU,YAAA;EAAA,IAAmB,OAAA,CAAA,YAAA;AAAA"}
1
+ {"version":3,"file":"EnokiFlow.d.mts","names":[],"sources":["../src/EnokiFlow.ts"],"mappings":";;;;;;;;;;AA2BA;;KAAY,eAAA,GAAkB,iBAAA;EAG1B,+BAAA;EAKQ;;;;EAAR,KAAA,GAAQ,SAAA;EALR;;;;EAUA,UAAA,GAAa,UAAA;AAAA;EAGb,KAAA;EACA,UAAA;EAI+B;;AAKnC;EALI,+BAAA;AAAA;AAAA,UAKa,YAAA;EAChB,QAAA,GAAW,YAAA;EACX,OAAA;EACA,IAAA;EACA,SAAA;AAAA;AAAA,UAIgB,cAAA;EAChB,gBAAA;EACA,QAAA;EACA,UAAA;EACA,SAAA;EAEA,GAAA;EACA,KAAA,GAAQ,sBAAA;AAAA;;;;cAWI,SAAA;EAAA;EASZ,eAAA,EAAiB,YAAA;IAAe,WAAA;IAAsB,KAAA,EAAO,cAAA;EAAA;EAC7D,aAAA,EAAe,YAAA,CAAa,YAAA;cAEhB,MAAA,EAAQ,eAAA;EAAA,IA0ChB,WAAA,CAAA,GAAW,WAAA;EAIT,sBAAA,CAAuB,KAAA;IAC5B,QAAA,EAAU,YAAA;IACV,QAAA;IACA,WAAA;IACA,OAAA;IACA,WAAA,GAAc,MAAA;EAAA,IACd,OAAA;EAuEK,kBAAA,CAAmB,IAAA,YAAmC,OAAA;EAkDtD,UAAA,CAAA,GAAU,OAAA,CAAA,cAAA;EA2BV,MAAA,CAAA,GAAM,OAAA;EAWN,QAAA,CAAA;IAAW;EAAA;IAAa,OAAA,GAAU,YAAA;EAAA,IAAmB,OAAA,CAAP,2BAAA;EA6C9C,UAAA,CAAA;IAAa;EAAA;IAAa,OAAA,GAAU,YAAA;EAAA,IAAmB,OAAA,CAAA,YAAA;AAAA"}
@@ -2,10 +2,10 @@ import { EnokiClient } from "./EnokiClient/index.mjs";
2
2
  import { createDefaultEncryption } from "./encryption.mjs";
3
3
  import { EnokiKeypair } from "./EnokiKeypair.mjs";
4
4
  import { createSessionStorage } from "./stores.mjs";
5
+ import { fromBase64, toBase64 } from "@mysten/sui/utils";
5
6
  import { WebCryptoSigner } from "@mysten/webcrypto-signer";
6
7
  import { decodeSuiPrivateKey } from "@mysten/sui/cryptography";
7
8
  import { Ed25519Keypair } from "@mysten/sui/keypairs/ed25519";
8
- import { fromBase64, toBase64 } from "@mysten/sui/utils";
9
9
  import { decodeJwt } from "@mysten/sui/zklogin";
10
10
  import { clear, createStore, get, set } from "idb-keyval";
11
11
  import { atom, onMount, onSet } from "nanostores";
package/dist/client.d.mts CHANGED
@@ -1,3 +1,4 @@
1
1
  import { AuthProvider, EnokiNetwork } from "./EnokiClient/type.mjs";
2
- import { EnokiClient, EnokiClientConfig, EnokiClientError } from "./EnokiClient/index.mjs";
3
- export { type AuthProvider, EnokiClient, type EnokiClientConfig, EnokiClientError, type EnokiNetwork };
2
+ import { EnokiClient, EnokiClientConfig, EnokiClientError, isStaleTransactionError } from "./EnokiClient/index.mjs";
3
+ import { EnokiClientExtension, EnokiExtensionOptions, EnokiPrepareSponsoredTransactionOptions, EnokiSponsorAndExecuteTransactionOptions, enoki } from "./extension.mjs";
4
+ export { type AuthProvider, EnokiClient, type EnokiClientConfig, EnokiClientError, EnokiClientExtension, type EnokiExtensionOptions, type EnokiNetwork, type EnokiPrepareSponsoredTransactionOptions, type EnokiSponsorAndExecuteTransactionOptions, enoki, isStaleTransactionError };
package/dist/client.mjs CHANGED
@@ -1,3 +1,4 @@
1
- import { EnokiClient, EnokiClientError } from "./EnokiClient/index.mjs";
1
+ import { EnokiClient, EnokiClientError, isStaleTransactionError } from "./EnokiClient/index.mjs";
2
+ import { EnokiClientExtension, enoki } from "./extension.mjs";
2
3
 
3
- export { EnokiClient, EnokiClientError };
4
+ export { EnokiClient, EnokiClientError, EnokiClientExtension, enoki, isStaleTransactionError };
@@ -0,0 +1,90 @@
1
+ import { EnokiClient, EnokiClientConfig } from "./EnokiClient/index.mjs";
2
+ import { Transaction } from "@mysten/sui/transactions";
3
+ import { Signer } from "@mysten/sui/cryptography";
4
+ import { ClientWithCoreApi, SuiClientTypes } from "@mysten/sui/client";
5
+
6
+ //#region src/extension.d.ts
7
+ type EnokiExtensionOptions<Name extends string = 'enoki'> = Omit<EnokiClientConfig, 'additionalEpochs'> & {
8
+ name?: Name;
9
+ };
10
+ interface EnokiSponsorAndExecuteBaseOptions<Include extends SuiClientTypes.TransactionInclude> extends SuiClientTypes.CoreClientMethodOptions {
11
+ /** Addresses the transaction may use, in addition to the app's allowlist in the Enoki Portal. */
12
+ allowedAddresses?: string[];
13
+ /** Move call targets the transaction may call, in addition to the app's allowlist in the Enoki Portal. */
14
+ allowedMoveCallTargets?: string[];
15
+ include?: Include & SuiClientTypes.TransactionInclude;
16
+ }
17
+ type EnokiSponsorAndExecuteTransactionOptions<Include extends SuiClientTypes.TransactionInclude = {}> = EnokiSponsorAndExecuteBaseOptions<Include> & ({
18
+ /** The transaction to send. Enoki is set as gas owner, and the sender defaults to `signer`. */transaction: Transaction; /** Signs as the transaction sender. */
19
+ signer: Signer;
20
+ signature?: never;
21
+ } | {
22
+ /**
23
+ * Built transaction bytes (or base64) of a transaction prepared with
24
+ * `prepareSponsoredTransaction`.
25
+ */
26
+ transaction: Uint8Array | string; /** The sender's signature over the bytes. */
27
+ signature: string;
28
+ signer?: never;
29
+ });
30
+ interface EnokiPrepareSponsoredTransactionOptions {
31
+ /** The transaction to prepare. Enoki is set as gas owner, paying from its address balance. */
32
+ transaction: Transaction;
33
+ }
34
+ /**
35
+ * Adds Enoki sponsorship to a Sui client. Requires a private API key with sponsored transactions
36
+ * enabled.
37
+ *
38
+ * @example
39
+ * ```ts
40
+ * const client = new SuiGrpcClient({ network: 'mainnet', baseUrl }).$extend(
41
+ * enoki({ apiKey: process.env.ENOKI_PRIVATE_KEY! }),
42
+ * );
43
+ *
44
+ * const result = await client.enoki.sponsorAndExecuteTransaction({ transaction, signer });
45
+ * ```
46
+ */
47
+ declare function enoki<const Name extends string = 'enoki'>({
48
+ name,
49
+ ...config
50
+ }: EnokiExtensionOptions<Name>): {
51
+ name: Name;
52
+ register: (client: ClientWithCoreApi) => EnokiClientExtension;
53
+ };
54
+ declare class EnokiClientExtension {
55
+ #private;
56
+ constructor({
57
+ client,
58
+ enoki
59
+ }: {
60
+ client: ClientWithCoreApi;
61
+ enoki: EnokiClient;
62
+ });
63
+ /** Enoki's sponsor address on the client's network. Cached until a transaction is rejected as stale. */
64
+ getSponsorAddress(): Promise<string>;
65
+ /**
66
+ * Sets Enoki as the transaction's gas owner with an empty gas payment.
67
+ * Doesn't build it, so a wallet can still resolve the rest. Build or have a wallet sign it, run
68
+ * any checks, then pass the bytes and signature to `sponsorAndExecuteTransaction`.
69
+ *
70
+ * Safe to call on a transaction that's already prepared. Throws if the transaction already has
71
+ * a different gas owner, or a gas payment.
72
+ */
73
+ prepareSponsoredTransaction({
74
+ transaction
75
+ }: EnokiPrepareSponsoredTransactionOptions): Promise<Transaction>;
76
+ /**
77
+ * Has Enoki sponsor and execute a transaction, and waits for it. Returns the same result as
78
+ * `client.core.signAndExecuteTransaction`.
79
+ *
80
+ * With a `signer`, the transaction is prepared with `prepareSponsoredTransaction`, built and
81
+ * signed here. With a `signature`, the bytes are sent as they are.
82
+ *
83
+ * Enoki errors are thrown as `EnokiClientError`. If `isStaleTransactionError(error)`, build a new
84
+ * transaction, sign it and call this again; the sponsor address is fetched again.
85
+ */
86
+ sponsorAndExecuteTransaction<Include extends SuiClientTypes.TransactionInclude = {}>(options: EnokiSponsorAndExecuteTransactionOptions<Include>): Promise<SuiClientTypes.TransactionResult<Include>>;
87
+ }
88
+ //#endregion
89
+ export { EnokiClientExtension, EnokiExtensionOptions, EnokiPrepareSponsoredTransactionOptions, EnokiSponsorAndExecuteTransactionOptions, enoki };
90
+ //# sourceMappingURL=extension.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"extension.d.mts","names":[],"sources":["../src/extension.ts"],"mappings":";;;;;;KAYY,qBAAA,kCAAuD,IAAA,CAClE,iBAAA;EAGA,IAAA,GAAO,IAAA;AAAA;AAAA,UAGE,iCAAA,iBAAkD,cAAA,CAAe,kBAAA,UAClE,cAAA,CAAe,uBAAA;EAPvB;EASA,gBAAA;EANO;EAQP,sBAAA;EACA,OAAA,GAAU,OAAA,GAAU,cAAA,CAAe,kBAAA;AAAA;AAAA,KAGxB,wCAAA,iBACK,cAAA,CAAe,kBAAA,SAC5B,iCAAA,CAAkC,OAAA;EAjBrC,+FAqBG,WAAA,EAAa,WAAA,EAlBT;EAoBJ,MAAA,EAAQ,MAAA;EACR,SAAA;AAAA;EAlBuC;;;;EAyBvC,WAAA,EAAa,UAAA,WAxBR;EA0BL,SAAA;EACA,MAAA;AAAA;AAAA,UAIa,uCAAA;EAhC0D;EAkC1E,WAAA,EAAa,WAAA;AAAA;;;;;;;;;AAzBd;;;;;iBAyCgB,KAAA,qCAAA,CAAA;EACf,IAAA;EAAA,GACG;AAAA,GACD,qBAAA,CAAsB,IAAA;;qBAGJ,iBAAA,KAAiB,oBAAA;AAAA;AAAA,cAKzB,oBAAA;EAAA;;IAKE,MAAA;IAAQ;EAAA;IAAW,MAAA,EAAQ,iBAAA;IAAmB,KAAA,EAAO,WAAA;EAAA;EAvD9B;EA6DrC,iBAAA,CAAA,GAAqB,OAAA;EAzDL;;;;;;;;EAqFV,2BAAA,CAAA;IACL;EAAA,GACE,uCAAA,GAA0C,OAAA,CAAQ,WAAA;EA1E5C;AAIV;;;;;AAkBA;;;;EAgFO,4BAAA,iBAA6C,cAAA,CAAe,kBAAA,MAAA,CACjE,OAAA,EAAS,wCAAA,CAAyC,OAAA,IAChD,OAAA,CAAQ,cAAA,CAAe,iBAAA,CAAkB,OAAA;AAAA"}
@@ -0,0 +1,125 @@
1
+ import { EnokiClient, isStaleTransactionError } from "./EnokiClient/index.mjs";
2
+ import { TransactionDataBuilder } from "@mysten/sui/transactions";
3
+ import { fromBase64, normalizeSuiAddress, toBase64 } from "@mysten/sui/utils";
4
+
5
+ //#region src/extension.ts
6
+ /**
7
+ * Adds Enoki sponsorship to a Sui client. Requires a private API key with sponsored transactions
8
+ * enabled.
9
+ *
10
+ * @example
11
+ * ```ts
12
+ * const client = new SuiGrpcClient({ network: 'mainnet', baseUrl }).$extend(
13
+ * enoki({ apiKey: process.env.ENOKI_PRIVATE_KEY! }),
14
+ * );
15
+ *
16
+ * const result = await client.enoki.sponsorAndExecuteTransaction({ transaction, signer });
17
+ * ```
18
+ */
19
+ function enoki({ name = "enoki", ...config }) {
20
+ return {
21
+ name,
22
+ register: (client) => new EnokiClientExtension({
23
+ client,
24
+ enoki: new EnokiClient(config)
25
+ })
26
+ };
27
+ }
28
+ var EnokiClientExtension = class {
29
+ #client;
30
+ #enoki;
31
+ #sponsorAddress;
32
+ constructor({ client, enoki: enoki$1 }) {
33
+ this.#client = client;
34
+ this.#enoki = enoki$1;
35
+ }
36
+ /** Enoki's sponsor address on the client's network. Cached until a transaction is rejected as stale. */
37
+ getSponsorAddress() {
38
+ if (!this.#sponsorAddress) {
39
+ const network = this.#network();
40
+ const promise = this.#enoki.getApp().then(({ sponsorAddresses }) => {
41
+ const address = sponsorAddresses?.[network];
42
+ if (!address) throw new Error(`Enoki does not sponsor transactions on ${network}`);
43
+ return normalizeSuiAddress(address);
44
+ });
45
+ this.#sponsorAddress = promise;
46
+ promise.catch(() => {
47
+ if (this.#sponsorAddress === promise) this.#sponsorAddress = void 0;
48
+ });
49
+ }
50
+ return this.#sponsorAddress;
51
+ }
52
+ /**
53
+ * Sets Enoki as the transaction's gas owner with an empty gas payment.
54
+ * Doesn't build it, so a wallet can still resolve the rest. Build or have a wallet sign it, run
55
+ * any checks, then pass the bytes and signature to `sponsorAndExecuteTransaction`.
56
+ *
57
+ * Safe to call on a transaction that's already prepared. Throws if the transaction already has
58
+ * a different gas owner, or a gas payment.
59
+ */
60
+ async prepareSponsoredTransaction({ transaction }) {
61
+ const sponsorAddress = await this.getSponsorAddress();
62
+ const data = transaction.getData();
63
+ if (data.gasData.owner && normalizeSuiAddress(data.gasData.owner) !== sponsorAddress) throw new Error(`Transaction gas owner is ${data.gasData.owner}, not Enoki's sponsor ${sponsorAddress}`);
64
+ if (data.gasData.payment && data.gasData.payment.length > 0) throw new Error("Sponsored transactions pay gas from the sponsor; remove the gas payment");
65
+ transaction.setGasOwner(sponsorAddress);
66
+ transaction.setGasPayment([]);
67
+ return transaction;
68
+ }
69
+ /**
70
+ * Has Enoki sponsor and execute a transaction, and waits for it. Returns the same result as
71
+ * `client.core.signAndExecuteTransaction`.
72
+ *
73
+ * With a `signer`, the transaction is prepared with `prepareSponsoredTransaction`, built and
74
+ * signed here. With a `signature`, the bytes are sent as they are.
75
+ *
76
+ * Enoki errors are thrown as `EnokiClientError`. If `isStaleTransactionError(error)`, build a new
77
+ * transaction, sign it and call this again; the sponsor address is fetched again.
78
+ */
79
+ async sponsorAndExecuteTransaction(options) {
80
+ const network = this.#network();
81
+ let bytes;
82
+ let signature;
83
+ if (options.signer) {
84
+ const { transaction, signer } = options;
85
+ transaction.setSenderIfNotSet(signer.toSuiAddress());
86
+ await this.prepareSponsoredTransaction({ transaction });
87
+ bytes = await transaction.build({ client: this.#client });
88
+ ({signature} = await signer.signTransaction(bytes));
89
+ } else {
90
+ bytes = options.transaction;
91
+ signature = options.signature;
92
+ }
93
+ const transactionBytes = typeof bytes === "string" ? fromBase64(bytes) : bytes;
94
+ const digest = TransactionDataBuilder.getDigestFromBytes(transactionBytes);
95
+ let response;
96
+ try {
97
+ options.signal?.throwIfAborted();
98
+ response = await this.#enoki.sponsorAndExecuteTransaction({
99
+ network,
100
+ transactionBytes: toBase64(transactionBytes),
101
+ signature,
102
+ allowedAddresses: options.allowedAddresses,
103
+ allowedMoveCallTargets: options.allowedMoveCallTargets
104
+ });
105
+ } catch (error) {
106
+ if (isStaleTransactionError(error)) this.#sponsorAddress = void 0;
107
+ throw error;
108
+ }
109
+ if (response.digest !== digest) throw new Error(`Enoki returned digest ${response.digest}, but the transaction is ${digest}`);
110
+ return this.#client.core.waitForTransaction({
111
+ digest,
112
+ include: options.include,
113
+ signal: options.signal
114
+ });
115
+ }
116
+ #network() {
117
+ const network = this.#client.network;
118
+ if (network === "mainnet" || network === "testnet") return network;
119
+ throw new Error(`Enoki sponsorship is not available on ${network}`);
120
+ }
121
+ };
122
+
123
+ //#endregion
124
+ export { EnokiClientExtension, enoki };
125
+ //# sourceMappingURL=extension.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"extension.mjs","names":["#client","#enoki","enoki","#sponsorAddress","#network"],"sources":["../src/extension.ts"],"sourcesContent":["// Copyright (c) Mysten Labs, Inc.\n// SPDX-License-Identifier: Apache-2.0\n\nimport type { ClientWithCoreApi, SuiClientTypes } from '@mysten/sui/client';\nimport type { Signer } from '@mysten/sui/cryptography';\nimport { TransactionDataBuilder, type Transaction } from '@mysten/sui/transactions';\nimport { fromBase64, normalizeSuiAddress, toBase64 } from '@mysten/sui/utils';\n\nimport type { EnokiClientConfig } from './EnokiClient/index.js';\nimport { EnokiClient, isStaleTransactionError } from './EnokiClient/index.js';\nimport type { EnokiDomainNetwork } from './EnokiClient/type.js';\n\nexport type EnokiExtensionOptions<Name extends string = 'enoki'> = Omit<\n\tEnokiClientConfig,\n\t'additionalEpochs'\n> & {\n\tname?: Name;\n};\n\ninterface EnokiSponsorAndExecuteBaseOptions<Include extends SuiClientTypes.TransactionInclude>\n\textends SuiClientTypes.CoreClientMethodOptions {\n\t/** Addresses the transaction may use, in addition to the app's allowlist in the Enoki Portal. */\n\tallowedAddresses?: string[];\n\t/** Move call targets the transaction may call, in addition to the app's allowlist in the Enoki Portal. */\n\tallowedMoveCallTargets?: string[];\n\tinclude?: Include & SuiClientTypes.TransactionInclude;\n}\n\nexport type EnokiSponsorAndExecuteTransactionOptions<\n\tInclude extends SuiClientTypes.TransactionInclude = {},\n> = EnokiSponsorAndExecuteBaseOptions<Include> &\n\t(\n\t\t| {\n\t\t\t\t/** The transaction to send. Enoki is set as gas owner, and the sender defaults to `signer`. */\n\t\t\t\ttransaction: Transaction;\n\t\t\t\t/** Signs as the transaction sender. */\n\t\t\t\tsigner: Signer;\n\t\t\t\tsignature?: never;\n\t\t }\n\t\t| {\n\t\t\t\t/**\n\t\t\t\t * Built transaction bytes (or base64) of a transaction prepared with\n\t\t\t\t * `prepareSponsoredTransaction`.\n\t\t\t\t */\n\t\t\t\ttransaction: Uint8Array | string;\n\t\t\t\t/** The sender's signature over the bytes. */\n\t\t\t\tsignature: string;\n\t\t\t\tsigner?: never;\n\t\t }\n\t);\n\nexport interface EnokiPrepareSponsoredTransactionOptions {\n\t/** The transaction to prepare. Enoki is set as gas owner, paying from its address balance. */\n\ttransaction: Transaction;\n}\n\n/**\n * Adds Enoki sponsorship to a Sui client. Requires a private API key with sponsored transactions\n * enabled.\n *\n * @example\n * ```ts\n * const client = new SuiGrpcClient({ network: 'mainnet', baseUrl }).$extend(\n * enoki({ apiKey: process.env.ENOKI_PRIVATE_KEY! }),\n * );\n *\n * const result = await client.enoki.sponsorAndExecuteTransaction({ transaction, signer });\n * ```\n */\nexport function enoki<const Name extends string = 'enoki'>({\n\tname = 'enoki' as Name,\n\t...config\n}: EnokiExtensionOptions<Name>) {\n\treturn {\n\t\tname,\n\t\tregister: (client: ClientWithCoreApi) =>\n\t\t\tnew EnokiClientExtension({ client, enoki: new EnokiClient(config) }),\n\t};\n}\n\nexport class EnokiClientExtension {\n\t#client: ClientWithCoreApi;\n\t#enoki: EnokiClient;\n\t#sponsorAddress?: Promise<string>;\n\n\tconstructor({ client, enoki }: { client: ClientWithCoreApi; enoki: EnokiClient }) {\n\t\tthis.#client = client;\n\t\tthis.#enoki = enoki;\n\t}\n\n\t/** Enoki's sponsor address on the client's network. Cached until a transaction is rejected as stale. */\n\tgetSponsorAddress(): Promise<string> {\n\t\tif (!this.#sponsorAddress) {\n\t\t\tconst network = this.#network();\n\t\t\tconst promise = this.#enoki.getApp().then(({ sponsorAddresses }) => {\n\t\t\t\tconst address = sponsorAddresses?.[network];\n\t\t\t\tif (!address) {\n\t\t\t\t\tthrow new Error(`Enoki does not sponsor transactions on ${network}`);\n\t\t\t\t}\n\t\t\t\treturn normalizeSuiAddress(address);\n\t\t\t});\n\t\t\tthis.#sponsorAddress = promise;\n\t\t\tpromise.catch(() => {\n\t\t\t\tif (this.#sponsorAddress === promise) {\n\t\t\t\t\tthis.#sponsorAddress = undefined;\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\t\treturn this.#sponsorAddress;\n\t}\n\n\t/**\n\t * Sets Enoki as the transaction's gas owner with an empty gas payment.\n\t * Doesn't build it, so a wallet can still resolve the rest. Build or have a wallet sign it, run\n\t * any checks, then pass the bytes and signature to `sponsorAndExecuteTransaction`.\n\t *\n\t * Safe to call on a transaction that's already prepared. Throws if the transaction already has\n\t * a different gas owner, or a gas payment.\n\t */\n\tasync prepareSponsoredTransaction({\n\t\ttransaction,\n\t}: EnokiPrepareSponsoredTransactionOptions): Promise<Transaction> {\n\t\tconst sponsorAddress = await this.getSponsorAddress();\n\t\tconst data = transaction.getData();\n\n\t\tif (data.gasData.owner && normalizeSuiAddress(data.gasData.owner) !== sponsorAddress) {\n\t\t\tthrow new Error(\n\t\t\t\t`Transaction gas owner is ${data.gasData.owner}, not Enoki's sponsor ${sponsorAddress}`,\n\t\t\t);\n\t\t}\n\t\tif (data.gasData.payment && data.gasData.payment.length > 0) {\n\t\t\tthrow new Error('Sponsored transactions pay gas from the sponsor; remove the gas payment');\n\t\t}\n\n\t\ttransaction.setGasOwner(sponsorAddress);\n\t\ttransaction.setGasPayment([]);\n\t\treturn transaction;\n\t}\n\n\t/**\n\t * Has Enoki sponsor and execute a transaction, and waits for it. Returns the same result as\n\t * `client.core.signAndExecuteTransaction`.\n\t *\n\t * With a `signer`, the transaction is prepared with `prepareSponsoredTransaction`, built and\n\t * signed here. With a `signature`, the bytes are sent as they are.\n\t *\n\t * Enoki errors are thrown as `EnokiClientError`. If `isStaleTransactionError(error)`, build a new\n\t * transaction, sign it and call this again; the sponsor address is fetched again.\n\t */\n\tasync sponsorAndExecuteTransaction<Include extends SuiClientTypes.TransactionInclude = {}>(\n\t\toptions: EnokiSponsorAndExecuteTransactionOptions<Include>,\n\t): Promise<SuiClientTypes.TransactionResult<Include>> {\n\t\tconst network = this.#network();\n\n\t\tlet bytes: Uint8Array | string;\n\t\tlet signature: string;\n\t\tif (options.signer) {\n\t\t\tconst { transaction, signer } = options;\n\t\t\ttransaction.setSenderIfNotSet(signer.toSuiAddress());\n\t\t\tawait this.prepareSponsoredTransaction({ transaction });\n\t\t\tbytes = await transaction.build({ client: this.#client });\n\t\t\t({ signature } = await signer.signTransaction(bytes));\n\t\t} else {\n\t\t\tbytes = options.transaction;\n\t\t\tsignature = options.signature;\n\t\t}\n\n\t\tconst transactionBytes = typeof bytes === 'string' ? fromBase64(bytes) : bytes;\n\t\t// Wait on the digest of the bytes that were signed, not one reported by the server.\n\t\tconst digest = TransactionDataBuilder.getDigestFromBytes(transactionBytes);\n\n\t\tlet response: { digest: string };\n\t\ttry {\n\t\t\toptions.signal?.throwIfAborted();\n\t\t\tresponse = await this.#enoki.sponsorAndExecuteTransaction({\n\t\t\t\tnetwork,\n\t\t\t\ttransactionBytes: toBase64(transactionBytes),\n\t\t\t\tsignature,\n\t\t\t\tallowedAddresses: options.allowedAddresses,\n\t\t\t\tallowedMoveCallTargets: options.allowedMoveCallTargets,\n\t\t\t});\n\t\t} catch (error) {\n\t\t\tif (isStaleTransactionError(error)) {\n\t\t\t\tthis.#sponsorAddress = undefined;\n\t\t\t}\n\t\t\tthrow error;\n\t\t}\n\t\tif (response.digest !== digest) {\n\t\t\tthrow new Error(`Enoki returned digest ${response.digest}, but the transaction is ${digest}`);\n\t\t}\n\n\t\treturn this.#client.core.waitForTransaction({\n\t\t\tdigest,\n\t\t\tinclude: options.include,\n\t\t\tsignal: options.signal,\n\t\t});\n\t}\n\n\t#network(): EnokiDomainNetwork {\n\t\tconst network: string = this.#client.network;\n\t\tif (network === 'mainnet' || network === 'testnet') {\n\t\t\treturn network;\n\t\t}\n\t\tthrow new Error(`Enoki sponsorship is not available on ${network}`);\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAqEA,SAAgB,MAA2C,EAC1D,OAAO,SACP,GAAG,UAC4B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a,CAAC;AACvD,WAAQ,MAAM,YAAY,MAAM,EAAE,QAAQ,MAAKJ,QAAS,CAAC;AACzD,IAAC,CAAE,aAAc,MAAM,OAAO,gBAAgB,MAAM;SAC9C;AACN,WAAQ,QAAQ;AAChB,eAAY,QAAQ;;EAGrB,MAAM,mBAAmB,OAAO,UAAU,WAAW,WAAW,MAAM,GAAG;EAEzE,MAAM,SAAS,uBAAuB,mBAAmB,iBAAiB;EAE1E,IAAI;AACJ,MAAI;AACH,WAAQ,QAAQ,gBAAgB;AAChC,cAAW,MAAM,MAAKC,MAAO,6BAA6B;IACzD;IACA,kBAAkB,SAAS,iBAAiB;IAC5C;IACA,kBAAkB,QAAQ;IAC1B,wBAAwB,QAAQ;IAChC,CAAC;WACM,OAAO;AACf,OAAI,wBAAwB,MAAM,CACjC,OAAKE,iBAAkB;AAExB,SAAM;;AAEP,MAAI,SAAS,WAAW,OACvB,OAAM,IAAI,MAAM,yBAAyB,SAAS,OAAO,2BAA2B,SAAS;AAG9F,SAAO,MAAKH,OAAQ,KAAK,mBAAmB;GAC3C;GACA,SAAS,QAAQ;GACjB,QAAQ,QAAQ;GAChB,CAAC;;CAGH,WAA+B;EAC9B,MAAM,UAAkB,MAAKA,OAAQ;AACrC,MAAI,YAAY,aAAa,YAAY,UACxC,QAAO;AAER,QAAM,IAAI,MAAM,yCAAyC,UAAU"}
package/dist/index.d.mts CHANGED
@@ -1,5 +1,6 @@
1
1
  import { AuthProvider, EnokiNetwork } from "./EnokiClient/type.mjs";
2
- import { EnokiClient, EnokiClientConfig, EnokiClientError } from "./EnokiClient/index.mjs";
2
+ import { EnokiClient, EnokiClientConfig, EnokiClientError, isStaleTransactionError } from "./EnokiClient/index.mjs";
3
+ import { EnokiClientExtension, EnokiExtensionOptions, EnokiPrepareSponsoredTransactionOptions, EnokiSponsorAndExecuteTransactionOptions, enoki } from "./extension.mjs";
3
4
  import "./client.mjs";
4
5
  import { Encryption, createDefaultEncryption } from "./encryption.mjs";
5
6
  import { EnokiKeypair, EnokiPublicKey } from "./EnokiKeypair.mjs";
@@ -11,4 +12,4 @@ import { registerEnokiWallets } from "./wallet/register.mjs";
11
12
  import { enokiWalletsInitializer } from "./wallet/initializer.mjs";
12
13
  import { getSession, getWalletMetadata, isEnokiWallet, isFacebookWallet, isGoogleWallet, isTwitchWallet } from "./wallet/utils.mjs";
13
14
  import { isEnokiNetwork } from "./utils.mjs";
14
- export { AuthProvider, type Encryption, EnokiClient, EnokiClientConfig, EnokiClientError, EnokiFlow, type EnokiFlowConfig, EnokiKeypair, EnokiNetwork, EnokiPublicKey, type EnokiWallet, type RegisterEnokiWalletsOptions, type SyncStore, createDefaultEncryption, createInMemoryStorage, createLocalStorage, createSessionStorage, enokiWalletsInitializer, getSession, getWalletMetadata, isEnokiNetwork, isEnokiWallet, isFacebookWallet, isGoogleWallet, isTwitchWallet, registerEnokiWallets };
15
+ export { AuthProvider, type Encryption, EnokiClient, EnokiClientConfig, EnokiClientError, EnokiClientExtension, EnokiExtensionOptions, EnokiFlow, type EnokiFlowConfig, EnokiKeypair, EnokiNetwork, EnokiPrepareSponsoredTransactionOptions, EnokiPublicKey, EnokiSponsorAndExecuteTransactionOptions, type EnokiWallet, type RegisterEnokiWalletsOptions, type SyncStore, createDefaultEncryption, createInMemoryStorage, createLocalStorage, createSessionStorage, enoki, enokiWalletsInitializer, getSession, getWalletMetadata, isEnokiNetwork, isEnokiWallet, isFacebookWallet, isGoogleWallet, isStaleTransactionError, isTwitchWallet, registerEnokiWallets };
package/dist/index.mjs CHANGED
@@ -1,4 +1,6 @@
1
- import { EnokiClient, EnokiClientError } from "./EnokiClient/index.mjs";
1
+ import { EnokiClient, EnokiClientError, isStaleTransactionError } from "./EnokiClient/index.mjs";
2
+ import { EnokiClientExtension, enoki } from "./extension.mjs";
3
+ import "./client.mjs";
2
4
  import { createDefaultEncryption } from "./encryption.mjs";
3
5
  import { EnokiKeypair, EnokiPublicKey } from "./EnokiKeypair.mjs";
4
6
  import { createInMemoryStorage, createLocalStorage, createSessionStorage } from "./stores.mjs";
@@ -8,4 +10,4 @@ import { registerEnokiWallets } from "./wallet/register.mjs";
8
10
  import { enokiWalletsInitializer } from "./wallet/initializer.mjs";
9
11
  import { getSession, getWalletMetadata, isEnokiWallet, isFacebookWallet, isGoogleWallet, isTwitchWallet } from "./wallet/utils.mjs";
10
12
 
11
- export { EnokiClient, EnokiClientError, EnokiFlow, EnokiKeypair, EnokiPublicKey, createDefaultEncryption, createInMemoryStorage, createLocalStorage, createSessionStorage, enokiWalletsInitializer, getSession, getWalletMetadata, isEnokiNetwork, isEnokiWallet, isFacebookWallet, isGoogleWallet, isTwitchWallet, registerEnokiWallets };
13
+ export { EnokiClient, EnokiClientError, EnokiClientExtension, EnokiFlow, EnokiKeypair, EnokiPublicKey, createDefaultEncryption, createInMemoryStorage, createLocalStorage, createSessionStorage, enoki, enokiWalletsInitializer, getSession, getWalletMetadata, isEnokiNetwork, isEnokiWallet, isFacebookWallet, isGoogleWallet, isStaleTransactionError, isTwitchWallet, registerEnokiWallets };
@@ -2,11 +2,11 @@ import { EnokiClient } from "../EnokiClient/index.mjs";
2
2
  import { EnokiKeypair } from "../EnokiKeypair.mjs";
3
3
  import { EnokiGetMetadata, EnokiGetSession } from "./features.mjs";
4
4
  import { EnokiWalletState } from "./state.mjs";
5
- import { WebCryptoSigner } from "@mysten/webcrypto-signer";
5
+ import { Transaction } from "@mysten/sui/transactions";
6
6
  import { fromBase64, toBase64 } from "@mysten/sui/utils";
7
+ import { WebCryptoSigner } from "@mysten/webcrypto-signer";
7
8
  import { decodeJwt } from "@mysten/sui/zklogin";
8
9
  import { get, set } from "idb-keyval";
9
- import { Transaction } from "@mysten/sui/transactions";
10
10
  import { ReadonlyWalletAccount, StandardConnect, StandardDisconnect, StandardEvents, SuiSignAndExecuteTransaction, SuiSignPersonalMessage, SuiSignTransaction } from "@mysten/wallet-standard";
11
11
  import { mitt } from "@mysten/utils";
12
12
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mysten/enoki",
3
- "version": "1.3.3",
3
+ "version": "1.4.0",
4
4
  "description": "zkLogin authentication and sponsored transactions",
5
5
  "license": "Apache-2.0",
6
6
  "author": "Mysten Labs <build@mystenlabs.com>",
@@ -51,13 +51,13 @@
51
51
  "idb-keyval": "^6.3.0",
52
52
  "nanostores": "^1.4.2",
53
53
  "@mysten/utils": "^0.4.2",
54
- "@mysten/wallet-standard": "^0.21.37",
55
- "@mysten/webcrypto-signer": "^0.2.37"
54
+ "@mysten/wallet-standard": "^0.21.38",
55
+ "@mysten/webcrypto-signer": "^0.2.38"
56
56
  },
57
57
  "peerDependencies": {
58
58
  "@types/react": ">=17.0.0",
59
59
  "react": ">=17.0.0",
60
- "@mysten/sui": "^2.39.0"
60
+ "@mysten/sui": "^2.39.1"
61
61
  },
62
62
  "peerDependenciesMeta": {
63
63
  "react": {