@account-kit/signer 4.15.3 → 4.16.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.
@@ -1,11 +1,12 @@
1
1
  import { type SmartAccountAuthenticator } from "@aa-sdk/core";
2
2
  import { type GetTransactionType, type Hex, type IsNarrowable, type LocalAccount, type SerializeTransactionFn, type SignableMessage, type TransactionSerializable, type TransactionSerialized, type TypedData, type TypedDataDefinition } from "viem";
3
+ import { type Authorization } from "viem/experimental";
3
4
  import type { BaseSignerClient } from "./client/base";
4
5
  import type { OauthConfig, User } from "./client/types";
5
6
  import { type SessionManagerParams } from "./session/manager.js";
6
7
  import type { AuthParams } from "./signer";
8
+ import { SolanaSigner } from "./solanaSigner.js";
7
9
  import { type AlchemySignerEvents, type ErrorInfo } from "./types.js";
8
- import { type Authorization } from "viem/experimental";
9
10
  export interface BaseAlchemySignerParams<TClient extends BaseSignerClient> {
10
11
  client: TClient;
11
12
  sessionConfig?: Omit<SessionManagerParams, "client">;
@@ -380,6 +381,31 @@ export declare abstract class BaseAlchemySigner<TClient extends BaseSignerClient
380
381
  * @returns {LocalAccount} a LocalAccount object that can be used with viem's wallet client
381
382
  */
382
383
  toViemAccount: () => LocalAccount;
384
+ /**
385
+ * Creates a new instance of `SolanaSigner` using the provided inner value.
386
+ * This requires the signer to be authenticated first
387
+ *
388
+ * @example
389
+ * ```ts
390
+ * import { AlchemyWebSigner } from "@account-kit/signer";
391
+ *
392
+ * const signer = new AlchemyWebSigner({
393
+ * client: {
394
+ * connection: {
395
+ * rpcUrl: "/api/rpc",
396
+ * },
397
+ * iframeConfig: {
398
+ * iframeContainerId: "alchemy-signer-iframe-container",
399
+ * },
400
+ * },
401
+ * });
402
+ *
403
+ * const solanaSigner = signer.toSolanaSigner();
404
+ * ```
405
+ *
406
+ * @returns {SolanaSigner} A new instance of `SolanaSigner`
407
+ */
408
+ experimental_toSolanaSigner: () => SolanaSigner;
383
409
  private authenticateWithEmail;
384
410
  private authenticateWithPasskey;
385
411
  private authenticateWithOauth;
package/dist/esm/base.js CHANGED
@@ -1,14 +1,15 @@
1
1
  import { takeBytes } from "@aa-sdk/core";
2
2
  import { hashMessage, hashTypedData, keccak256, serializeTransaction, } from "viem";
3
3
  import { toAccount } from "viem/accounts";
4
+ import { hashAuthorization } from "viem/experimental";
4
5
  import { subscribeWithSelector } from "zustand/middleware";
5
6
  import { createStore } from "zustand/vanilla";
6
7
  import { NotAuthenticatedError } from "./errors.js";
7
8
  import { SignerLogger } from "./metrics.js";
8
9
  import { SessionManager, } from "./session/manager.js";
10
+ import { SolanaSigner } from "./solanaSigner.js";
9
11
  import { AlchemySignerStatus, } from "./types.js";
10
12
  import { assertNever } from "./utils/typeAssertions.js";
11
- import { hashAuthorization } from "viem/experimental";
12
13
  /**
13
14
  * Base abstract class for Alchemy Signer, providing authentication and session management for smart accounts.
14
15
  * Implements the `SmartAccountAuthenticator` interface and handles various signer events.
@@ -636,6 +637,41 @@ export class BaseAlchemySigner {
636
637
  });
637
638
  }
638
639
  });
640
+ /**
641
+ * Creates a new instance of `SolanaSigner` using the provided inner value.
642
+ * This requires the signer to be authenticated first
643
+ *
644
+ * @example
645
+ * ```ts
646
+ * import { AlchemyWebSigner } from "@account-kit/signer";
647
+ *
648
+ * const signer = new AlchemyWebSigner({
649
+ * client: {
650
+ * connection: {
651
+ * rpcUrl: "/api/rpc",
652
+ * },
653
+ * iframeConfig: {
654
+ * iframeContainerId: "alchemy-signer-iframe-container",
655
+ * },
656
+ * },
657
+ * });
658
+ *
659
+ * const solanaSigner = signer.toSolanaSigner();
660
+ * ```
661
+ *
662
+ * @returns {SolanaSigner} A new instance of `SolanaSigner`
663
+ */
664
+ Object.defineProperty(this, "experimental_toSolanaSigner", {
665
+ enumerable: true,
666
+ configurable: true,
667
+ writable: true,
668
+ value: () => {
669
+ if (!this.inner.getUser()) {
670
+ throw new NotAuthenticatedError();
671
+ }
672
+ return new SolanaSigner(this.inner);
673
+ }
674
+ });
639
675
  Object.defineProperty(this, "authenticateWithEmail", {
640
676
  enumerable: true,
641
677
  configurable: true,
@@ -1 +1 @@
1
- {"version":3,"file":"base.js","sourceRoot":"","sources":["../../src/base.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAkC,MAAM,cAAc,CAAC;AACzE,OAAO,EACL,WAAW,EACX,aAAa,EACb,SAAS,EACT,oBAAoB,GAWrB,MAAM,MAAM,CAAC;AACd,OAAO,EAAE,SAAS,EAAE,MAAM,eAAe,CAAC;AAE1C,OAAO,EAAE,qBAAqB,EAAE,MAAM,oBAAoB,CAAC;AAC3D,OAAO,EAAE,WAAW,EAAE,MAAM,iBAAiB,CAAC;AAG9C,OAAO,EAAE,qBAAqB,EAAE,MAAM,aAAa,CAAC;AACpD,OAAO,EAAE,YAAY,EAAE,MAAM,cAAc,CAAC;AAC5C,OAAO,EACL,cAAc,GAEf,MAAM,sBAAsB,CAAC;AAE9B,OAAO,EACL,mBAAmB,GAIpB,MAAM,YAAY,CAAC;AACpB,OAAO,EAAE,WAAW,EAAE,MAAM,2BAA2B,CAAC;AAExD,OAAO,EAAE,iBAAiB,EAAsB,MAAM,mBAAmB,CAAC;AA2B1E;;;GAGG;AACH,MAAM,OAAgB,iBAAiB;IAQrC;;;;;;;;;OASG;IACH,YAAY,EACV,MAAM,EACN,aAAa,EACb,YAAY,GACqB;QAnBnC;;;;mBAAqD,gBAAgB;WAAC;QACtE;;;;;WAAe;QACP;;;;;WAA+B;QAC/B;;;;;WAAqB;QAyC7B;;;;;;WAMG;QACH;;;;mBAAK,CACH,KAAQ,EACR,QAAgC,EAChC,EAAE;gBACF,+FAA+F;gBAC/F,gGAAgG;gBAChG,0GAA0G;gBAC1G,QAAQ,KAAK,EAAE,CAAC;oBACd,KAAK,WAAW;wBACd,OAAO,IAAI,CAAC,KAAK,CAAC,SAAS,CACzB,CAAC,EAAE,MAAM,EAAE,EAAE,EAAE,CAAC,MAAM,EACtB,CAAC,MAAM,EAAE,EAA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AAC;WAAC;QAEM;;;;mBAAmB,CAAC,SAAmB,EAAE,EAAE;gBACjD,gEAAgE;gBAChE,IAAI,SAAS;oBAAE,IAAI,CAAC,KAAK,CAAC,QAAQ,CAAC,EAAE,SAAS,EAAE,CAAC,CAAC;YACpD,CAAC;WAAC;QAv3BA,IAAI,CAAC,KAAK,GAAG,MAAM,CAAC;QACpB,IAAI,CAAC,KAAK,GAAG,WAAW,CACtB,qBAAqB,CACnB,GAAG,EAAE,CACH,CAAC;YACC,IAAI,EAAE,IAAI;YACV,MAAM,EAAE,mBAAmB,CAAC,YAAY;YACxC,KAAK,EAAE,YAAY,IAAI,IAAI;SACC,CAAC,CAClC,CACF,CAAC;QACF,+DAA+D;QAC/D,oEAAoE;QACpE,2BAA2B;QAC3B,IAAI,CAAC,cAAc,GAAG,IAAI,cAAc,CAAC;YACvC,GAAG,aAAa;YAChB,MAAM,EAAE,IAAI,CAAC,KAAK;SACnB,CAAC,CAAC;QACH,2BAA2B;QAC3B,IAAI,CAAC,iBAAiB,EAAE,CAAC;QACzB,oDAAoD;QACpD,IAAI,CAAC,cAAc,CAAC,UAAU,EAAE,CAAC;IACnC,CAAC;CAk2BF;AAED,SAAS,WAAW,CAAC,KAAc;IACjC,OAAO,KAAK,YAAY,KAAK;QAC3B,CAAC,CAAC,EAAE,IAAI,EAAE,KAAK,CAAC,IAAI,EAAE,OAAO,EAAE,KAAK,CAAC,OAAO,EAAE;QAC9C,CAAC,CAAC,EAAE,IAAI,EAAE,OAAO,EAAE,OAAO,EAAE,eAAe,EAAE,CAAC;AAClD,CAAC","sourcesContent":["import { takeBytes, type SmartAccountAuthenticator } from \"@aa-sdk/core\";\nimport {\n hashMessage,\n hashTypedData,\n keccak256,\n serializeTransaction,\n type GetTransactionType,\n type Hex,\n type IsNarrowable,\n type LocalAccount,\n type SerializeTransactionFn,\n type SignableMessage,\n type TransactionSerializable,\n type TransactionSerialized,\n type TypedData,\n type TypedDataDefinition,\n} from \"viem\";\nimport { toAccount } from \"viem/accounts\";\nimport type { Mutate, StoreApi } from \"zustand\";\nimport { subscribeWithSelector } from \"zustand/middleware\";\nimport { createStore } from \"zustand/vanilla\";\nimport type { BaseSignerClient } from \"./client/base\";\nimport type { OauthConfig, OauthParams, User } from \"./client/types\";\nimport { NotAuthenticatedError } from \"./errors.js\";\nimport { SignerLogger } from \"./metrics.js\";\nimport {\n SessionManager,\n type SessionManagerParams,\n} from \"./session/manager.js\";\nimport type { AuthParams } from \"./signer\";\nimport {\n AlchemySignerStatus,\n type AlchemySignerEvent,\n type AlchemySignerEvents,\n type ErrorInfo,\n} from \"./types.js\";\nimport { assertNever } from \"./utils/typeAssertions.js\";\nimport type { SessionManagerEvents } from \"./session/types\";\nimport { hashAuthorization, type Authorization } from \"viem/experimental\";\n\nexport interface BaseAlchemySignerParams<TClient extends BaseSignerClient> {\n client: TClient;\n sessionConfig?: Omit<SessionManagerParams, \"client\">;\n initialError?: ErrorInfo;\n}\n\ntype AlchemySignerStore = {\n user: User | null;\n status: AlchemySignerStatus;\n error: ErrorInfo | null;\n otpId?: string;\n isNewUser?: boolean;\n};\n\ntype UnpackedSignature = {\n r: `0x${string}`;\n s: `0x${string}`;\n v: bigint;\n};\n\ntype InternalStore = Mutate<\n StoreApi<AlchemySignerStore>,\n [[\"zustand/subscribeWithSelector\", never]]\n>;\n\n/**\n * Base abstract class for Alchemy Signer, providing authentication and session management for smart accounts.\n * Implements the `SmartAccountAuthenticator` interface and handles various signer events.\n */\nexport abstract class BaseAlchemySigner<TClient extends BaseSignerClient>\n implements SmartAccountAuthenticator<AuthParams, User, TClient>\n{\n signerType: \"alchemy-signer\" | \"rn-alchemy-signer\" = \"alchemy-signer\";\n inner: TClient;\n private sessionManager: SessionManager;\n private store: InternalStore;\n\n /**\n * Initializes an instance with the provided client and session configuration.\n * This function sets up the internal store, initializes the session manager,\n * registers listeners and initializes the session manager to manage session state.\n *\n * @param {BaseAlchemySignerParams<TClient>} param0 Object containing the client and session configuration\n * @param {TClient} param0.client The client instance to be used internally\n * @param {SessionConfig} param0.sessionConfig Configuration for managing sessions\n * @param {ErrorInfo | undefined} param0.initialError Error already present on the signer when initialized, if any\n */\n constructor({\n client,\n sessionConfig,\n initialError,\n }: BaseAlchemySignerParams<TClient>) {\n this.inner = client;\n this.store = createStore(\n subscribeWithSelector(\n () =>\n ({\n user: null,\n status: AlchemySignerStatus.INITIALIZING,\n error: initialError ?? null,\n } satisfies AlchemySignerStore)\n )\n );\n // NOTE: it's important that the session manager share a client\n // with the signer. The SessionManager leverages the Signer's client\n // to manage session state.\n this.sessionManager = new SessionManager({\n ...sessionConfig,\n client: this.inner,\n });\n // register listeners first\n this.registerListeners();\n // then initialize so that we can catch those events\n this.sessionManager.initialize();\n }\n\n /**\n * Allows you to subscribe to events emitted by the signer\n *\n * @param {AlchemySignerEvent} event the event to subscribe to\n * @param {AlchemySignerEvents[AlchemySignerEvent]} listener the function to run when the event is emitted\n * @returns {() => void} a function to remove the listener\n */\n on = <E extends AlchemySignerEvent>(\n event: E,\n listener: AlchemySignerEvents[E]\n ) => {\n // NOTE: we're using zustand here to handle this because we are able to use the fireImmediately\n // option which deals with a possible race condition where the listener is added after the event\n // is fired. In the Client and SessionManager we use EventEmitter because it's easier to handle internally\n switch (event) {\n case \"connected\":\n return this.store.subscribe(\n ({ status }) => status,\n (status) =>\n status === AlchemySignerStatus.CONNECTED &&\n (listener as AlchemySignerEvents[\"connected\"])(\n this.store.getState().user!\n ),\n { fireImmediately: true }\n );\n case \"disconnected\":\n return this.store.subscribe(\n ({ status }) => status,\n (status) =>\n status === AlchemySignerStatus.DISCONNECTED &&\n (listener as AlchemySignerEvents[\"disconnected\"])(),\n { fireImmediately: true }\n );\n case \"statusChanged\":\n return this.store.subscribe(\n ({ status }) => status,\n listener as AlchemySignerEvents[\"statusChanged\"],\n { fireImmediately: true }\n );\n case \"errorChanged\":\n return this.store.subscribe(\n ({ error }) => error,\n (error) =>\n (listener as AlchemySignerEvents[\"errorChanged\"])(\n error ?? undefined\n ),\n { fireImmediately: true }\n );\n case \"newUserSignup\":\n return this.store.subscribe(\n ({ isNewUser }) => isNewUser,\n (isNewUser) => {\n if (isNewUser) (listener as AlchemySignerEvents[\"newUserSignup\"])();\n },\n { fireImmediately: true }\n );\n default:\n assertNever(event, `Unknown event type ${event}`);\n }\n };\n\n /**\n * Prepares the config needed to use popup-based OAuth login. This must be\n * called before calling `.authenticate` with params `{ type: \"oauth\", mode:\n * \"popup\" }`, and is recommended to be called on page load.\n *\n * This method exists because browsers may prevent popups from opening unless\n * triggered by user interaction, and so the OAuth config must already have\n * been fetched at the time a user clicks a social login button.\n *\n * @example\n * ```ts\n * import { AlchemyWebSigner } from \"@account-kit/signer\";\n *\n * const signer = new AlchemyWebSigner({\n * client: {\n * connection: {\n * rpcUrl: \"/api/rpc\",\n * },\n * iframeConfig: {\n * iframeContainerId: \"alchemy-signer-iframe-container\",\n * },\n * },\n * });\n *\n * await signer.preparePopupOauth();\n * ```\n * @returns {Promise<OauthConfig>} the config which must be loaded before\n * using popup-based OAuth\n */\n preparePopupOauth = (): Promise<OauthConfig> => this.inner.initOauth();\n\n /**\n * Authenticate a user with either an email or a passkey and create a session for that user\n *\n * @example\n * ```ts\n * import { AlchemyWebSigner } from \"@account-kit/signer\";\n *\n * const signer = new AlchemyWebSigner({\n * client: {\n * connection: {\n * rpcUrl: \"/api/rpc\",\n * },\n * iframeConfig: {\n * iframeContainerId: \"alchemy-signer-iframe-container\",\n * },\n * },\n * });\n *\n * const result = await signer.authenticate({\n * type: \"email\",\n * email: \"foo@mail.com\",\n * });\n * ```\n *\n * @param {AuthParams} params - undefined if passkey login, otherwise an object with email and bundle to resolve\n * @returns {Promise<User>} the user that was authenticated\n */\n authenticate: (params: AuthParams) => Promise<User> = SignerLogger.profiled(\n \"BaseAlchemySigner.authenticate\",\n async (params) => {\n const { type } = params;\n const result = (() => {\n switch (type) {\n case \"email\":\n return this.authenticateWithEmail(params);\n case \"passkey\":\n return this.authenticateWithPasskey(params);\n case \"oauth\":\n return this.authenticateWithOauth(params);\n case \"oauthReturn\":\n return this.handleOauthReturn(params);\n case \"otp\":\n return this.authenticateWithOtp(params);\n default:\n assertNever(type, `Unknown auth type: ${type}`);\n }\n })();\n\n this.trackAuthenticateType(params);\n\n return result.catch((error) => {\n /**\n * 2 things going on here:\n * 1. for oauth flows we expect the status to remain in authenticating\n * 2. we do the ternary, because if we explicitly pass in `undefined` for the status, zustand will set the value of status to `undefined`.\n * However, if we omit it, then it will not override the current value of status.\n */\n this.store.setState({\n error: toErrorInfo(error),\n ...(type === \"oauthReturn\" || type === \"oauth\"\n ? {}\n : { status: AlchemySignerStatus.DISCONNECTED }),\n });\n throw error;\n });\n }\n );\n\n private trackAuthenticateType = (params: AuthParams) => {\n const { type } = params;\n switch (type) {\n case \"email\": {\n // we just want to track the start of email auth\n if (\"bundle\" in params) return;\n SignerLogger.trackEvent({\n name: \"signer_authnticate\",\n data: { authType: \"email\" },\n });\n return;\n }\n case \"passkey\": {\n const isAnon = !(\"email\" in params) && params.createNew == null;\n SignerLogger.trackEvent({\n name: \"signer_authnticate\",\n data: {\n authType: isAnon ? \"passkey_anon\" : \"passkey_email\",\n },\n });\n return;\n }\n case \"oauth\":\n SignerLogger.trackEvent({\n name: \"signer_authnticate\",\n data: {\n authType: \"oauth\",\n provider: params.authProviderId,\n },\n });\n break;\n case \"oauthReturn\":\n break;\n case \"otp\":\n SignerLogger.trackEvent({\n name: \"signer_authnticate\",\n data: { authType: \"otp\" },\n });\n break;\n default:\n assertNever(type, `Unknown auth type: ${type}`);\n }\n };\n\n /**\n * Clear a user session and log them out\n *\n * @example\n * ```ts\n * import { AlchemyWebSigner } from \"@account-kit/signer\";\n *\n * const signer = new AlchemyWebSigner({\n * client: {\n * connection: {\n * rpcUrl: \"/api/rpc\",\n * },\n * iframeConfig: {\n * iframeContainerId: \"alchemy-signer-iframe-container\",\n * },\n * },\n * });\n *\n * await signer.disconnect();\n * ```\n *\n * @returns {Promise<void>} a promise that resolves when the user is logged out\n */\n disconnect: () => Promise<void> = async () => {\n await this.inner.disconnect();\n };\n\n /**\n * Gets the current logged in user\n * If a user has an ongoing session, it will use that session and\n * try to authenticate\n *\n * @example\n * ```ts\n * import { AlchemyWebSigner } from \"@account-kit/signer\";\n *\n * const signer = new AlchemyWebSigner({\n * client: {\n * connection: {\n * rpcUrl: \"/api/rpc\",\n * },\n * iframeConfig: {\n * iframeContainerId: \"alchemy-signer-iframe-container\",\n * },\n * },\n * });\n *\n * // throws if not logged in\n * const user = await signer.getAuthDetails();\n * ```\n *\n * @throws if there is no user logged in\n * @returns {Promise<User>} the current user\n */\n getAuthDetails = async (): Promise<User> => {\n const sessionUser = await this.sessionManager.getSessionUser();\n if (sessionUser != null) {\n return sessionUser;\n }\n\n return this.inner.whoami();\n };\n\n /**\n * Retrieves the address of the current user by calling the `whoami` method on `this.inner`.\n *\n * @returns {Promise<string>} A promise that resolves to the address of the current user.\n */\n getAddress: () => Promise<`0x${string}`> = SignerLogger.profiled(\n \"BaseAlchemySigner.getAddress\",\n async () => {\n const { address } = await this.inner.whoami();\n\n return address;\n }\n );\n\n /**\n * Signs a raw message after hashing it.\n *\n * @example\n * ```ts\n * import { AlchemyWebSigner } from \"@account-kit/signer\";\n *\n * const signer = new AlchemyWebSigner({\n * client: {\n * connection: {\n * rpcUrl: \"/api/rpc\",\n * },\n * iframeConfig: {\n * iframeContainerId: \"alchemy-signer-iframe-container\",\n * },\n * },\n * });\n *\n * const signature = await signer.signMessage(\"Hello, world!\");\n * ```\n *\n * @param {string} msg the message to be hashed and then signed\n * @returns {Promise<string>} a promise that resolves to the signed message\n */\n signMessage: (msg: SignableMessage) => Promise<`0x${string}`> =\n SignerLogger.profiled(\"BaseAlchemySigner.signMessage\", async (msg) => {\n const messageHash = hashMessage(msg);\n\n const result = await this.inner.signRawMessage(messageHash);\n\n SignerLogger.trackEvent({\n name: \"signer_sign_message\",\n });\n\n return result;\n });\n\n /**\n * Signs a typed message by first hashing it and then signing the hashed message using the `signRawMessage` method.\n *\n * @example\n * ```ts\n * import { AlchemyWebSigner } from \"@account-kit/signer\";\n *\n * const signer = new AlchemyWebSigner({\n * client: {\n * connection: {\n * rpcUrl: \"/api/rpc\",\n * },\n * iframeConfig: {\n * iframeContainerId: \"alchemy-signer-iframe-container\",\n * },\n * },\n * });\n *\n * const signature = await signer.signTypedData({\n * domain: {},\n * types: {},\n * primaryType: \"\",\n * message: {},\n * });\n * ```\n *\n * @param {TypedDataDefinition<TTypedData, TPrimaryType>} params The parameters for the typed message to be hashed and signed\n * @returns {Promise<any>} A promise that resolves to the signed message\n */\n signTypedData: <\n const TTypedData extends TypedData | Record<string, unknown>,\n TPrimaryType extends keyof TTypedData | \"EIP712Domain\" = keyof TTypedData\n >(\n params: TypedDataDefinition<TTypedData, TPrimaryType>\n ) => Promise<Hex> = SignerLogger.profiled(\n \"BaseAlchemySigner.signTypedData\",\n async (params) => {\n const messageHash = hashTypedData(params);\n\n return this.inner.signRawMessage(messageHash);\n }\n );\n\n /**\n * Serializes a transaction, signs it with a raw message, and then returns the serialized transaction with the signature.\n *\n * @example\n * ```ts\n * import { AlchemyWebSigner } from \"@account-kit/signer\";\n *\n * const signer = new AlchemyWebSigner({\n * client: {\n * connection: {\n * rpcUrl: \"/api/rpc\",\n * },\n * iframeConfig: {\n * iframeContainerId: \"alchemy-signer-iframe-container\",\n * },\n * },\n * });\n *\n * const tx = await signer.signTransaction({\n * to: \"0x1234\",\n * value: \"0x1234\",\n * data: \"0x1234\",\n * });\n * ```\n *\n * @param {Transaction} tx the transaction to be serialized and signed\n * @param {{serializer?: SerializeTransactionFn}} args options for serialization\n * @param {() => Hex} [args.serializer] an optional serializer function. If not provided, the default `serializeTransaction` function will be used\n * @returns {Promise<string>} a promise that resolves to the serialized transaction with the signature\n */\n signTransaction: <\n serializer extends SerializeTransactionFn<TransactionSerializable> = SerializeTransactionFn<TransactionSerializable>,\n transaction extends Parameters<serializer>[0] = Parameters<serializer>[0]\n >(\n transaction: transaction,\n options?:\n | {\n serializer?: serializer | undefined;\n }\n | undefined\n ) => Promise<\n IsNarrowable<\n TransactionSerialized<GetTransactionType<transaction>>,\n Hex\n > extends true\n ? TransactionSerialized<GetTransactionType<transaction>>\n : Hex\n > = SignerLogger.profiled(\n \"BaseAlchemySigner.signTransaction\",\n async (tx, args) => {\n const serializeFn = args?.serializer ?? serializeTransaction;\n const serializedTx = serializeFn(tx);\n const signatureHex = await this.inner.signRawMessage(\n keccak256(serializedTx)\n );\n\n const signature = this.unpackSignRawMessageBytes(signatureHex);\n\n return serializeFn(tx, signature);\n }\n );\n\n /**\n * Signs an EIP-7702 Authorization and then returns the authorization with the signature.\n *\n * @example\n * ```ts twoslash\n * import { AlchemyWebSigner } from \"@account-kit/signer\";\n *\n * const signer = new AlchemyWebSigner({\n * client: {\n * connection: {\n * rpcUrl: \"/api/rpc\",\n * },\n * iframeConfig: {\n * iframeContainerId: \"alchemy-signer-iframe-container\",\n * },\n * },\n * });\n *\n * const tx = await signer.signAuthorization({\n * contractAddress: \"0x1234123412341234123412341234123412341234\",\n * chainId: 1,\n * nonce: 0,\n * });\n * ```\n *\n * @param {Authorization<number, false>} unsignedAuthorization the authorization to be signed\n * @returns {Promise<Authorization<number, true>> | undefined} a promise that resolves to the authorization with the signature\n */\n signAuthorization: (\n unsignedAuthorization: Authorization<number, false>\n ) => Promise<Authorization<number, true>> = SignerLogger.profiled(\n \"BaseAlchemySigner.signAuthorization\",\n async (unsignedAuthorization) => {\n const hashedAuthorization = hashAuthorization(unsignedAuthorization);\n const signedAuthorizationHex = await this.inner.signRawMessage(\n hashedAuthorization\n );\n const signature = this.unpackSignRawMessageBytes(signedAuthorizationHex);\n return { ...unsignedAuthorization, ...signature };\n }\n );\n\n private unpackSignRawMessageBytes = (\n hex: `0x${string}`\n ): UnpackedSignature => {\n return {\n r: takeBytes(hex, { count: 32 }),\n s: takeBytes(hex, { count: 32, offset: 32 }),\n v: BigInt(takeBytes(hex, { count: 1, offset: 64 })),\n };\n };\n\n /**\n * Unauthenticated call to look up a user's organizationId by email\n *\n * @example\n * ```ts\n * import { AlchemyWebSigner } from \"@account-kit/signer\";\n *\n * const signer = new AlchemyWebSigner({\n * client: {\n * connection: {\n * rpcUrl: \"/api/rpc\",\n * },\n * iframeConfig: {\n * iframeContainerId: \"alchemy-signer-iframe-container\",\n * },\n * },\n * });\n *\n * const result = await signer.getUser(\"foo@mail.com\");\n * ```\n *\n * @param {string} email the email to lookup\n * @returns {Promise<{orgId: string}>} the organization id for the user if they exist\n */\n getUser: (email: string) => Promise<{ orgId: string } | null> =\n SignerLogger.profiled(\"BaseAlchemySigner.getUser\", async (email) => {\n const result = await this.inner.lookupUserByEmail(email);\n\n if (result.orgId == null) {\n return null;\n }\n\n return {\n orgId: result.orgId,\n };\n });\n\n /**\n * Adds a passkey to the user's account\n *\n * @example\n * ```ts\n * import { AlchemyWebSigner } from \"@account-kit/signer\";\n *\n * const signer = new AlchemyWebSigner({\n * client: {\n * connection: {\n * rpcUrl: \"/api/rpc\",\n * },\n * iframeConfig: {\n * iframeContainerId: \"alchemy-signer-iframe-container\",\n * },\n * },\n * });\n *\n * const result = await signer.addPasskey()\n * ```\n *\n * @param {CredentialCreationOptions | undefined} params optional parameters for the passkey creation\n * @returns {Promise<string[]>} an array of the authenticator ids added to the user\n */\n addPasskey: (params?: CredentialCreationOptions) => Promise<string[]> =\n SignerLogger.profiled(\"BaseAlchemySigner.addPasskey\", async (params) => {\n return this.inner.addPasskey(params ?? {});\n });\n\n /**\n * Used to export the wallet for a given user\n * If the user is authenticated with an Email, this will return a seed phrase\n * If the user is authenticated with a Passkey, this will return a private key\n *\n * @example\n * ```ts\n * import { AlchemyWebSigner } from \"@account-kit/signer\";\n *\n * const signer = new AlchemyWebSigner({\n * client: {\n * connection: {\n * rpcUrl: \"/api/rpc\",\n * },\n * iframeConfig: {\n * iframeContainerId: \"alchemy-signer-iframe-container\",\n * },\n * },\n * });\n *\n * // the params passed to this are different based on the specific signer\n * const result = signer.exportWallet()\n * ```\n *\n * @param {unknown} params export wallet parameters\n * @returns {boolean} true if the wallet was exported successfully\n */\n exportWallet: (\n params: Parameters<(typeof this.inner)[\"exportWallet\"]>[0]\n ) => Promise<boolean> = async (params) => {\n return this.inner.exportWallet(params);\n };\n\n /**\n * This method lets you adapt your AlchemySigner to a viem LocalAccount, which\n * will let you use the signer as an EOA directly.\n *\n * @example\n * ```ts\n * import { AlchemyWebSigner } from \"@account-kit/signer\";\n *\n * const signer = new AlchemyWebSigner({\n * client: {\n * connection: {\n * rpcUrl: \"/api/rpc\",\n * },\n * iframeConfig: {\n * iframeContainerId: \"alchemy-signer-iframe-container\",\n * },\n * },\n * });\n *\n * const account = signer.toViemAccount();\n * ```\n *\n * @throws if your signer is not authenticated\n * @returns {LocalAccount} a LocalAccount object that can be used with viem's wallet client\n */\n toViemAccount = (): LocalAccount => {\n // if we want this method to be synchronous, then we need to do this check here\n // otherwise we can use the sessionManager to get the user\n if (!this.inner.getUser()) {\n throw new NotAuthenticatedError();\n }\n\n return toAccount({\n address: this.inner.getUser()!.address,\n signMessage: (msg) => this.signMessage(msg.message),\n signTypedData: <\n const typedData extends TypedData | Record<string, unknown>,\n primaryType extends keyof typedData | \"EIP712Domain\" = keyof typedData\n >(\n typedDataDefinition: TypedDataDefinition<typedData, primaryType>\n ) => this.signTypedData<typedData, primaryType>(typedDataDefinition),\n signTransaction: this.signTransaction,\n });\n };\n\n private authenticateWithEmail = async (\n params: Extract<AuthParams, { type: \"email\" }>\n ): Promise<User> => {\n if (\"email\" in params) {\n const existingUser = await this.getUser(params.email);\n const expirationSeconds = this.getExpirationSeconds();\n\n const { orgId, otpId } = existingUser\n ? await this.inner.initEmailAuth({\n email: params.email,\n emailMode: params.emailMode,\n expirationSeconds,\n redirectParams: params.redirectParams,\n })\n : await this.inner.createAccount({\n type: \"email\",\n email: params.email,\n emailMode: params.emailMode,\n expirationSeconds,\n redirectParams: params.redirectParams,\n });\n\n this.sessionManager.setTemporarySession({\n orgId,\n isNewUser: !existingUser,\n });\n this.store.setState({\n status: AlchemySignerStatus.AWAITING_EMAIL_AUTH,\n otpId,\n error: null,\n });\n\n // We wait for the session manager to emit a connected event if\n // cross tab sessions are permitted\n return new Promise<User>((resolve) => {\n const removeListener = this.sessionManager.on(\n \"connected\",\n (session) => {\n resolve(session.user);\n removeListener();\n }\n );\n });\n } else {\n const temporarySession = params.orgId\n ? { orgId: params.orgId }\n : this.sessionManager.getTemporarySession();\n\n if (!temporarySession) {\n this.store.setState({\n status: AlchemySignerStatus.DISCONNECTED,\n });\n throw new Error(\"Could not find email auth init session!\");\n }\n\n const user = await this.inner.completeAuthWithBundle({\n bundle: params.bundle,\n orgId: temporarySession.orgId,\n connectedEventName: \"connectedEmail\",\n authenticatingType: \"email\",\n });\n\n // fire new user event\n this.emitNewUserEvent(params.isNewUser);\n\n return user;\n }\n };\n\n private authenticateWithPasskey = async (\n args: Extract<AuthParams, { type: \"passkey\" }>\n ): Promise<User> => {\n let user: User;\n const shouldCreateNew = async () => {\n if (\"email\" in args) {\n const existingUser = await this.getUser(args.email);\n return existingUser == null;\n }\n\n return args.createNew;\n };\n\n if (await shouldCreateNew()) {\n const result = await this.inner.createAccount(\n args as Extract<\n AuthParams,\n { type: \"passkey\" } & ({ email: string } | { createNew: true })\n >\n );\n // account creation for passkeys returns the whoami response so we don't have to\n // call it again after signup\n user = {\n address: result.address!,\n userId: result.userId!,\n orgId: result.orgId,\n };\n } else {\n user = await this.inner.lookupUserWithPasskey();\n if (!user) {\n this.store.setState({\n status: AlchemySignerStatus.DISCONNECTED,\n });\n throw new Error(\"No user found\");\n }\n }\n\n return user;\n };\n\n private authenticateWithOauth = async (\n args: Extract<AuthParams, { type: \"oauth\" }>\n ): Promise<User> => {\n const params: OauthParams = {\n ...args,\n expirationSeconds: this.getExpirationSeconds(),\n };\n if (params.mode === \"redirect\") {\n return this.inner.oauthWithRedirect(params);\n } else {\n return this.inner.oauthWithPopup(params);\n }\n };\n\n private authenticateWithOtp = async (\n args: Extract<AuthParams, { type: \"otp\" }>\n ): Promise<User> => {\n const tempSession = this.sessionManager.getTemporarySession();\n const { orgId, isNewUser } = tempSession ?? {};\n const { otpId } = this.store.getState();\n if (!orgId) {\n throw new Error(\"orgId not found in session\");\n }\n if (!otpId) {\n throw new Error(\"otpId not found in session\");\n }\n const { bundle } = await this.inner.submitOtpCode({\n orgId,\n otpId,\n otpCode: args.otpCode,\n expirationSeconds: this.getExpirationSeconds(),\n });\n const user = await this.inner.completeAuthWithBundle({\n bundle,\n orgId,\n connectedEventName: \"connectedOtp\",\n authenticatingType: \"otp\",\n });\n\n this.emitNewUserEvent(isNewUser);\n if (tempSession) {\n this.sessionManager.setTemporarySession({\n ...tempSession,\n isNewUser: false,\n });\n }\n\n return user;\n };\n\n private handleOauthReturn = ({\n bundle,\n orgId,\n idToken,\n isNewUser,\n }: Extract<AuthParams, { type: \"oauthReturn\" }>): Promise<User> => {\n const user = this.inner.completeAuthWithBundle({\n bundle,\n orgId,\n connectedEventName: \"connectedOauth\",\n authenticatingType: \"oauth\",\n idToken,\n });\n\n this.emitNewUserEvent(isNewUser);\n\n return user;\n };\n\n private getExpirationSeconds = () =>\n Math.floor(this.sessionManager.expirationTimeMs / 1000);\n\n private registerListeners = () => {\n // Declare listeners in an object to typecheck that every event type is\n // handled.\n const listeners: SessionManagerEvents = {\n connected: (session) => {\n this.store.setState({\n user: session.user,\n status: AlchemySignerStatus.CONNECTED,\n error: null,\n });\n },\n disconnected: () => {\n this.store.setState({\n user: null,\n status: AlchemySignerStatus.DISCONNECTED,\n });\n },\n initialized: () => {\n this.store.setState((state) => ({\n status: state.user\n ? AlchemySignerStatus.CONNECTED\n : AlchemySignerStatus.DISCONNECTED,\n ...(state.user ? { error: null } : undefined),\n }));\n },\n };\n\n for (const [event, listener] of Object.entries(listeners)) {\n this.sessionManager.on(event as keyof SessionManagerEvents, listener);\n }\n\n this.inner.on(\"authenticating\", ({ type }) => {\n const status = (() => {\n switch (type) {\n case \"email\":\n return AlchemySignerStatus.AUTHENTICATING_EMAIL;\n case \"passkey\":\n return AlchemySignerStatus.AUTHENTICATING_PASSKEY;\n case \"oauth\":\n return AlchemySignerStatus.AUTHENTICATING_OAUTH;\n case \"otp\":\n case \"otpVerify\":\n return AlchemySignerStatus.AWAITING_OTP_AUTH;\n default:\n assertNever(type, \"unhandled authenticating type\");\n }\n })();\n\n // trigger new user event on signer from client\n this.inner.on(\"newUserSignup\", () => {\n this.emitNewUserEvent(true);\n });\n\n this.store.setState({\n status,\n error: null,\n });\n });\n };\n\n private emitNewUserEvent = (isNewUser?: boolean) => {\n // assumes that if isNewUser is undefined it is a returning user\n if (isNewUser) this.store.setState({ isNewUser });\n };\n}\n\nfunction toErrorInfo(error: unknown): ErrorInfo {\n return error instanceof Error\n ? { name: error.name, message: error.message }\n : { name: \"Error\", message: \"Unknown error\" };\n}\n"]}
1
+ {"version":3,"file":"base.js","sourceRoot":"","sources":["../../src/base.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAkC,MAAM,cAAc,CAAC;AACzE,OAAO,EACL,WAAW,EACX,aAAa,EACb,SAAS,EACT,oBAAoB,GAWrB,MAAM,MAAM,CAAC;AACd,OAAO,EAAE,SAAS,EAAE,MAAM,eAAe,CAAC;AAC1C,OAAO,EAAE,iBAAiB,EAAsB,MAAM,mBAAmB,CAAC;AAE1E,OAAO,EAAE,qBAAqB,EAAE,MAAM,oBAAoB,CAAC;AAC3D,OAAO,EAAE,WAAW,EAAE,MAAM,iBAAiB,CAAC;AAG9C,OAAO,EAAE,qBAAqB,EAAE,MAAM,aAAa,CAAC;AACpD,OAAO,EAAE,YAAY,EAAE,MAAM,cAAc,CAAC;AAC5C,OAAO,EACL,cAAc,GAEf,MAAM,sBAAsB,CAAC;AAG9B,OAAO,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAC;AACjD,OAAO,EACL,mBAAmB,GAIpB,MAAM,YAAY,CAAC;AACpB,OAAO,EAAE,WAAW,EA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D;QAC/D,oEAAoE;QACpE,2BAA2B;QAC3B,IAAI,CAAC,cAAc,GAAG,IAAI,cAAc,CAAC;YACvC,GAAG,aAAa;YAChB,MAAM,EAAE,IAAI,CAAC,KAAK;SACnB,CAAC,CAAC;QACH,2BAA2B;QAC3B,IAAI,CAAC,iBAAiB,EAAE,CAAC;QACzB,oDAAoD;QACpD,IAAI,CAAC,cAAc,CAAC,UAAU,EAAE,CAAC;IACnC,CAAC;CAk4BF;AAED,SAAS,WAAW,CAAC,KAAc;IACjC,OAAO,KAAK,YAAY,KAAK;QAC3B,CAAC,CAAC,EAAE,IAAI,EAAE,KAAK,CAAC,IAAI,EAAE,OAAO,EAAE,KAAK,CAAC,OAAO,EAAE;QAC9C,CAAC,CAAC,EAAE,IAAI,EAAE,OAAO,EAAE,OAAO,EAAE,eAAe,EAAE,CAAC;AAClD,CAAC","sourcesContent":["import { takeBytes, type SmartAccountAuthenticator } from \"@aa-sdk/core\";\nimport {\n hashMessage,\n hashTypedData,\n keccak256,\n serializeTransaction,\n type GetTransactionType,\n type Hex,\n type IsNarrowable,\n type LocalAccount,\n type SerializeTransactionFn,\n type SignableMessage,\n type TransactionSerializable,\n type TransactionSerialized,\n type TypedData,\n type TypedDataDefinition,\n} from \"viem\";\nimport { toAccount } from \"viem/accounts\";\nimport { hashAuthorization, type Authorization } from \"viem/experimental\";\nimport type { Mutate, StoreApi } from \"zustand\";\nimport { subscribeWithSelector } from \"zustand/middleware\";\nimport { createStore } from \"zustand/vanilla\";\nimport type { BaseSignerClient } from \"./client/base\";\nimport type { OauthConfig, OauthParams, User } from \"./client/types\";\nimport { NotAuthenticatedError } from \"./errors.js\";\nimport { SignerLogger } from \"./metrics.js\";\nimport {\n SessionManager,\n type SessionManagerParams,\n} from \"./session/manager.js\";\nimport type { SessionManagerEvents } from \"./session/types\";\nimport type { AuthParams } from \"./signer\";\nimport { SolanaSigner } from \"./solanaSigner.js\";\nimport {\n AlchemySignerStatus,\n type AlchemySignerEvent,\n type AlchemySignerEvents,\n type ErrorInfo,\n} from \"./types.js\";\nimport { assertNever } from \"./utils/typeAssertions.js\";\n\nexport interface BaseAlchemySignerParams<TClient extends BaseSignerClient> {\n client: TClient;\n sessionConfig?: Omit<SessionManagerParams, \"client\">;\n initialError?: ErrorInfo;\n}\n\ntype AlchemySignerStore = {\n user: User | null;\n status: AlchemySignerStatus;\n error: ErrorInfo | null;\n otpId?: string;\n isNewUser?: boolean;\n};\n\ntype UnpackedSignature = {\n r: `0x${string}`;\n s: `0x${string}`;\n v: bigint;\n};\n\ntype InternalStore = Mutate<\n StoreApi<AlchemySignerStore>,\n [[\"zustand/subscribeWithSelector\", never]]\n>;\n\n/**\n * Base abstract class for Alchemy Signer, providing authentication and session management for smart accounts.\n * Implements the `SmartAccountAuthenticator` interface and handles various signer events.\n */\nexport abstract class BaseAlchemySigner<TClient extends BaseSignerClient>\n implements SmartAccountAuthenticator<AuthParams, User, TClient>\n{\n signerType: \"alchemy-signer\" | \"rn-alchemy-signer\" = \"alchemy-signer\";\n inner: TClient;\n private sessionManager: SessionManager;\n private store: InternalStore;\n\n /**\n * Initializes an instance with the provided client and session configuration.\n * This function sets up the internal store, initializes the session manager,\n * registers listeners and initializes the session manager to manage session state.\n *\n * @param {BaseAlchemySignerParams<TClient>} param0 Object containing the client and session configuration\n * @param {TClient} param0.client The client instance to be used internally\n * @param {SessionConfig} param0.sessionConfig Configuration for managing sessions\n * @param {ErrorInfo | undefined} param0.initialError Error already present on the signer when initialized, if any\n */\n constructor({\n client,\n sessionConfig,\n initialError,\n }: BaseAlchemySignerParams<TClient>) {\n this.inner = client;\n this.store = createStore(\n subscribeWithSelector(\n () =>\n ({\n user: null,\n status: AlchemySignerStatus.INITIALIZING,\n error: initialError ?? null,\n } satisfies AlchemySignerStore)\n )\n );\n // NOTE: it's important that the session manager share a client\n // with the signer. The SessionManager leverages the Signer's client\n // to manage session state.\n this.sessionManager = new SessionManager({\n ...sessionConfig,\n client: this.inner,\n });\n // register listeners first\n this.registerListeners();\n // then initialize so that we can catch those events\n this.sessionManager.initialize();\n }\n\n /**\n * Allows you to subscribe to events emitted by the signer\n *\n * @param {AlchemySignerEvent} event the event to subscribe to\n * @param {AlchemySignerEvents[AlchemySignerEvent]} listener the function to run when the event is emitted\n * @returns {() => void} a function to remove the listener\n */\n on = <E extends AlchemySignerEvent>(\n event: E,\n listener: AlchemySignerEvents[E]\n ) => {\n // NOTE: we're using zustand here to handle this because we are able to use the fireImmediately\n // option which deals with a possible race condition where the listener is added after the event\n // is fired. In the Client and SessionManager we use EventEmitter because it's easier to handle internally\n switch (event) {\n case \"connected\":\n return this.store.subscribe(\n ({ status }) => status,\n (status) =>\n status === AlchemySignerStatus.CONNECTED &&\n (listener as AlchemySignerEvents[\"connected\"])(\n this.store.getState().user!\n ),\n { fireImmediately: true }\n );\n case \"disconnected\":\n return this.store.subscribe(\n ({ status }) => status,\n (status) =>\n status === AlchemySignerStatus.DISCONNECTED &&\n (listener as AlchemySignerEvents[\"disconnected\"])(),\n { fireImmediately: true }\n );\n case \"statusChanged\":\n return this.store.subscribe(\n ({ status }) => status,\n listener as AlchemySignerEvents[\"statusChanged\"],\n { fireImmediately: true }\n );\n case \"errorChanged\":\n return this.store.subscribe(\n ({ error }) => error,\n (error) =>\n (listener as AlchemySignerEvents[\"errorChanged\"])(\n error ?? undefined\n ),\n { fireImmediately: true }\n );\n case \"newUserSignup\":\n return this.store.subscribe(\n ({ isNewUser }) => isNewUser,\n (isNewUser) => {\n if (isNewUser) (listener as AlchemySignerEvents[\"newUserSignup\"])();\n },\n { fireImmediately: true }\n );\n default:\n assertNever(event, `Unknown event type ${event}`);\n }\n };\n\n /**\n * Prepares the config needed to use popup-based OAuth login. This must be\n * called before calling `.authenticate` with params `{ type: \"oauth\", mode:\n * \"popup\" }`, and is recommended to be called on page load.\n *\n * This method exists because browsers may prevent popups from opening unless\n * triggered by user interaction, and so the OAuth config must already have\n * been fetched at the time a user clicks a social login button.\n *\n * @example\n * ```ts\n * import { AlchemyWebSigner } from \"@account-kit/signer\";\n *\n * const signer = new AlchemyWebSigner({\n * client: {\n * connection: {\n * rpcUrl: \"/api/rpc\",\n * },\n * iframeConfig: {\n * iframeContainerId: \"alchemy-signer-iframe-container\",\n * },\n * },\n * });\n *\n * await signer.preparePopupOauth();\n * ```\n * @returns {Promise<OauthConfig>} the config which must be loaded before\n * using popup-based OAuth\n */\n preparePopupOauth = (): Promise<OauthConfig> => this.inner.initOauth();\n\n /**\n * Authenticate a user with either an email or a passkey and create a session for that user\n *\n * @example\n * ```ts\n * import { AlchemyWebSigner } from \"@account-kit/signer\";\n *\n * const signer = new AlchemyWebSigner({\n * client: {\n * connection: {\n * rpcUrl: \"/api/rpc\",\n * },\n * iframeConfig: {\n * iframeContainerId: \"alchemy-signer-iframe-container\",\n * },\n * },\n * });\n *\n * const result = await signer.authenticate({\n * type: \"email\",\n * email: \"foo@mail.com\",\n * });\n * ```\n *\n * @param {AuthParams} params - undefined if passkey login, otherwise an object with email and bundle to resolve\n * @returns {Promise<User>} the user that was authenticated\n */\n authenticate: (params: AuthParams) => Promise<User> = SignerLogger.profiled(\n \"BaseAlchemySigner.authenticate\",\n async (params) => {\n const { type } = params;\n const result = (() => {\n switch (type) {\n case \"email\":\n return this.authenticateWithEmail(params);\n case \"passkey\":\n return this.authenticateWithPasskey(params);\n case \"oauth\":\n return this.authenticateWithOauth(params);\n case \"oauthReturn\":\n return this.handleOauthReturn(params);\n case \"otp\":\n return this.authenticateWithOtp(params);\n default:\n assertNever(type, `Unknown auth type: ${type}`);\n }\n })();\n\n this.trackAuthenticateType(params);\n\n return result.catch((error) => {\n /**\n * 2 things going on here:\n * 1. for oauth flows we expect the status to remain in authenticating\n * 2. we do the ternary, because if we explicitly pass in `undefined` for the status, zustand will set the value of status to `undefined`.\n * However, if we omit it, then it will not override the current value of status.\n */\n this.store.setState({\n error: toErrorInfo(error),\n ...(type === \"oauthReturn\" || type === \"oauth\"\n ? {}\n : { status: AlchemySignerStatus.DISCONNECTED }),\n });\n throw error;\n });\n }\n );\n\n private trackAuthenticateType = (params: AuthParams) => {\n const { type } = params;\n switch (type) {\n case \"email\": {\n // we just want to track the start of email auth\n if (\"bundle\" in params) return;\n SignerLogger.trackEvent({\n name: \"signer_authnticate\",\n data: { authType: \"email\" },\n });\n return;\n }\n case \"passkey\": {\n const isAnon = !(\"email\" in params) && params.createNew == null;\n SignerLogger.trackEvent({\n name: \"signer_authnticate\",\n data: {\n authType: isAnon ? \"passkey_anon\" : \"passkey_email\",\n },\n });\n return;\n }\n case \"oauth\":\n SignerLogger.trackEvent({\n name: \"signer_authnticate\",\n data: {\n authType: \"oauth\",\n provider: params.authProviderId,\n },\n });\n break;\n case \"oauthReturn\":\n break;\n case \"otp\":\n SignerLogger.trackEvent({\n name: \"signer_authnticate\",\n data: { authType: \"otp\" },\n });\n break;\n default:\n assertNever(type, `Unknown auth type: ${type}`);\n }\n };\n\n /**\n * Clear a user session and log them out\n *\n * @example\n * ```ts\n * import { AlchemyWebSigner } from \"@account-kit/signer\";\n *\n * const signer = new AlchemyWebSigner({\n * client: {\n * connection: {\n * rpcUrl: \"/api/rpc\",\n * },\n * iframeConfig: {\n * iframeContainerId: \"alchemy-signer-iframe-container\",\n * },\n * },\n * });\n *\n * await signer.disconnect();\n * ```\n *\n * @returns {Promise<void>} a promise that resolves when the user is logged out\n */\n disconnect: () => Promise<void> = async () => {\n await this.inner.disconnect();\n };\n\n /**\n * Gets the current logged in user\n * If a user has an ongoing session, it will use that session and\n * try to authenticate\n *\n * @example\n * ```ts\n * import { AlchemyWebSigner } from \"@account-kit/signer\";\n *\n * const signer = new AlchemyWebSigner({\n * client: {\n * connection: {\n * rpcUrl: \"/api/rpc\",\n * },\n * iframeConfig: {\n * iframeContainerId: \"alchemy-signer-iframe-container\",\n * },\n * },\n * });\n *\n * // throws if not logged in\n * const user = await signer.getAuthDetails();\n * ```\n *\n * @throws if there is no user logged in\n * @returns {Promise<User>} the current user\n */\n getAuthDetails = async (): Promise<User> => {\n const sessionUser = await this.sessionManager.getSessionUser();\n if (sessionUser != null) {\n return sessionUser;\n }\n\n return this.inner.whoami();\n };\n\n /**\n * Retrieves the address of the current user by calling the `whoami` method on `this.inner`.\n *\n * @returns {Promise<string>} A promise that resolves to the address of the current user.\n */\n getAddress: () => Promise<`0x${string}`> = SignerLogger.profiled(\n \"BaseAlchemySigner.getAddress\",\n async () => {\n const { address } = await this.inner.whoami();\n\n return address;\n }\n );\n\n /**\n * Signs a raw message after hashing it.\n *\n * @example\n * ```ts\n * import { AlchemyWebSigner } from \"@account-kit/signer\";\n *\n * const signer = new AlchemyWebSigner({\n * client: {\n * connection: {\n * rpcUrl: \"/api/rpc\",\n * },\n * iframeConfig: {\n * iframeContainerId: \"alchemy-signer-iframe-container\",\n * },\n * },\n * });\n *\n * const signature = await signer.signMessage(\"Hello, world!\");\n * ```\n *\n * @param {string} msg the message to be hashed and then signed\n * @returns {Promise<string>} a promise that resolves to the signed message\n */\n signMessage: (msg: SignableMessage) => Promise<`0x${string}`> =\n SignerLogger.profiled(\"BaseAlchemySigner.signMessage\", async (msg) => {\n const messageHash = hashMessage(msg);\n\n const result = await this.inner.signRawMessage(messageHash);\n\n SignerLogger.trackEvent({\n name: \"signer_sign_message\",\n });\n\n return result;\n });\n\n /**\n * Signs a typed message by first hashing it and then signing the hashed message using the `signRawMessage` method.\n *\n * @example\n * ```ts\n * import { AlchemyWebSigner } from \"@account-kit/signer\";\n *\n * const signer = new AlchemyWebSigner({\n * client: {\n * connection: {\n * rpcUrl: \"/api/rpc\",\n * },\n * iframeConfig: {\n * iframeContainerId: \"alchemy-signer-iframe-container\",\n * },\n * },\n * });\n *\n * const signature = await signer.signTypedData({\n * domain: {},\n * types: {},\n * primaryType: \"\",\n * message: {},\n * });\n * ```\n *\n * @param {TypedDataDefinition<TTypedData, TPrimaryType>} params The parameters for the typed message to be hashed and signed\n * @returns {Promise<any>} A promise that resolves to the signed message\n */\n signTypedData: <\n const TTypedData extends TypedData | Record<string, unknown>,\n TPrimaryType extends keyof TTypedData | \"EIP712Domain\" = keyof TTypedData\n >(\n params: TypedDataDefinition<TTypedData, TPrimaryType>\n ) => Promise<Hex> = SignerLogger.profiled(\n \"BaseAlchemySigner.signTypedData\",\n async (params) => {\n const messageHash = hashTypedData(params);\n\n return this.inner.signRawMessage(messageHash);\n }\n );\n\n /**\n * Serializes a transaction, signs it with a raw message, and then returns the serialized transaction with the signature.\n *\n * @example\n * ```ts\n * import { AlchemyWebSigner } from \"@account-kit/signer\";\n *\n * const signer = new AlchemyWebSigner({\n * client: {\n * connection: {\n * rpcUrl: \"/api/rpc\",\n * },\n * iframeConfig: {\n * iframeContainerId: \"alchemy-signer-iframe-container\",\n * },\n * },\n * });\n *\n * const tx = await signer.signTransaction({\n * to: \"0x1234\",\n * value: \"0x1234\",\n * data: \"0x1234\",\n * });\n * ```\n *\n * @param {Transaction} tx the transaction to be serialized and signed\n * @param {{serializer?: SerializeTransactionFn}} args options for serialization\n * @param {() => Hex} [args.serializer] an optional serializer function. If not provided, the default `serializeTransaction` function will be used\n * @returns {Promise<string>} a promise that resolves to the serialized transaction with the signature\n */\n signTransaction: <\n serializer extends SerializeTransactionFn<TransactionSerializable> = SerializeTransactionFn<TransactionSerializable>,\n transaction extends Parameters<serializer>[0] = Parameters<serializer>[0]\n >(\n transaction: transaction,\n options?:\n | {\n serializer?: serializer | undefined;\n }\n | undefined\n ) => Promise<\n IsNarrowable<\n TransactionSerialized<GetTransactionType<transaction>>,\n Hex\n > extends true\n ? TransactionSerialized<GetTransactionType<transaction>>\n : Hex\n > = SignerLogger.profiled(\n \"BaseAlchemySigner.signTransaction\",\n async (tx, args) => {\n const serializeFn = args?.serializer ?? serializeTransaction;\n const serializedTx = serializeFn(tx);\n const signatureHex = await this.inner.signRawMessage(\n keccak256(serializedTx)\n );\n\n const signature = this.unpackSignRawMessageBytes(signatureHex);\n\n return serializeFn(tx, signature);\n }\n );\n\n /**\n * Signs an EIP-7702 Authorization and then returns the authorization with the signature.\n *\n * @example\n * ```ts twoslash\n * import { AlchemyWebSigner } from \"@account-kit/signer\";\n *\n * const signer = new AlchemyWebSigner({\n * client: {\n * connection: {\n * rpcUrl: \"/api/rpc\",\n * },\n * iframeConfig: {\n * iframeContainerId: \"alchemy-signer-iframe-container\",\n * },\n * },\n * });\n *\n * const tx = await signer.signAuthorization({\n * contractAddress: \"0x1234123412341234123412341234123412341234\",\n * chainId: 1,\n * nonce: 0,\n * });\n * ```\n *\n * @param {Authorization<number, false>} unsignedAuthorization the authorization to be signed\n * @returns {Promise<Authorization<number, true>> | undefined} a promise that resolves to the authorization with the signature\n */\n signAuthorization: (\n unsignedAuthorization: Authorization<number, false>\n ) => Promise<Authorization<number, true>> = SignerLogger.profiled(\n \"BaseAlchemySigner.signAuthorization\",\n async (unsignedAuthorization) => {\n const hashedAuthorization = hashAuthorization(unsignedAuthorization);\n const signedAuthorizationHex = await this.inner.signRawMessage(\n hashedAuthorization\n );\n const signature = this.unpackSignRawMessageBytes(signedAuthorizationHex);\n return { ...unsignedAuthorization, ...signature };\n }\n );\n\n private unpackSignRawMessageBytes = (\n hex: `0x${string}`\n ): UnpackedSignature => {\n return {\n r: takeBytes(hex, { count: 32 }),\n s: takeBytes(hex, { count: 32, offset: 32 }),\n v: BigInt(takeBytes(hex, { count: 1, offset: 64 })),\n };\n };\n\n /**\n * Unauthenticated call to look up a user's organizationId by email\n *\n * @example\n * ```ts\n * import { AlchemyWebSigner } from \"@account-kit/signer\";\n *\n * const signer = new AlchemyWebSigner({\n * client: {\n * connection: {\n * rpcUrl: \"/api/rpc\",\n * },\n * iframeConfig: {\n * iframeContainerId: \"alchemy-signer-iframe-container\",\n * },\n * },\n * });\n *\n * const result = await signer.getUser(\"foo@mail.com\");\n * ```\n *\n * @param {string} email the email to lookup\n * @returns {Promise<{orgId: string}>} the organization id for the user if they exist\n */\n getUser: (email: string) => Promise<{ orgId: string } | null> =\n SignerLogger.profiled(\"BaseAlchemySigner.getUser\", async (email) => {\n const result = await this.inner.lookupUserByEmail(email);\n\n if (result.orgId == null) {\n return null;\n }\n\n return {\n orgId: result.orgId,\n };\n });\n\n /**\n * Adds a passkey to the user's account\n *\n * @example\n * ```ts\n * import { AlchemyWebSigner } from \"@account-kit/signer\";\n *\n * const signer = new AlchemyWebSigner({\n * client: {\n * connection: {\n * rpcUrl: \"/api/rpc\",\n * },\n * iframeConfig: {\n * iframeContainerId: \"alchemy-signer-iframe-container\",\n * },\n * },\n * });\n *\n * const result = await signer.addPasskey()\n * ```\n *\n * @param {CredentialCreationOptions | undefined} params optional parameters for the passkey creation\n * @returns {Promise<string[]>} an array of the authenticator ids added to the user\n */\n addPasskey: (params?: CredentialCreationOptions) => Promise<string[]> =\n SignerLogger.profiled(\"BaseAlchemySigner.addPasskey\", async (params) => {\n return this.inner.addPasskey(params ?? {});\n });\n\n /**\n * Used to export the wallet for a given user\n * If the user is authenticated with an Email, this will return a seed phrase\n * If the user is authenticated with a Passkey, this will return a private key\n *\n * @example\n * ```ts\n * import { AlchemyWebSigner } from \"@account-kit/signer\";\n *\n * const signer = new AlchemyWebSigner({\n * client: {\n * connection: {\n * rpcUrl: \"/api/rpc\",\n * },\n * iframeConfig: {\n * iframeContainerId: \"alchemy-signer-iframe-container\",\n * },\n * },\n * });\n *\n * // the params passed to this are different based on the specific signer\n * const result = signer.exportWallet()\n * ```\n *\n * @param {unknown} params export wallet parameters\n * @returns {boolean} true if the wallet was exported successfully\n */\n exportWallet: (\n params: Parameters<(typeof this.inner)[\"exportWallet\"]>[0]\n ) => Promise<boolean> = async (params) => {\n return this.inner.exportWallet(params);\n };\n\n /**\n * This method lets you adapt your AlchemySigner to a viem LocalAccount, which\n * will let you use the signer as an EOA directly.\n *\n * @example\n * ```ts\n * import { AlchemyWebSigner } from \"@account-kit/signer\";\n *\n * const signer = new AlchemyWebSigner({\n * client: {\n * connection: {\n * rpcUrl: \"/api/rpc\",\n * },\n * iframeConfig: {\n * iframeContainerId: \"alchemy-signer-iframe-container\",\n * },\n * },\n * });\n *\n * const account = signer.toViemAccount();\n * ```\n *\n * @throws if your signer is not authenticated\n * @returns {LocalAccount} a LocalAccount object that can be used with viem's wallet client\n */\n toViemAccount = (): LocalAccount => {\n // if we want this method to be synchronous, then we need to do this check here\n // otherwise we can use the sessionManager to get the user\n if (!this.inner.getUser()) {\n throw new NotAuthenticatedError();\n }\n\n return toAccount({\n address: this.inner.getUser()!.address,\n signMessage: (msg) => this.signMessage(msg.message),\n signTypedData: <\n const typedData extends TypedData | Record<string, unknown>,\n primaryType extends keyof typedData | \"EIP712Domain\" = keyof typedData\n >(\n typedDataDefinition: TypedDataDefinition<typedData, primaryType>\n ) => this.signTypedData<typedData, primaryType>(typedDataDefinition),\n signTransaction: this.signTransaction,\n });\n };\n\n /**\n * Creates a new instance of `SolanaSigner` using the provided inner value.\n * This requires the signer to be authenticated first\n *\n * @example\n * ```ts\n * import { AlchemyWebSigner } from \"@account-kit/signer\";\n *\n * const signer = new AlchemyWebSigner({\n * client: {\n * connection: {\n * rpcUrl: \"/api/rpc\",\n * },\n * iframeConfig: {\n * iframeContainerId: \"alchemy-signer-iframe-container\",\n * },\n * },\n * });\n *\n * const solanaSigner = signer.toSolanaSigner();\n * ```\n *\n * @returns {SolanaSigner} A new instance of `SolanaSigner`\n */\n experimental_toSolanaSigner = (): SolanaSigner => {\n if (!this.inner.getUser()) {\n throw new NotAuthenticatedError();\n }\n\n return new SolanaSigner(this.inner);\n };\n\n private authenticateWithEmail = async (\n params: Extract<AuthParams, { type: \"email\" }>\n ): Promise<User> => {\n if (\"email\" in params) {\n const existingUser = await this.getUser(params.email);\n const expirationSeconds = this.getExpirationSeconds();\n\n const { orgId, otpId } = existingUser\n ? await this.inner.initEmailAuth({\n email: params.email,\n emailMode: params.emailMode,\n expirationSeconds,\n redirectParams: params.redirectParams,\n })\n : await this.inner.createAccount({\n type: \"email\",\n email: params.email,\n emailMode: params.emailMode,\n expirationSeconds,\n redirectParams: params.redirectParams,\n });\n\n this.sessionManager.setTemporarySession({\n orgId,\n isNewUser: !existingUser,\n });\n this.store.setState({\n status: AlchemySignerStatus.AWAITING_EMAIL_AUTH,\n otpId,\n error: null,\n });\n\n // We wait for the session manager to emit a connected event if\n // cross tab sessions are permitted\n return new Promise<User>((resolve) => {\n const removeListener = this.sessionManager.on(\n \"connected\",\n (session) => {\n resolve(session.user);\n removeListener();\n }\n );\n });\n } else {\n const temporarySession = params.orgId\n ? { orgId: params.orgId }\n : this.sessionManager.getTemporarySession();\n\n if (!temporarySession) {\n this.store.setState({\n status: AlchemySignerStatus.DISCONNECTED,\n });\n throw new Error(\"Could not find email auth init session!\");\n }\n\n const user = await this.inner.completeAuthWithBundle({\n bundle: params.bundle,\n orgId: temporarySession.orgId,\n connectedEventName: \"connectedEmail\",\n authenticatingType: \"email\",\n });\n\n // fire new user event\n this.emitNewUserEvent(params.isNewUser);\n\n return user;\n }\n };\n\n private authenticateWithPasskey = async (\n args: Extract<AuthParams, { type: \"passkey\" }>\n ): Promise<User> => {\n let user: User;\n const shouldCreateNew = async () => {\n if (\"email\" in args) {\n const existingUser = await this.getUser(args.email);\n return existingUser == null;\n }\n\n return args.createNew;\n };\n\n if (await shouldCreateNew()) {\n const result = await this.inner.createAccount(\n args as Extract<\n AuthParams,\n { type: \"passkey\" } & ({ email: string } | { createNew: true })\n >\n );\n // account creation for passkeys returns the whoami response so we don't have to\n // call it again after signup\n user = {\n address: result.address!,\n userId: result.userId!,\n orgId: result.orgId,\n };\n } else {\n user = await this.inner.lookupUserWithPasskey();\n if (!user) {\n this.store.setState({\n status: AlchemySignerStatus.DISCONNECTED,\n });\n throw new Error(\"No user found\");\n }\n }\n\n return user;\n };\n\n private authenticateWithOauth = async (\n args: Extract<AuthParams, { type: \"oauth\" }>\n ): Promise<User> => {\n const params: OauthParams = {\n ...args,\n expirationSeconds: this.getExpirationSeconds(),\n };\n if (params.mode === \"redirect\") {\n return this.inner.oauthWithRedirect(params);\n } else {\n return this.inner.oauthWithPopup(params);\n }\n };\n\n private authenticateWithOtp = async (\n args: Extract<AuthParams, { type: \"otp\" }>\n ): Promise<User> => {\n const tempSession = this.sessionManager.getTemporarySession();\n const { orgId, isNewUser } = tempSession ?? {};\n const { otpId } = this.store.getState();\n if (!orgId) {\n throw new Error(\"orgId not found in session\");\n }\n if (!otpId) {\n throw new Error(\"otpId not found in session\");\n }\n const { bundle } = await this.inner.submitOtpCode({\n orgId,\n otpId,\n otpCode: args.otpCode,\n expirationSeconds: this.getExpirationSeconds(),\n });\n const user = await this.inner.completeAuthWithBundle({\n bundle,\n orgId,\n connectedEventName: \"connectedOtp\",\n authenticatingType: \"otp\",\n });\n\n this.emitNewUserEvent(isNewUser);\n if (tempSession) {\n this.sessionManager.setTemporarySession({\n ...tempSession,\n isNewUser: false,\n });\n }\n\n return user;\n };\n\n private handleOauthReturn = ({\n bundle,\n orgId,\n idToken,\n isNewUser,\n }: Extract<AuthParams, { type: \"oauthReturn\" }>): Promise<User> => {\n const user = this.inner.completeAuthWithBundle({\n bundle,\n orgId,\n connectedEventName: \"connectedOauth\",\n authenticatingType: \"oauth\",\n idToken,\n });\n\n this.emitNewUserEvent(isNewUser);\n\n return user;\n };\n\n private getExpirationSeconds = () =>\n Math.floor(this.sessionManager.expirationTimeMs / 1000);\n\n private registerListeners = () => {\n // Declare listeners in an object to typecheck that every event type is\n // handled.\n const listeners: SessionManagerEvents = {\n connected: (session) => {\n this.store.setState({\n user: session.user,\n status: AlchemySignerStatus.CONNECTED,\n error: null,\n });\n },\n disconnected: () => {\n this.store.setState({\n user: null,\n status: AlchemySignerStatus.DISCONNECTED,\n });\n },\n initialized: () => {\n this.store.setState((state) => ({\n status: state.user\n ? AlchemySignerStatus.CONNECTED\n : AlchemySignerStatus.DISCONNECTED,\n ...(state.user ? { error: null } : undefined),\n }));\n },\n };\n\n for (const [event, listener] of Object.entries(listeners)) {\n this.sessionManager.on(event as keyof SessionManagerEvents, listener);\n }\n\n this.inner.on(\"authenticating\", ({ type }) => {\n const status = (() => {\n switch (type) {\n case \"email\":\n return AlchemySignerStatus.AUTHENTICATING_EMAIL;\n case \"passkey\":\n return AlchemySignerStatus.AUTHENTICATING_PASSKEY;\n case \"oauth\":\n return AlchemySignerStatus.AUTHENTICATING_OAUTH;\n case \"otp\":\n case \"otpVerify\":\n return AlchemySignerStatus.AWAITING_OTP_AUTH;\n default:\n assertNever(type, \"unhandled authenticating type\");\n }\n })();\n\n // trigger new user event on signer from client\n this.inner.on(\"newUserSignup\", () => {\n this.emitNewUserEvent(true);\n });\n\n this.store.setState({\n status,\n error: null,\n });\n });\n };\n\n private emitNewUserEvent = (isNewUser?: boolean) => {\n // assumes that if isNewUser is undefined it is a returning user\n if (isNewUser) this.store.setState({ isNewUser });\n };\n}\n\nfunction toErrorInfo(error: unknown): ErrorInfo {\n return error instanceof Error\n ? { name: error.name, message: error.message }\n : { name: \"Error\", message: \"Unknown error\" };\n}\n"]}
@@ -135,9 +135,10 @@ export declare abstract class BaseSignerClient<TExportWalletParams = unknown> {
135
135
  * that result here.
136
136
  *
137
137
  * @param {Hex} msg the hex representation of the bytes to sign
138
+ * @param {string} mode specify if signing should happen for solana or ethereum
138
139
  * @returns {Promise<Hex>} the signature over the raw hex
139
140
  */
140
- signRawMessage: (msg: Hex) => Promise<Hex>;
141
+ signRawMessage: (msg: Hex, mode?: "SOLANA" | "ETHEREUM") => Promise<Hex>;
141
142
  /**
142
143
  * Returns the current user or null if no user is set.
143
144
  *
@@ -212,25 +212,32 @@ export class BaseSignerClient {
212
212
  * that result here.
213
213
  *
214
214
  * @param {Hex} msg the hex representation of the bytes to sign
215
+ * @param {string} mode specify if signing should happen for solana or ethereum
215
216
  * @returns {Promise<Hex>} the signature over the raw hex
216
217
  */
217
218
  Object.defineProperty(this, "signRawMessage", {
218
219
  enumerable: true,
219
220
  configurable: true,
220
221
  writable: true,
221
- value: async (msg) => {
222
+ value: async (msg, mode = "ETHEREUM") => {
222
223
  if (!this.user) {
223
224
  throw new NotAuthenticatedError();
224
225
  }
226
+ if (!this.user.solanaAddress && mode === "SOLANA") {
227
+ // TODO: we need to add backwards compatibility for users who signed up before we added Solana support
228
+ throw new Error("No Solana address available for the user");
229
+ }
225
230
  const stampedRequest = await this.turnkeyClient.stampSignRawPayload({
226
231
  organizationId: this.user.orgId,
227
232
  type: "ACTIVITY_TYPE_SIGN_RAW_PAYLOAD_V2",
228
233
  timestampMs: Date.now().toString(),
229
234
  parameters: {
230
235
  encoding: "PAYLOAD_ENCODING_HEXADECIMAL",
231
- hashFunction: "HASH_FUNCTION_NO_OP",
236
+ hashFunction: mode === "ETHEREUM"
237
+ ? "HASH_FUNCTION_NO_OP"
238
+ : "HASH_FUNCTION_NOT_APPLICABLE",
232
239
  payload: msg,
233
- signWith: this.user.address,
240
+ signWith: mode === "ETHEREUM" ? this.user.address : this.user.solanaAddress,
234
241
  },
235
242
  });
236
243
  const { signature } = await this.request("/v1/sign-payload", {
@@ -1 +1 @@
1
- {"version":3,"file":"base.js","sourceRoot":"","sources":["../../../src/client/base.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,sBAAsB,EAAyB,MAAM,cAAc,CAAC;AAC7E,OAAO,EAAE,aAAa,EAAuB,MAAM,eAAe,CAAC;AACnE,OAAO,YAAY,MAAM,eAAe,CAAC;AACzC,OAAO,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AACvC,OAAO,EAAE,MAAM,EAAY,MAAM,MAAM,CAAC;AACxC,OAAO,EAAE,qBAAqB,EAAE,mBAAmB,EAAE,MAAM,cAAc,CAAC;AAC1E,OAAO,EAAE,iBAAiB,EAAE,wBAAwB,EAAE,MAAM,aAAa,CAAC;AAE1E,OAAO,EAAE,eAAe,EAAE,MAAM,6BAA6B,CAAC;AAC9D,OAAO,EAAE,kBAAkB,EAAE,MAAM,gCAAgC,CAAC;AACpE,OAAO,EAAE,WAAW,EAAE,MAAM,4BAA4B,CAAC;AAiCzD;;GAEG;AACH,MAAM,OAAgB,gBAAgB;IAOpC;;;;OAIG;IACH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,kBAAkB,CAAC,MAAM,CAAC,aAAa,CAAC,CAAC;YACvD;gBACE,WAAW,CAAC,QAAQ,EAAE,wBAAwB,QAAQ,EAAE,CAAC,CAAC;QAC9D,CAAC;IACH,CAAC;CA2jBF","sourcesContent":["import { ConnectionConfigSchema, type ConnectionConfig } from \"@aa-sdk/core\";\nimport { TurnkeyClient, type TSignedRequest } from \"@turnkey/http\";\nimport EventEmitter from \"eventemitter3\";\nimport { jwtDecode } from \"jwt-decode\";\nimport { sha256, type Hex } from \"viem\";\nimport { NotAuthenticatedError, OAuthProvidersError } from \"../errors.js\";\nimport { addOpenIdIfAbsent, getDefaultScopeAndClaims } from \"../oauth.js\";\nimport type { OauthMode } from \"../signer.js\";\nimport { base64UrlEncode } from \"../utils/base64UrlEncode.js\";\nimport { resolveRelativeUrl } from \"../utils/resolveRelativeUrl.js\";\nimport { assertNever } from \"../utils/typeAssertions.js\";\nimport type {\n AlchemySignerClientEvent,\n AlchemySignerClientEvents,\n AuthenticatingEventMetadata,\n CreateAccountParams,\n EmailAuthParams,\n GetOauthProviderUrlArgs,\n GetWebAuthnAttestationResult,\n OauthConfig,\n OauthParams,\n OauthState,\n OtpParams,\n SignerBody,\n SignerResponse,\n SignerRoutes,\n SignupResponse,\n User,\n} from \"./types.js\";\n\nexport interface BaseSignerClientParams {\n stamper: TurnkeyClient[\"stamper\"];\n connection: ConnectionConfig;\n rootOrgId?: string;\n rpId?: string;\n}\n\nexport type ExportWalletStamper = TurnkeyClient[\"stamper\"] & {\n injectWalletExportBundle(bundle: string): Promise<boolean>;\n injectKeyExportBundle(bundle: string): Promise<boolean>;\n publicKey(): string | null;\n};\n\n/**\n * Base class for all Alchemy Signer clients\n */\nexport abstract class BaseSignerClient<TExportWalletParams = unknown> {\n private _user: User | undefined;\n private connectionConfig: ConnectionConfig;\n protected turnkeyClient: TurnkeyClient;\n protected rootOrg: string;\n protected eventEmitter: EventEmitter<AlchemySignerClientEvents>;\n protected oauthConfig: OauthConfig | undefined;\n /**\n * Create a new instance of the Alchemy Signer client\n *\n * @param {BaseSignerClientParams} params the parameters required to create the client\n */\n constructor(params: BaseSignerClientParams) {\n const { stamper, connection, rootOrgId } = params;\n this.rootOrg = rootOrgId ?? \"24c1acf5-810f-41e0-a503-d5d13fa8e830\";\n this.eventEmitter = new EventEmitter<AlchemySignerClientEvents>();\n this.connectionConfig = ConnectionConfigSchema.parse(connection);\n this.turnkeyClient = new TurnkeyClient(\n { baseUrl: \"https://api.turnkey.com\" },\n stamper\n );\n }\n\n /**\n * Asynchronously fetches and sets the OAuth configuration.\n *\n * @returns {Promise<OauthConfig>} A promise that resolves to the OAuth configuration\n */\n public initOauth = async (): Promise<OauthConfig> => {\n this.oauthConfig = await this.getOauthConfig();\n return this.oauthConfig;\n };\n\n protected get user() {\n return this._user;\n }\n\n protected set user(user: User | undefined) {\n if (user && !this._user) {\n this.eventEmitter.emit(\"connected\", user);\n } else if (!user && this._user) {\n this.eventEmitter.emit(\"disconnected\");\n }\n\n this._user = user;\n }\n\n /**\n * Sets the stamper of the TurnkeyClient.\n *\n * @param {TurnkeyClient[\"stamper\"]} stamper the stamper function to set for the TurnkeyClient\n */\n protected setStamper(stamper: TurnkeyClient[\"stamper\"]) {\n this.turnkeyClient.stamper = stamper;\n }\n\n /**\n * Exports wallet credentials based on the specified type, either as a SEED_PHRASE or PRIVATE_KEY.\n *\n * @param {object} params The parameters for exporting the wallet\n * @param {ExportWalletStamper} params.exportStamper The stamper used for exporting the wallet\n * @param {\"SEED_PHRASE\" | \"PRIVATE_KEY\"} params.exportAs Specifies the format for exporting the wallet, either as a SEED_PHRASE or PRIVATE_KEY\n * @returns {Promise<boolean>} A promise that resolves to true if the export is successful\n */\n protected exportWalletInner(params: {\n exportStamper: ExportWalletStamper;\n exportAs: \"SEED_PHRASE\" | \"PRIVATE_KEY\";\n }): Promise<boolean> {\n const { exportAs } = params;\n switch (exportAs) {\n case \"PRIVATE_KEY\":\n return this.exportAsPrivateKey(params.exportStamper);\n case \"SEED_PHRASE\":\n return this.exportAsSeedPhrase(params.exportStamper);\n default:\n assertNever(exportAs, `Unknown export mode: ${exportAs}`);\n }\n }\n\n // #region ABSTRACT METHODS\n\n public abstract createAccount(\n params: CreateAccountParams\n ): Promise<SignupResponse>;\n\n public abstract initEmailAuth(\n params: Omit<EmailAuthParams, \"targetPublicKey\">\n ): Promise<{ orgId: string; otpId?: string }>;\n\n public abstract completeAuthWithBundle(params: {\n bundle: string;\n orgId: string;\n connectedEventName: keyof AlchemySignerClientEvents;\n authenticatingType: AuthenticatingEventMetadata[\"type\"];\n idToken?: string;\n }): Promise<User>;\n\n public abstract oauthWithRedirect(\n args: Extract<OauthParams, { mode: \"redirect\" }>\n ): Promise<User | never>;\n\n public abstract oauthWithPopup(\n args: Extract<OauthParams, { mode: \"popup\" }>\n ): Promise<User>;\n\n public abstract submitOtpCode(\n args: Omit<OtpParams, \"targetPublicKey\">\n ): Promise<{ bundle: string }>;\n\n public abstract disconnect(): Promise<void>;\n\n public abstract exportWallet(params: TExportWalletParams): Promise<boolean>;\n\n public abstract lookupUserWithPasskey(user?: User): Promise<User>;\n\n public abstract targetPublicKey(): Promise<string>;\n\n protected abstract getOauthConfig(): Promise<OauthConfig>;\n\n protected abstract getWebAuthnAttestation(\n options: CredentialCreationOptions,\n userDetails?: { username: string }\n ): Promise<GetWebAuthnAttestationResult>;\n\n // #endregion\n\n // #region PUBLIC METHODS\n\n /**\n * Listen to events emitted by the client\n *\n * @param {AlchemySignerClientEvent} event the event you want to listen to\n * @param {AlchemySignerClientEvents[AlchemySignerClientEvent]} listener the callback function to execute when an event is fired\n * @returns {() => void} a function that will remove the listener when called\n */\n public on = <E extends AlchemySignerClientEvent>(\n event: E,\n listener: AlchemySignerClientEvents[E]\n ) => {\n this.eventEmitter.on(event, listener as any);\n\n return () => this.eventEmitter.removeListener(event, listener as any);\n };\n\n /**\n * Handles the creation of authenticators using WebAuthn attestation and the provided options. Requires the user to be authenticated.\n *\n * @param {CredentialCreationOptions} options The options used to create the WebAuthn attestation\n * @returns {Promise<string[]>} A promise that resolves to an array of authenticator IDs\n * @throws {NotAuthenticatedError} If the user is not authenticated\n */\n public addPasskey = async (options: CredentialCreationOptions) => {\n if (!this.user) {\n throw new NotAuthenticatedError();\n }\n const { attestation, challenge } = await this.getWebAuthnAttestation(\n options\n );\n\n const { activity } = await this.turnkeyClient.createAuthenticators({\n type: \"ACTIVITY_TYPE_CREATE_AUTHENTICATORS_V2\",\n timestampMs: Date.now().toString(),\n organizationId: this.user.orgId,\n parameters: {\n userId: this.user.userId,\n authenticators: [\n {\n attestation,\n authenticatorName: `passkey-${Date.now().toString()}`,\n challenge: base64UrlEncode(challenge),\n },\n ],\n },\n });\n\n const { authenticatorIds } = await this.pollActivityCompletion(\n activity,\n this.user.orgId,\n \"createAuthenticatorsResult\"\n );\n\n return authenticatorIds;\n };\n\n /**\n * Retrieves the current user or fetches the user information if not already available.\n *\n * @param {string} [orgId] optional organization ID, defaults to the user's organization ID\n * @param {string} idToken an OIDC ID token containing additional user information\n * @returns {Promise<User>} A promise that resolves to the user object\n * @throws {Error} if no organization ID is provided when there is no current user\n */\n public whoami = async (\n orgId = this.user?.orgId,\n idToken?: string\n ): Promise<User> => {\n if (this.user) {\n return this.user;\n }\n\n if (!orgId) {\n throw new Error(\"No orgId provided\");\n }\n\n const stampedRequest = await this.turnkeyClient.stampGetWhoami({\n organizationId: orgId,\n });\n\n const user = await this.request(\"/v1/whoami\", {\n stampedRequest,\n });\n\n if (idToken) {\n const claims: Record<string, unknown> = jwtDecode(idToken);\n user.idToken = idToken;\n user.claims = claims;\n if (typeof claims.email === \"string\") {\n user.email = claims.email;\n }\n }\n\n const credentialId = (() => {\n try {\n return JSON.parse(stampedRequest?.stamp.stampHeaderValue)\n .credentialId as string;\n } catch (e) {\n return undefined;\n }\n })();\n\n this.user = {\n ...user,\n credentialId,\n };\n\n return this.user;\n };\n\n /**\n * Generates a stamped whoami request for the current user. This request can then be used to call /signer/v1/whoami to get the user information.\n * This is useful if you want to get the user information in a different context like a server. You can pass the stamped request to the server\n * and then call our API to get the user information. Using this stamp is the most trusted way to get the user information since a stamp can only\n * belong to the user who created it.\n *\n * @returns {Promise<TSignedRequest>} a promise that resolves to the \"whoami\" information for the logged in user\n * @throws {Error} if no organization ID is provided\n */\n public stampWhoami = async (): Promise<TSignedRequest> => {\n if (!this.user) {\n throw new Error(\"User must be authenticated to stamp a whoami request\");\n }\n\n return await this.turnkeyClient.stampGetWhoami({\n organizationId: this.user.orgId,\n });\n };\n\n /**\n * Looks up information based on an email address.\n *\n * @param {string} email the email address to look up\n * @returns {Promise<any>} the result of the lookup request\n */\n public lookupUserByEmail = async (email: string) => {\n return this.request(\"/v1/lookup\", { email });\n };\n\n /**\n * This will sign a message with the user's private key, without doing any transformations on the message.\n * For SignMessage or SignTypedData, the caller should hash the message before calling this method and pass\n * that result here.\n *\n * @param {Hex} msg the hex representation of the bytes to sign\n * @returns {Promise<Hex>} the signature over the raw hex\n */\n public signRawMessage = async (msg: Hex): Promise<Hex> => {\n if (!this.user) {\n throw new NotAuthenticatedError();\n }\n\n const stampedRequest = await this.turnkeyClient.stampSignRawPayload({\n organizationId: this.user.orgId,\n type: \"ACTIVITY_TYPE_SIGN_RAW_PAYLOAD_V2\",\n timestampMs: Date.now().toString(),\n parameters: {\n encoding: \"PAYLOAD_ENCODING_HEXADECIMAL\",\n hashFunction: \"HASH_FUNCTION_NO_OP\",\n payload: msg,\n signWith: this.user.address,\n },\n });\n\n const { signature } = await this.request(\"/v1/sign-payload\", {\n stampedRequest,\n });\n\n return signature;\n };\n\n /**\n * Returns the current user or null if no user is set.\n *\n * @returns {User | null} the current user object or null if no user is available\n */\n public getUser = (): User | null => {\n return this.user ?? null;\n };\n\n /**\n * Sends a POST request to the given signer route with the specified body and returns the response.\n * Not intended to be used directly, use the specific methods instead on the client instead.\n *\n * @param {SignerRoutes} route The route to which the request should be sent\n * @param {SignerBody<R>} body The request body containing the data to be sent\n * @returns {Promise<SignerResponse<R>>} A promise that resolves to the response from the signer\n */\n public request = async <R extends SignerRoutes>(\n route: R,\n body: SignerBody<R>\n ): Promise<SignerResponse<R>> => {\n const url = this.connectionConfig.rpcUrl ?? \"https://api.g.alchemy.com\";\n\n const basePath = \"/signer\";\n\n const headers = new Headers();\n headers.append(\"Content-Type\", \"application/json\");\n if (this.connectionConfig.apiKey) {\n headers.append(\"Authorization\", `Bearer ${this.connectionConfig.apiKey}`);\n } else if (this.connectionConfig.jwt) {\n headers.append(\"Authorization\", `Bearer ${this.connectionConfig.jwt}`);\n }\n\n const response = await fetch(`${url}${basePath}${route}`, {\n method: \"POST\",\n body: JSON.stringify(body),\n headers,\n });\n\n if (!response.ok) {\n throw new Error(await response.text());\n }\n\n const json = await response.json();\n\n return json as SignerResponse<R>;\n };\n\n // #endregion\n\n // #region PRIVATE METHODS\n private exportAsSeedPhrase = async (stamper: ExportWalletStamper) => {\n if (!this.user) {\n throw new NotAuthenticatedError();\n }\n\n const { wallets } = await this.turnkeyClient.getWallets({\n organizationId: this.user.orgId,\n });\n\n const walletAccounts = await Promise.all(\n wallets.map(({ walletId }) =>\n this.turnkeyClient.getWalletAccounts({\n organizationId: this.user!.orgId,\n walletId,\n })\n )\n ).then((x) => x.flatMap((x) => x.accounts));\n\n const walletAccount = walletAccounts.find(\n (x) => x.address === this.user!.address\n );\n\n if (!walletAccount) {\n throw new Error(\n `Could not find wallet associated with ${this.user.address}`\n );\n }\n\n const { activity } = await this.turnkeyClient.exportWallet({\n organizationId: this.user.orgId,\n type: \"ACTIVITY_TYPE_EXPORT_WALLET\",\n timestampMs: Date.now().toString(),\n parameters: {\n walletId: walletAccount!.walletId,\n targetPublicKey: stamper.publicKey()!,\n },\n });\n\n const { exportBundle } = await this.pollActivityCompletion(\n activity,\n this.user.orgId,\n \"exportWalletResult\"\n );\n\n const result = await stamper.injectWalletExportBundle(exportBundle);\n\n if (!result) {\n throw new Error(\"Failed to inject wallet export bundle\");\n }\n\n return result;\n };\n\n private exportAsPrivateKey = async (stamper: ExportWalletStamper) => {\n if (!this.user) {\n throw new NotAuthenticatedError();\n }\n\n const { activity } = await this.turnkeyClient.exportWalletAccount({\n organizationId: this.user.orgId,\n type: \"ACTIVITY_TYPE_EXPORT_WALLET_ACCOUNT\",\n timestampMs: Date.now().toString(),\n parameters: {\n address: this.user.address,\n targetPublicKey: stamper.publicKey()!,\n },\n });\n\n const { exportBundle } = await this.pollActivityCompletion(\n activity,\n this.user.orgId,\n \"exportWalletAccountResult\"\n );\n\n const result = await stamper.injectKeyExportBundle(exportBundle);\n\n if (!result) {\n throw new Error(\"Failed to inject wallet export bundle\");\n }\n\n return result;\n };\n\n /**\n * Returns the authentication url for the selected OAuth Proivder\n *\n * @example\n * ```ts\n *\n * cosnt oauthParams = {\n * authProviderId: \"google\",\n * isCustomProvider: false,\n * auth0Connection: undefined,\n * scope: undefined,\n * claims: undefined,\n * mode: \"redirect\",\n * redirectUrl: \"https://your-url-path/oauth-return\",\n * expirationSeconds: 3000\n * };\n *\n * const turnkeyPublicKey = await this.initIframeStamper();\n * const oauthCallbackUrl = this.oauthCallbackUrl;\n * const oauthConfig = this.getOauthConfig() // Optional value for OauthConfig()\n * const usesRelativeUrl = true // Optional value to determine if we use a relative (or absolute) url for the `redirect_url`\n *\n * const oauthProviderUrl = getOauthProviderUrl({\n * oauthParams,\n * turnkeyPublicKey,\n * oauthCallbackUrl\n * })\n *\n * ```\n * @param {GetOauthProviderUrlArgs} args Required. The Oauth provider's auth parameters\n *\n * @returns {Promise<string>} returns the Oauth provider's url\n */\n protected getOauthProviderUrl = async (\n args: GetOauthProviderUrlArgs\n ): Promise<string> => {\n const {\n oauthParams,\n turnkeyPublicKey,\n oauthCallbackUrl,\n oauthConfig,\n usesRelativeUrl = true,\n } = args;\n\n const {\n authProviderId,\n isCustomProvider,\n auth0Connection,\n scope: providedScope,\n claims: providedClaims,\n mode,\n redirectUrl,\n expirationSeconds,\n } = oauthParams;\n\n const { codeChallenge, requestKey, authProviders } =\n oauthConfig ?? (await this.getOauthConfigForMode(mode));\n\n if (!authProviders) {\n throw new OAuthProvidersError();\n }\n\n const authProvider = authProviders.find(\n (provider) =>\n provider.id === authProviderId &&\n !!provider.isCustomProvider === !!isCustomProvider\n );\n\n if (!authProvider) {\n throw new Error(`No auth provider found with id ${authProviderId}`);\n }\n\n let scope: string;\n let claims: string | undefined;\n\n if (providedScope) {\n scope = addOpenIdIfAbsent(providedScope);\n claims = providedClaims;\n } else {\n if (isCustomProvider) {\n throw new Error(\"scope must be provided for a custom provider\");\n }\n const scopeAndClaims = getDefaultScopeAndClaims(authProviderId);\n if (!scopeAndClaims) {\n throw new Error(\n `Default scope not known for provider ${authProviderId}`\n );\n }\n ({ scope, claims } = scopeAndClaims);\n }\n const { authEndpoint, clientId } = authProvider;\n\n const nonce = this.getOauthNonce(turnkeyPublicKey);\n const stateObject: OauthState = {\n authProviderId,\n isCustomProvider,\n requestKey,\n turnkeyPublicKey,\n expirationSeconds,\n redirectUrl:\n mode === \"redirect\"\n ? usesRelativeUrl\n ? resolveRelativeUrl(redirectUrl)\n : redirectUrl\n : undefined,\n openerOrigin: mode === \"popup\" ? window.location.origin : undefined,\n };\n const state = base64UrlEncode(\n new TextEncoder().encode(JSON.stringify(stateObject))\n );\n const authUrl = new URL(authEndpoint);\n const params: Record<string, string> = {\n redirect_uri: oauthCallbackUrl,\n response_type: \"code\",\n scope,\n state,\n code_challenge: codeChallenge,\n code_challenge_method: \"S256\",\n prompt: \"select_account\",\n client_id: clientId,\n nonce,\n // Fixes Facebook mobile login so that `window.opener` doesn't get nullified.\n ...(mode === \"popup\" && authProvider.id === \"facebook\"\n ? { sdk: \"joey\" }\n : {}),\n };\n if (claims) {\n params.claims = claims;\n }\n if (auth0Connection) {\n params.connection = auth0Connection;\n }\n\n Object.keys(params).forEach((param) => {\n params[param] && authUrl.searchParams.append(param, params[param]);\n });\n\n const [urlPath, searchParams] = authUrl.href.split(\"?\");\n\n return `${urlPath?.replace(/\\/$/, \"\")}?${searchParams}`;\n };\n\n private getOauthConfigForMode = async (\n mode: OauthMode\n ): Promise<OauthConfig> => {\n if (this.oauthConfig) {\n return this.oauthConfig;\n } else if (mode === \"redirect\") {\n return this.initOauth();\n } else {\n throw new Error(\n \"enablePopupOauth must be set in configuration or signer.preparePopupOauth must be called before using popup-based OAuth login\"\n );\n }\n };\n\n // eslint-disable-next-line eslint-rules/require-jsdoc-on-reexported-functions\n protected pollActivityCompletion = async <\n T extends keyof Awaited<\n ReturnType<(typeof this.turnkeyClient)[\"getActivity\"]>\n >[\"activity\"][\"result\"]\n >(\n activity: Awaited<\n ReturnType<(typeof this.turnkeyClient)[\"getActivity\"]>\n >[\"activity\"],\n organizationId: string,\n resultKey: T\n ): Promise<\n NonNullable<\n Awaited<\n ReturnType<(typeof this.turnkeyClient)[\"getActivity\"]>\n >[\"activity\"][\"result\"][T]\n >\n > => {\n if (activity.status === \"ACTIVITY_STATUS_COMPLETED\") {\n return activity.result[resultKey]!;\n }\n\n const {\n activity: { status, id, result },\n } = await this.turnkeyClient.getActivity({\n activityId: activity.id,\n organizationId,\n });\n\n if (status === \"ACTIVITY_STATUS_COMPLETED\") {\n return result[resultKey]!;\n }\n\n if (\n status === \"ACTIVITY_STATUS_FAILED\" ||\n status === \"ACTIVITY_STATUS_REJECTED\" ||\n status === \"ACTIVITY_STATUS_CONSENSUS_NEEDED\"\n ) {\n throw new Error(\n `Failed to get activity with with id ${id} (status: ${status})`\n );\n }\n\n // TODO: add ability to configure this + add exponential backoff\n await new Promise((resolve) => setTimeout(resolve, 500));\n\n return this.pollActivityCompletion(activity, organizationId, resultKey);\n };\n // #endregion\n\n /**\n * Turnkey requires the nonce in the id token to be in this format.\n *\n * @param {string} turnkeyPublicKey key from a Turnkey iframe\n * @returns {string} nonce to be used in OIDC\n */\n protected getOauthNonce = (turnkeyPublicKey: string): string => {\n return sha256(new TextEncoder().encode(turnkeyPublicKey)).slice(2);\n };\n}\n"]}
1
+ {"version":3,"file":"base.js","s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AAgB,GAAG,sBAAsB,CAAC,KAAK,CAAC,UAAU,CAAC,CAAC;QACjE,IAAI,CAAC,aAAa,GAAG,IAAI,aAAa,CACpC,EAAE,OAAO,EAAE,yBAAyB,EAAE,EACtC,OAAO,CACR,CAAC;IACJ,CAAC;IAYD,IAAc,IAAI;QAChB,OAAO,IAAI,CAAC,KAAK,CAAC;IACpB,CAAC;IAED,IAAc,IAAI,CAAC,IAAsB;QACvC,IAAI,IAAI,IAAI,CAAC,IAAI,CAAC,KAAK,EAAE,CAAC;YACxB,IAAI,CAAC,YAAY,CAAC,IAAI,CAAC,WAAW,EAAE,IAAI,CAAC,CAAC;QAC5C,CAAC;aAAM,IAAI,CAAC,IAAI,IAAI,IAAI,CAAC,KAAK,EAAE,CAAC;YAC/B,IAAI,CAAC,YAAY,CAAC,IAAI,CAAC,cAAc,CAAC,CAAC;QACzC,CAAC;QAED,IAAI,CAAC,KAAK,GAAG,IAAI,CAAC;IACpB,CAAC;IAED;;;;OAIG;IACO,UAAU,CAAC,OAAiC;QACpD,IAAI,CAAC,aAAa,CAAC,OAAO,GAAG,OAAO,CAAC;IACvC,CAAC;IAED;;;;;;;OAOG;IACO,iBAAiB,CAAC,MAG3B;QACC,MAAM,EAAE,QAAQ,EAAE,GAAG,MAAM,CAAC;QAC5B,QAAQ,QAAQ,EAAE,CAAC;YACjB,KAAK,aAAa;gBAChB,OAAO,IAAI,CAAC,kBAAkB,CAAC,MAAM,CAAC,aAAa,CAAC,CAAC;YACvD,KAAK,aAAa;gBAChB,OAAO,IAAI,CAAC,kBAAkB,CAAC,MAAM,CAAC,aAAa,CAAC,CAAC;YACvD;gBACE,WAAW,CAAC,QAAQ,EAAE,wBAAwB,QAAQ,EAAE,CAAC,CAAC;QAC9D,CAAC;IACH,CAAC;CAwkBF","sourcesContent":["import { ConnectionConfigSchema, type ConnectionConfig } from \"@aa-sdk/core\";\nimport { TurnkeyClient, type TSignedRequest } from \"@turnkey/http\";\nimport EventEmitter from \"eventemitter3\";\nimport { jwtDecode } from \"jwt-decode\";\nimport { sha256, type Hex } from \"viem\";\nimport { NotAuthenticatedError, OAuthProvidersError } from \"../errors.js\";\nimport { addOpenIdIfAbsent, getDefaultScopeAndClaims } from \"../oauth.js\";\nimport type { OauthMode } from \"../signer.js\";\nimport { base64UrlEncode } from \"../utils/base64UrlEncode.js\";\nimport { resolveRelativeUrl } from \"../utils/resolveRelativeUrl.js\";\nimport { assertNever } from \"../utils/typeAssertions.js\";\nimport type {\n AlchemySignerClientEvent,\n AlchemySignerClientEvents,\n AuthenticatingEventMetadata,\n CreateAccountParams,\n EmailAuthParams,\n GetOauthProviderUrlArgs,\n GetWebAuthnAttestationResult,\n OauthConfig,\n OauthParams,\n OauthState,\n OtpParams,\n SignerBody,\n SignerResponse,\n SignerRoutes,\n SignupResponse,\n User,\n} from \"./types.js\";\n\nexport interface BaseSignerClientParams {\n stamper: TurnkeyClient[\"stamper\"];\n connection: ConnectionConfig;\n rootOrgId?: string;\n rpId?: string;\n}\n\nexport type ExportWalletStamper = TurnkeyClient[\"stamper\"] & {\n injectWalletExportBundle(bundle: string): Promise<boolean>;\n injectKeyExportBundle(bundle: string): Promise<boolean>;\n publicKey(): string | null;\n};\n\n/**\n * Base class for all Alchemy Signer clients\n */\nexport abstract class BaseSignerClient<TExportWalletParams = unknown> {\n private _user: User | undefined;\n private connectionConfig: ConnectionConfig;\n protected turnkeyClient: TurnkeyClient;\n protected rootOrg: string;\n protected eventEmitter: EventEmitter<AlchemySignerClientEvents>;\n protected oauthConfig: OauthConfig | undefined;\n /**\n * Create a new instance of the Alchemy Signer client\n *\n * @param {BaseSignerClientParams} params the parameters required to create the client\n */\n constructor(params: BaseSignerClientParams) {\n const { stamper, connection, rootOrgId } = params;\n this.rootOrg = rootOrgId ?? \"24c1acf5-810f-41e0-a503-d5d13fa8e830\";\n this.eventEmitter = new EventEmitter<AlchemySignerClientEvents>();\n this.connectionConfig = ConnectionConfigSchema.parse(connection);\n this.turnkeyClient = new TurnkeyClient(\n { baseUrl: \"https://api.turnkey.com\" },\n stamper\n );\n }\n\n /**\n * Asynchronously fetches and sets the OAuth configuration.\n *\n * @returns {Promise<OauthConfig>} A promise that resolves to the OAuth configuration\n */\n public initOauth = async (): Promise<OauthConfig> => {\n this.oauthConfig = await this.getOauthConfig();\n return this.oauthConfig;\n };\n\n protected get user() {\n return this._user;\n }\n\n protected set user(user: User | undefined) {\n if (user && !this._user) {\n this.eventEmitter.emit(\"connected\", user);\n } else if (!user && this._user) {\n this.eventEmitter.emit(\"disconnected\");\n }\n\n this._user = user;\n }\n\n /**\n * Sets the stamper of the TurnkeyClient.\n *\n * @param {TurnkeyClient[\"stamper\"]} stamper the stamper function to set for the TurnkeyClient\n */\n protected setStamper(stamper: TurnkeyClient[\"stamper\"]) {\n this.turnkeyClient.stamper = stamper;\n }\n\n /**\n * Exports wallet credentials based on the specified type, either as a SEED_PHRASE or PRIVATE_KEY.\n *\n * @param {object} params The parameters for exporting the wallet\n * @param {ExportWalletStamper} params.exportStamper The stamper used for exporting the wallet\n * @param {\"SEED_PHRASE\" | \"PRIVATE_KEY\"} params.exportAs Specifies the format for exporting the wallet, either as a SEED_PHRASE or PRIVATE_KEY\n * @returns {Promise<boolean>} A promise that resolves to true if the export is successful\n */\n protected exportWalletInner(params: {\n exportStamper: ExportWalletStamper;\n exportAs: \"SEED_PHRASE\" | \"PRIVATE_KEY\";\n }): Promise<boolean> {\n const { exportAs } = params;\n switch (exportAs) {\n case \"PRIVATE_KEY\":\n return this.exportAsPrivateKey(params.exportStamper);\n case \"SEED_PHRASE\":\n return this.exportAsSeedPhrase(params.exportStamper);\n default:\n assertNever(exportAs, `Unknown export mode: ${exportAs}`);\n }\n }\n\n // #region ABSTRACT METHODS\n\n public abstract createAccount(\n params: CreateAccountParams\n ): Promise<SignupResponse>;\n\n public abstract initEmailAuth(\n params: Omit<EmailAuthParams, \"targetPublicKey\">\n ): Promise<{ orgId: string; otpId?: string }>;\n\n public abstract completeAuthWithBundle(params: {\n bundle: string;\n orgId: string;\n connectedEventName: keyof AlchemySignerClientEvents;\n authenticatingType: AuthenticatingEventMetadata[\"type\"];\n idToken?: string;\n }): Promise<User>;\n\n public abstract oauthWithRedirect(\n args: Extract<OauthParams, { mode: \"redirect\" }>\n ): Promise<User | never>;\n\n public abstract oauthWithPopup(\n args: Extract<OauthParams, { mode: \"popup\" }>\n ): Promise<User>;\n\n public abstract submitOtpCode(\n args: Omit<OtpParams, \"targetPublicKey\">\n ): Promise<{ bundle: string }>;\n\n public abstract disconnect(): Promise<void>;\n\n public abstract exportWallet(params: TExportWalletParams): Promise<boolean>;\n\n public abstract lookupUserWithPasskey(user?: User): Promise<User>;\n\n public abstract targetPublicKey(): Promise<string>;\n\n protected abstract getOauthConfig(): Promise<OauthConfig>;\n\n protected abstract getWebAuthnAttestation(\n options: CredentialCreationOptions,\n userDetails?: { username: string }\n ): Promise<GetWebAuthnAttestationResult>;\n\n // #endregion\n\n // #region PUBLIC METHODS\n\n /**\n * Listen to events emitted by the client\n *\n * @param {AlchemySignerClientEvent} event the event you want to listen to\n * @param {AlchemySignerClientEvents[AlchemySignerClientEvent]} listener the callback function to execute when an event is fired\n * @returns {() => void} a function that will remove the listener when called\n */\n public on = <E extends AlchemySignerClientEvent>(\n event: E,\n listener: AlchemySignerClientEvents[E]\n ) => {\n this.eventEmitter.on(event, listener as any);\n\n return () => this.eventEmitter.removeListener(event, listener as any);\n };\n\n /**\n * Handles the creation of authenticators using WebAuthn attestation and the provided options. Requires the user to be authenticated.\n *\n * @param {CredentialCreationOptions} options The options used to create the WebAuthn attestation\n * @returns {Promise<string[]>} A promise that resolves to an array of authenticator IDs\n * @throws {NotAuthenticatedError} If the user is not authenticated\n */\n public addPasskey = async (options: CredentialCreationOptions) => {\n if (!this.user) {\n throw new NotAuthenticatedError();\n }\n const { attestation, challenge } = await this.getWebAuthnAttestation(\n options\n );\n\n const { activity } = await this.turnkeyClient.createAuthenticators({\n type: \"ACTIVITY_TYPE_CREATE_AUTHENTICATORS_V2\",\n timestampMs: Date.now().toString(),\n organizationId: this.user.orgId,\n parameters: {\n userId: this.user.userId,\n authenticators: [\n {\n attestation,\n authenticatorName: `passkey-${Date.now().toString()}`,\n challenge: base64UrlEncode(challenge),\n },\n ],\n },\n });\n\n const { authenticatorIds } = await this.pollActivityCompletion(\n activity,\n this.user.orgId,\n \"createAuthenticatorsResult\"\n );\n\n return authenticatorIds;\n };\n\n /**\n * Retrieves the current user or fetches the user information if not already available.\n *\n * @param {string} [orgId] optional organization ID, defaults to the user's organization ID\n * @param {string} idToken an OIDC ID token containing additional user information\n * @returns {Promise<User>} A promise that resolves to the user object\n * @throws {Error} if no organization ID is provided when there is no current user\n */\n public whoami = async (\n orgId = this.user?.orgId,\n idToken?: string\n ): Promise<User> => {\n if (this.user) {\n return this.user;\n }\n\n if (!orgId) {\n throw new Error(\"No orgId provided\");\n }\n\n const stampedRequest = await this.turnkeyClient.stampGetWhoami({\n organizationId: orgId,\n });\n\n const user = await this.request(\"/v1/whoami\", {\n stampedRequest,\n });\n\n if (idToken) {\n const claims: Record<string, unknown> = jwtDecode(idToken);\n user.idToken = idToken;\n user.claims = claims;\n if (typeof claims.email === \"string\") {\n user.email = claims.email;\n }\n }\n\n const credentialId = (() => {\n try {\n return JSON.parse(stampedRequest?.stamp.stampHeaderValue)\n .credentialId as string;\n } catch (e) {\n return undefined;\n }\n })();\n\n this.user = {\n ...user,\n credentialId,\n };\n\n return this.user;\n };\n\n /**\n * Generates a stamped whoami request for the current user. This request can then be used to call /signer/v1/whoami to get the user information.\n * This is useful if you want to get the user information in a different context like a server. You can pass the stamped request to the server\n * and then call our API to get the user information. Using this stamp is the most trusted way to get the user information since a stamp can only\n * belong to the user who created it.\n *\n * @returns {Promise<TSignedRequest>} a promise that resolves to the \"whoami\" information for the logged in user\n * @throws {Error} if no organization ID is provided\n */\n public stampWhoami = async (): Promise<TSignedRequest> => {\n if (!this.user) {\n throw new Error(\"User must be authenticated to stamp a whoami request\");\n }\n\n return await this.turnkeyClient.stampGetWhoami({\n organizationId: this.user.orgId,\n });\n };\n\n /**\n * Looks up information based on an email address.\n *\n * @param {string} email the email address to look up\n * @returns {Promise<any>} the result of the lookup request\n */\n public lookupUserByEmail = async (email: string) => {\n return this.request(\"/v1/lookup\", { email });\n };\n\n /**\n * This will sign a message with the user's private key, without doing any transformations on the message.\n * For SignMessage or SignTypedData, the caller should hash the message before calling this method and pass\n * that result here.\n *\n * @param {Hex} msg the hex representation of the bytes to sign\n * @param {string} mode specify if signing should happen for solana or ethereum\n * @returns {Promise<Hex>} the signature over the raw hex\n */\n public signRawMessage = async (\n msg: Hex,\n mode: \"SOLANA\" | \"ETHEREUM\" = \"ETHEREUM\"\n ): Promise<Hex> => {\n if (!this.user) {\n throw new NotAuthenticatedError();\n }\n\n if (!this.user.solanaAddress && mode === \"SOLANA\") {\n // TODO: we need to add backwards compatibility for users who signed up before we added Solana support\n throw new Error(\"No Solana address available for the user\");\n }\n\n const stampedRequest = await this.turnkeyClient.stampSignRawPayload({\n organizationId: this.user.orgId,\n type: \"ACTIVITY_TYPE_SIGN_RAW_PAYLOAD_V2\",\n timestampMs: Date.now().toString(),\n parameters: {\n encoding: \"PAYLOAD_ENCODING_HEXADECIMAL\",\n hashFunction:\n mode === \"ETHEREUM\"\n ? \"HASH_FUNCTION_NO_OP\"\n : \"HASH_FUNCTION_NOT_APPLICABLE\",\n payload: msg,\n signWith:\n mode === \"ETHEREUM\" ? this.user.address : this.user.solanaAddress!,\n },\n });\n\n const { signature } = await this.request(\"/v1/sign-payload\", {\n stampedRequest,\n });\n\n return signature;\n };\n\n /**\n * Returns the current user or null if no user is set.\n *\n * @returns {User | null} the current user object or null if no user is available\n */\n public getUser = (): User | null => {\n return this.user ?? null;\n };\n\n /**\n * Sends a POST request to the given signer route with the specified body and returns the response.\n * Not intended to be used directly, use the specific methods instead on the client instead.\n *\n * @param {SignerRoutes} route The route to which the request should be sent\n * @param {SignerBody<R>} body The request body containing the data to be sent\n * @returns {Promise<SignerResponse<R>>} A promise that resolves to the response from the signer\n */\n public request = async <R extends SignerRoutes>(\n route: R,\n body: SignerBody<R>\n ): Promise<SignerResponse<R>> => {\n const url = this.connectionConfig.rpcUrl ?? \"https://api.g.alchemy.com\";\n\n const basePath = \"/signer\";\n\n const headers = new Headers();\n headers.append(\"Content-Type\", \"application/json\");\n if (this.connectionConfig.apiKey) {\n headers.append(\"Authorization\", `Bearer ${this.connectionConfig.apiKey}`);\n } else if (this.connectionConfig.jwt) {\n headers.append(\"Authorization\", `Bearer ${this.connectionConfig.jwt}`);\n }\n\n const response = await fetch(`${url}${basePath}${route}`, {\n method: \"POST\",\n body: JSON.stringify(body),\n headers,\n });\n\n if (!response.ok) {\n throw new Error(await response.text());\n }\n\n const json = await response.json();\n\n return json as SignerResponse<R>;\n };\n\n // #endregion\n\n // #region PRIVATE METHODS\n private exportAsSeedPhrase = async (stamper: ExportWalletStamper) => {\n if (!this.user) {\n throw new NotAuthenticatedError();\n }\n\n const { wallets } = await this.turnkeyClient.getWallets({\n organizationId: this.user.orgId,\n });\n\n const walletAccounts = await Promise.all(\n wallets.map(({ walletId }) =>\n this.turnkeyClient.getWalletAccounts({\n organizationId: this.user!.orgId,\n walletId,\n })\n )\n ).then((x) => x.flatMap((x) => x.accounts));\n\n const walletAccount = walletAccounts.find(\n (x) => x.address === this.user!.address\n );\n\n if (!walletAccount) {\n throw new Error(\n `Could not find wallet associated with ${this.user.address}`\n );\n }\n\n const { activity } = await this.turnkeyClient.exportWallet({\n organizationId: this.user.orgId,\n type: \"ACTIVITY_TYPE_EXPORT_WALLET\",\n timestampMs: Date.now().toString(),\n parameters: {\n walletId: walletAccount!.walletId,\n targetPublicKey: stamper.publicKey()!,\n },\n });\n\n const { exportBundle } = await this.pollActivityCompletion(\n activity,\n this.user.orgId,\n \"exportWalletResult\"\n );\n\n const result = await stamper.injectWalletExportBundle(exportBundle);\n\n if (!result) {\n throw new Error(\"Failed to inject wallet export bundle\");\n }\n\n return result;\n };\n\n private exportAsPrivateKey = async (stamper: ExportWalletStamper) => {\n if (!this.user) {\n throw new NotAuthenticatedError();\n }\n\n const { activity } = await this.turnkeyClient.exportWalletAccount({\n organizationId: this.user.orgId,\n type: \"ACTIVITY_TYPE_EXPORT_WALLET_ACCOUNT\",\n timestampMs: Date.now().toString(),\n parameters: {\n address: this.user.address,\n targetPublicKey: stamper.publicKey()!,\n },\n });\n\n const { exportBundle } = await this.pollActivityCompletion(\n activity,\n this.user.orgId,\n \"exportWalletAccountResult\"\n );\n\n const result = await stamper.injectKeyExportBundle(exportBundle);\n\n if (!result) {\n throw new Error(\"Failed to inject wallet export bundle\");\n }\n\n return result;\n };\n\n /**\n * Returns the authentication url for the selected OAuth Proivder\n *\n * @example\n * ```ts\n *\n * cosnt oauthParams = {\n * authProviderId: \"google\",\n * isCustomProvider: false,\n * auth0Connection: undefined,\n * scope: undefined,\n * claims: undefined,\n * mode: \"redirect\",\n * redirectUrl: \"https://your-url-path/oauth-return\",\n * expirationSeconds: 3000\n * };\n *\n * const turnkeyPublicKey = await this.initIframeStamper();\n * const oauthCallbackUrl = this.oauthCallbackUrl;\n * const oauthConfig = this.getOauthConfig() // Optional value for OauthConfig()\n * const usesRelativeUrl = true // Optional value to determine if we use a relative (or absolute) url for the `redirect_url`\n *\n * const oauthProviderUrl = getOauthProviderUrl({\n * oauthParams,\n * turnkeyPublicKey,\n * oauthCallbackUrl\n * })\n *\n * ```\n * @param {GetOauthProviderUrlArgs} args Required. The Oauth provider's auth parameters\n *\n * @returns {Promise<string>} returns the Oauth provider's url\n */\n protected getOauthProviderUrl = async (\n args: GetOauthProviderUrlArgs\n ): Promise<string> => {\n const {\n oauthParams,\n turnkeyPublicKey,\n oauthCallbackUrl,\n oauthConfig,\n usesRelativeUrl = true,\n } = args;\n\n const {\n authProviderId,\n isCustomProvider,\n auth0Connection,\n scope: providedScope,\n claims: providedClaims,\n mode,\n redirectUrl,\n expirationSeconds,\n } = oauthParams;\n\n const { codeChallenge, requestKey, authProviders } =\n oauthConfig ?? (await this.getOauthConfigForMode(mode));\n\n if (!authProviders) {\n throw new OAuthProvidersError();\n }\n\n const authProvider = authProviders.find(\n (provider) =>\n provider.id === authProviderId &&\n !!provider.isCustomProvider === !!isCustomProvider\n );\n\n if (!authProvider) {\n throw new Error(`No auth provider found with id ${authProviderId}`);\n }\n\n let scope: string;\n let claims: string | undefined;\n\n if (providedScope) {\n scope = addOpenIdIfAbsent(providedScope);\n claims = providedClaims;\n } else {\n if (isCustomProvider) {\n throw new Error(\"scope must be provided for a custom provider\");\n }\n const scopeAndClaims = getDefaultScopeAndClaims(authProviderId);\n if (!scopeAndClaims) {\n throw new Error(\n `Default scope not known for provider ${authProviderId}`\n );\n }\n ({ scope, claims } = scopeAndClaims);\n }\n const { authEndpoint, clientId } = authProvider;\n\n const nonce = this.getOauthNonce(turnkeyPublicKey);\n const stateObject: OauthState = {\n authProviderId,\n isCustomProvider,\n requestKey,\n turnkeyPublicKey,\n expirationSeconds,\n redirectUrl:\n mode === \"redirect\"\n ? usesRelativeUrl\n ? resolveRelativeUrl(redirectUrl)\n : redirectUrl\n : undefined,\n openerOrigin: mode === \"popup\" ? window.location.origin : undefined,\n };\n const state = base64UrlEncode(\n new TextEncoder().encode(JSON.stringify(stateObject))\n );\n const authUrl = new URL(authEndpoint);\n const params: Record<string, string> = {\n redirect_uri: oauthCallbackUrl,\n response_type: \"code\",\n scope,\n state,\n code_challenge: codeChallenge,\n code_challenge_method: \"S256\",\n prompt: \"select_account\",\n client_id: clientId,\n nonce,\n // Fixes Facebook mobile login so that `window.opener` doesn't get nullified.\n ...(mode === \"popup\" && authProvider.id === \"facebook\"\n ? { sdk: \"joey\" }\n : {}),\n };\n if (claims) {\n params.claims = claims;\n }\n if (auth0Connection) {\n params.connection = auth0Connection;\n }\n\n Object.keys(params).forEach((param) => {\n params[param] && authUrl.searchParams.append(param, params[param]);\n });\n\n const [urlPath, searchParams] = authUrl.href.split(\"?\");\n\n return `${urlPath?.replace(/\\/$/, \"\")}?${searchParams}`;\n };\n\n private getOauthConfigForMode = async (\n mode: OauthMode\n ): Promise<OauthConfig> => {\n if (this.oauthConfig) {\n return this.oauthConfig;\n } else if (mode === \"redirect\") {\n return this.initOauth();\n } else {\n throw new Error(\n \"enablePopupOauth must be set in configuration or signer.preparePopupOauth must be called before using popup-based OAuth login\"\n );\n }\n };\n\n // eslint-disable-next-line eslint-rules/require-jsdoc-on-reexported-functions\n protected pollActivityCompletion = async <\n T extends keyof Awaited<\n ReturnType<(typeof this.turnkeyClient)[\"getActivity\"]>\n >[\"activity\"][\"result\"]\n >(\n activity: Awaited<\n ReturnType<(typeof this.turnkeyClient)[\"getActivity\"]>\n >[\"activity\"],\n organizationId: string,\n resultKey: T\n ): Promise<\n NonNullable<\n Awaited<\n ReturnType<(typeof this.turnkeyClient)[\"getActivity\"]>\n >[\"activity\"][\"result\"][T]\n >\n > => {\n if (activity.status === \"ACTIVITY_STATUS_COMPLETED\") {\n return activity.result[resultKey]!;\n }\n\n const {\n activity: { status, id, result },\n } = await this.turnkeyClient.getActivity({\n activityId: activity.id,\n organizationId,\n });\n\n if (status === \"ACTIVITY_STATUS_COMPLETED\") {\n return result[resultKey]!;\n }\n\n if (\n status === \"ACTIVITY_STATUS_FAILED\" ||\n status === \"ACTIVITY_STATUS_REJECTED\" ||\n status === \"ACTIVITY_STATUS_CONSENSUS_NEEDED\"\n ) {\n throw new Error(\n `Failed to get activity with with id ${id} (status: ${status})`\n );\n }\n\n // TODO: add ability to configure this + add exponential backoff\n await new Promise((resolve) => setTimeout(resolve, 500));\n\n return this.pollActivityCompletion(activity, organizationId, resultKey);\n };\n // #endregion\n\n /**\n * Turnkey requires the nonce in the id token to be in this format.\n *\n * @param {string} turnkeyPublicKey key from a Turnkey iframe\n * @returns {string} nonce to be used in OIDC\n */\n protected getOauthNonce = (turnkeyPublicKey: string): string => {\n return sha256(new TextEncoder().encode(turnkeyPublicKey)).slice(2);\n };\n}\n"]}
@@ -10,6 +10,7 @@ export type User = {
10
10
  orgId: string;
11
11
  userId: string;
12
12
  address: Address;
13
+ solanaAddress?: string;
13
14
  credentialId?: string;
14
15
  idToken?: string;
15
16
  claims?: Record<string, unknown>;
@@ -1 +1 @@
1
- {"version":3,"file":"types.js","sourceRoot":"","sources":["../../../src/client/types.ts"],"names":[],"mappings":"","sourcesContent":["import type { Address } from \"@aa-sdk/core\";\nimport type { TSignedRequest, getWebAuthnAttestation } from \"@turnkey/http\";\nimport type { Hex } from \"viem\";\nimport type { AuthParams } from \"../signer\";\n\nexport type CredentialCreationOptionOverrides = {\n publicKey?: Partial<CredentialCreationOptions[\"publicKey\"]>;\n} & Pick<CredentialCreationOptions, \"signal\">;\n\n// [!region User]\nexport type User = {\n email?: string;\n orgId: string;\n userId: string;\n address: Address;\n credentialId?: string;\n idToken?: string;\n claims?: Record<string, unknown>;\n};\n// [!endregion User]\n\nexport type ExportWalletParams = {\n iframeContainerId: string;\n iframeElementId?: string;\n};\n\nexport type CreateAccountParams =\n | {\n type: \"email\";\n email: string;\n emailMode?: EmailType;\n expirationSeconds?: number;\n redirectParams?: URLSearchParams;\n }\n | {\n type: \"passkey\";\n email: string;\n creationOpts?: CredentialCreationOptionOverrides;\n }\n | {\n type: \"passkey\";\n username: string;\n creationOpts?: CredentialCreationOptionOverrides;\n };\n\nexport type EmailType = \"magicLink\" | \"otp\";\n\nexport type EmailAuthParams = {\n email: string;\n emailMode?: EmailType;\n expirationSeconds?: number;\n targetPublicKey: string;\n redirectParams?: URLSearchParams;\n};\n\nexport type OauthParams = Extract<AuthParams, { type: \"oauth\" }> & {\n expirationSeconds?: number;\n};\n\nexport type OtpParams = {\n orgId: string;\n otpId: string;\n otpCode: string;\n targetPublicKey: string;\n expirationSeconds?: number;\n};\n\nexport type SignupResponse = {\n orgId: string;\n userId?: string;\n address?: Address;\n otpId?: string;\n};\n\nexport type OauthConfig = {\n codeChallenge: string;\n requestKey: string;\n authProviders: AuthProviderConfig[];\n};\n\nexport type AuthProviderConfig = {\n id: string;\n isCustomProvider?: boolean;\n clientId: string;\n authEndpoint: string;\n};\n\nexport type SignerRoutes = SignerEndpoints[number][\"Route\"];\nexport type SignerBody<T extends SignerRoutes> = Extract<\n SignerEndpoints[number],\n { Route: T }\n>[\"Body\"];\nexport type SignerResponse<T extends SignerRoutes> = Extract<\n SignerEndpoints[number],\n { Route: T }\n>[\"Response\"];\n\nexport type SignerEndpoints = [\n {\n Route: \"/v1/signup\";\n Body:\n | (Omit<EmailAuthParams, \"redirectParams\"> & {\n redirectParams?: string;\n })\n | {\n passkey: {\n challenge: string;\n attestation: Awaited<ReturnType<typeof getWebAuthnAttestation>>;\n };\n };\n Response: SignupResponse;\n },\n {\n Route: \"/v1/whoami\";\n Body: {\n stampedRequest: TSignedRequest;\n };\n Response: User;\n },\n {\n Route: \"/v1/auth\";\n Body: Omit<EmailAuthParams, \"redirectParams\"> & {\n redirectParams?: string;\n };\n Response: {\n orgId: string;\n otpId?: string;\n };\n },\n {\n Route: \"/v1/lookup\";\n Body: {\n email: string;\n };\n Response: {\n orgId: string | null;\n };\n },\n {\n Route: \"/v1/sign-payload\";\n Body: {\n stampedRequest: TSignedRequest;\n };\n Response: {\n signature: Hex;\n };\n },\n {\n Route: \"/v1/prepare-oauth\";\n Body: {\n nonce: string;\n };\n Response: OauthConfig;\n },\n {\n Route: \"/v1/otp\";\n Body: OtpParams;\n Response: { credentialBundle: string };\n }\n];\n\nexport type AuthenticatingEventMetadata = {\n type: \"email\" | \"passkey\" | \"oauth\" | \"otp\" | \"otpVerify\";\n};\n\nexport type AlchemySignerClientEvents = {\n connected(user: User): void;\n newUserSignup(): void;\n authenticating(data: AuthenticatingEventMetadata): void;\n connectedEmail(user: User, bundle: string): void;\n connectedPasskey(user: User): void;\n connectedOauth(user: User, bundle: string): void;\n connectedOtp(user: User, bundle: string): void;\n disconnected(): void;\n};\n\nexport type AlchemySignerClientEvent = keyof AlchemySignerClientEvents;\n\nexport type GetWebAuthnAttestationResult = {\n attestation: Awaited<ReturnType<typeof getWebAuthnAttestation>>;\n challenge: ArrayBuffer;\n authenticatorUserId: ArrayBuffer;\n};\n\nexport type OauthState = {\n authProviderId: string;\n isCustomProvider?: boolean;\n requestKey: string;\n turnkeyPublicKey: string;\n expirationSeconds?: number;\n redirectUrl?: string;\n openerOrigin?: string;\n};\n\nexport type GetOauthProviderUrlArgs = {\n oauthParams: OauthParams;\n turnkeyPublicKey: string;\n oauthCallbackUrl: string;\n oauthConfig?: OauthConfig;\n usesRelativeUrl?: boolean;\n};\n"]}
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../../../src/client/types.ts"],"names":[],"mappings":"","sourcesContent":["import type { Address } from \"@aa-sdk/core\";\nimport type { TSignedRequest, getWebAuthnAttestation } from \"@turnkey/http\";\nimport type { Hex } from \"viem\";\nimport type { AuthParams } from \"../signer\";\n\nexport type CredentialCreationOptionOverrides = {\n publicKey?: Partial<CredentialCreationOptions[\"publicKey\"]>;\n} & Pick<CredentialCreationOptions, \"signal\">;\n\n// [!region User]\nexport type User = {\n email?: string;\n orgId: string;\n userId: string;\n address: Address;\n solanaAddress?: string;\n credentialId?: string;\n idToken?: string;\n claims?: Record<string, unknown>;\n};\n// [!endregion User]\n\nexport type ExportWalletParams = {\n iframeContainerId: string;\n iframeElementId?: string;\n};\n\nexport type CreateAccountParams =\n | {\n type: \"email\";\n email: string;\n emailMode?: EmailType;\n expirationSeconds?: number;\n redirectParams?: URLSearchParams;\n }\n | {\n type: \"passkey\";\n email: string;\n creationOpts?: CredentialCreationOptionOverrides;\n }\n | {\n type: \"passkey\";\n username: string;\n creationOpts?: CredentialCreationOptionOverrides;\n };\n\nexport type EmailType = \"magicLink\" | \"otp\";\n\nexport type EmailAuthParams = {\n email: string;\n emailMode?: EmailType;\n expirationSeconds?: number;\n targetPublicKey: string;\n redirectParams?: URLSearchParams;\n};\n\nexport type OauthParams = Extract<AuthParams, { type: \"oauth\" }> & {\n expirationSeconds?: number;\n};\n\nexport type OtpParams = {\n orgId: string;\n otpId: string;\n otpCode: string;\n targetPublicKey: string;\n expirationSeconds?: number;\n};\n\nexport type SignupResponse = {\n orgId: string;\n userId?: string;\n address?: Address;\n otpId?: string;\n};\n\nexport type OauthConfig = {\n codeChallenge: string;\n requestKey: string;\n authProviders: AuthProviderConfig[];\n};\n\nexport type AuthProviderConfig = {\n id: string;\n isCustomProvider?: boolean;\n clientId: string;\n authEndpoint: string;\n};\n\nexport type SignerRoutes = SignerEndpoints[number][\"Route\"];\nexport type SignerBody<T extends SignerRoutes> = Extract<\n SignerEndpoints[number],\n { Route: T }\n>[\"Body\"];\nexport type SignerResponse<T extends SignerRoutes> = Extract<\n SignerEndpoints[number],\n { Route: T }\n>[\"Response\"];\n\nexport type SignerEndpoints = [\n {\n Route: \"/v1/signup\";\n Body:\n | (Omit<EmailAuthParams, \"redirectParams\"> & {\n redirectParams?: string;\n })\n | {\n passkey: {\n challenge: string;\n attestation: Awaited<ReturnType<typeof getWebAuthnAttestation>>;\n };\n };\n Response: SignupResponse;\n },\n {\n Route: \"/v1/whoami\";\n Body: {\n stampedRequest: TSignedRequest;\n };\n Response: User;\n },\n {\n Route: \"/v1/auth\";\n Body: Omit<EmailAuthParams, \"redirectParams\"> & {\n redirectParams?: string;\n };\n Response: {\n orgId: string;\n otpId?: string;\n };\n },\n {\n Route: \"/v1/lookup\";\n Body: {\n email: string;\n };\n Response: {\n orgId: string | null;\n };\n },\n {\n Route: \"/v1/sign-payload\";\n Body: {\n stampedRequest: TSignedRequest;\n };\n Response: {\n signature: Hex;\n };\n },\n {\n Route: \"/v1/prepare-oauth\";\n Body: {\n nonce: string;\n };\n Response: OauthConfig;\n },\n {\n Route: \"/v1/otp\";\n Body: OtpParams;\n Response: { credentialBundle: string };\n }\n];\n\nexport type AuthenticatingEventMetadata = {\n type: \"email\" | \"passkey\" | \"oauth\" | \"otp\" | \"otpVerify\";\n};\n\nexport type AlchemySignerClientEvents = {\n connected(user: User): void;\n newUserSignup(): void;\n authenticating(data: AuthenticatingEventMetadata): void;\n connectedEmail(user: User, bundle: string): void;\n connectedPasskey(user: User): void;\n connectedOauth(user: User, bundle: string): void;\n connectedOtp(user: User, bundle: string): void;\n disconnected(): void;\n};\n\nexport type AlchemySignerClientEvent = keyof AlchemySignerClientEvents;\n\nexport type GetWebAuthnAttestationResult = {\n attestation: Awaited<ReturnType<typeof getWebAuthnAttestation>>;\n challenge: ArrayBuffer;\n authenticatorUserId: ArrayBuffer;\n};\n\nexport type OauthState = {\n authProviderId: string;\n isCustomProvider?: boolean;\n requestKey: string;\n turnkeyPublicKey: string;\n expirationSeconds?: number;\n redirectUrl?: string;\n openerOrigin?: string;\n};\n\nexport type GetOauthProviderUrlArgs = {\n oauthParams: OauthParams;\n turnkeyPublicKey: string;\n oauthCallbackUrl: string;\n oauthConfig?: OauthConfig;\n usesRelativeUrl?: boolean;\n};\n"]}
@@ -2,9 +2,10 @@ export { BaseAlchemySigner } from "./base.js";
2
2
  export { BaseSignerClient } from "./client/base.js";
3
3
  export { AlchemySignerWebClient, OauthCancelledError, OauthFailedError, } from "./client/index.js";
4
4
  export type * from "./client/types.js";
5
+ export { NotAuthenticatedError, OAuthProvidersError } from "./errors.js";
5
6
  export { DEFAULT_SESSION_MS, SessionManagerParamsSchema, } from "./session/manager.js";
6
7
  export type * from "./signer.js";
7
8
  export { AlchemyWebSigner } from "./signer.js";
9
+ export type * from "./solanaSigner.js";
8
10
  export type * from "./types.js";
9
11
  export { AlchemySignerStatus } from "./types.js";
10
- export { OAuthProvidersError, NotAuthenticatedError } from "./errors.js";
package/dist/esm/index.js CHANGED
@@ -1,8 +1,8 @@
1
1
  export { BaseAlchemySigner } from "./base.js";
2
2
  export { BaseSignerClient } from "./client/base.js";
3
3
  export { AlchemySignerWebClient, OauthCancelledError, OauthFailedError, } from "./client/index.js";
4
+ export { NotAuthenticatedError, OAuthProvidersError } from "./errors.js";
4
5
  export { DEFAULT_SESSION_MS, SessionManagerParamsSchema, } from "./session/manager.js";
5
6
  export { AlchemyWebSigner } from "./signer.js";
6
7
  export { AlchemySignerStatus } from "./types.js";
7
- export { OAuthProvidersError, NotAuthenticatedError } from "./errors.js";
8
8
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,MAAM,WAAW,CAAC;AAC9C,OAAO,EAAE,gBAAgB,EAAE,MAAM,kBAAkB,CAAC;AACpD,OAAO,EACL,sBAAsB,EACtB,mBAAmB,EACnB,gBAAgB,GACjB,MAAM,mBAAmB,CAAC;AAE3B,OAAO,EACL,kBAAkB,EAClB,0BAA0B,GAC3B,MAAM,sBAAsB,CAAC;AAE9B,OAAO,EAAE,gBAAgB,EAAE,MAAM,aAAa,CAAC;AAE/C,OAAO,EAAE,mBAAmB,EAAE,MAAM,YAAY,CAAC;AACjD,OAAO,EAAE,mBAAmB,EAAE,qBAAqB,EAAE,MAAM,aAAa,CAAC","sourcesContent":["export { BaseAlchemySigner } from \"./base.js\";\nexport { BaseSignerClient } from \"./client/base.js\";\nexport {\n AlchemySignerWebClient,\n OauthCancelledError,\n OauthFailedError,\n} from \"./client/index.js\";\nexport type * from \"./client/types.js\";\nexport {\n DEFAULT_SESSION_MS,\n SessionManagerParamsSchema,\n} from \"./session/manager.js\";\nexport type * from \"./signer.js\";\nexport { AlchemyWebSigner } from \"./signer.js\";\nexport type * from \"./types.js\";\nexport { AlchemySignerStatus } from \"./types.js\";\nexport { OAuthProvidersError, NotAuthenticatedError } from \"./errors.js\";\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,MAAM,WAAW,CAAC;AAC9C,OAAO,EAAE,gBAAgB,EAAE,MAAM,kBAAkB,CAAC;AACpD,OAAO,EACL,sBAAsB,EACtB,mBAAmB,EACnB,gBAAgB,GACjB,MAAM,mBAAmB,CAAC;AAE3B,OAAO,EAAE,qBAAqB,EAAE,mBAAmB,EAAE,MAAM,aAAa,CAAC;AACzE,OAAO,EACL,kBAAkB,EAClB,0BAA0B,GAC3B,MAAM,sBAAsB,CAAC;AAE9B,OAAO,EAAE,gBAAgB,EAAE,MAAM,aAAa,CAAC;AAG/C,OAAO,EAAE,mBAAmB,EAAE,MAAM,YAAY,CAAC","sourcesContent":["export { BaseAlchemySigner } from \"./base.js\";\nexport { BaseSignerClient } from \"./client/base.js\";\nexport {\n AlchemySignerWebClient,\n OauthCancelledError,\n OauthFailedError,\n} from \"./client/index.js\";\nexport type * from \"./client/types.js\";\nexport { NotAuthenticatedError, OAuthProvidersError } from \"./errors.js\";\nexport {\n DEFAULT_SESSION_MS,\n SessionManagerParamsSchema,\n} from \"./session/manager.js\";\nexport type * from \"./signer.js\";\nexport { AlchemyWebSigner } from \"./signer.js\";\nexport type * from \"./solanaSigner.js\";\nexport type * from \"./types.js\";\nexport { AlchemySignerStatus } from \"./types.js\";\n"]}
@@ -0,0 +1,12 @@
1
+ import { Transaction, type VersionedTransaction } from "@solana/web3.js";
2
+ import { type ByteArray } from "viem";
3
+ import type { BaseSignerClient } from "./client/base";
4
+ export declare class SolanaSigner {
5
+ private alchemyClient;
6
+ address: string;
7
+ constructor(client: BaseSignerClient);
8
+ addSignature(tx: Transaction | VersionedTransaction): Promise<Transaction | VersionedTransaction>;
9
+ signMessage(message: Uint8Array): Promise<ByteArray>;
10
+ private formatSignatureForSolana;
11
+ private getMessageToSign;
12
+ }
@@ -0,0 +1,67 @@
1
+ import { PublicKey, Transaction, } from "@solana/web3.js";
2
+ import { size, slice, toBytes, toHex } from "viem";
3
+ import { NotAuthenticatedError } from "./errors.js";
4
+ // TODO: I don't want this to be a class so that the flow is closer to how we do this for `toViemAccount`
5
+ export class SolanaSigner {
6
+ constructor(client) {
7
+ Object.defineProperty(this, "alchemyClient", {
8
+ enumerable: true,
9
+ configurable: true,
10
+ writable: true,
11
+ value: void 0
12
+ });
13
+ Object.defineProperty(this, "address", {
14
+ enumerable: true,
15
+ configurable: true,
16
+ writable: true,
17
+ value: void 0
18
+ });
19
+ this.alchemyClient = client;
20
+ if (!client.getUser())
21
+ throw new Error("Must be authenticated!");
22
+ // TODO: also throw here
23
+ this.address = client.getUser().solanaAddress;
24
+ }
25
+ async addSignature(tx) {
26
+ const user = this.alchemyClient.getUser();
27
+ if (!user) {
28
+ throw new NotAuthenticatedError();
29
+ }
30
+ if (!user.solanaAddress) {
31
+ throw new Error("no solana address");
32
+ }
33
+ const fromKey = new PublicKey(user.solanaAddress);
34
+ const messageToSign = this.getMessageToSign(tx);
35
+ const signature = await this.alchemyClient.signRawMessage(messageToSign, "SOLANA");
36
+ tx.addSignature(fromKey, Buffer.from(toBytes(this.formatSignatureForSolana(signature))));
37
+ return tx;
38
+ }
39
+ async signMessage(message) {
40
+ const user = this.alchemyClient.getUser();
41
+ if (!user) {
42
+ throw new NotAuthenticatedError();
43
+ }
44
+ if (!user.solanaAddress) {
45
+ throw new Error("no solana address");
46
+ }
47
+ const messageToSign = toHex(message);
48
+ const signature = await this.alchemyClient.signRawMessage(messageToSign, "SOLANA");
49
+ return toBytes(this.formatSignatureForSolana(signature));
50
+ }
51
+ formatSignatureForSolana(signature) {
52
+ if (size(signature) === 64)
53
+ return signature;
54
+ return slice(signature, 0, 64);
55
+ }
56
+ getMessageToSign(tx) {
57
+ let messageToSign;
58
+ if (tx instanceof Transaction) {
59
+ messageToSign = tx.serializeMessage();
60
+ }
61
+ else {
62
+ messageToSign = Buffer.from(tx.message.serialize());
63
+ }
64
+ return toHex(messageToSign);
65
+ }
66
+ }
67
+ //# sourceMappingURL=solanaSigner.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"solanaSigner.js","sourceRoot":"","sources":["../../src/solanaSigner.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,SAAS,EACT,WAAW,GAEZ,MAAM,iBAAiB,CAAC;AACzB,OAAO,EAAE,IAAI,EAAE,KAA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AAO,EAAE,CAAC;QAC1C,IAAI,CAAC,IAAI,EAAE,CAAC;YACV,MAAM,IAAI,qBAAqB,EAAE,CAAC;QACpC,CAAC;QAED,IAAI,CAAC,IAAI,CAAC,aAAa,EAAE,CAAC;YACxB,MAAM,IAAI,KAAK,CAAC,mBAAmB,CAAC,CAAC;QACvC,CAAC;QAED,MAAM,aAAa,GAAG,KAAK,CAAC,OAAO,CAAC,CAAC;QACrC,MAAM,SAAS,GAAG,MAAM,IAAI,CAAC,aAAa,CAAC,cAAc,CACvD,aAAa,EACb,QAAQ,CACT,CAAC;QAEF,OAAO,OAAO,CAAC,IAAI,CAAC,wBAAwB,CAAC,SAAS,CAAC,CAAC,CAAC;IAC3D,CAAC;IAEO,wBAAwB,CAAC,SAAc;QAC7C,IAAI,IAAI,CAAC,SAAS,CAAC,KAAK,EAAE;YAAE,OAAO,SAAS,CAAC;QAE7C,OAAO,KAAK,CAAC,SAAS,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC;IACjC,CAAC;IAEO,gBAAgB,CAAC,EAAsC;QAC7D,IAAI,aAAa,CAAC;QAClB,IAAI,EAAE,YAAY,WAAW,EAAE,CAAC;YAC9B,aAAa,GAAG,EAAE,CAAC,gBAAgB,EAAE,CAAC;QACxC,CAAC;aAAM,CAAC;YACN,aAAa,GAAG,MAAM,CAAC,IAAI,CAAC,EAAE,CAAC,OAAO,CAAC,SAAS,EAAE,CAAC,CAAC;QACtD,CAAC;QACD,OAAO,KAAK,CAAC,aAAa,CAAC,CAAC;IAC9B,CAAC;CACF","sourcesContent":["import {\n PublicKey,\n Transaction,\n type VersionedTransaction,\n} from \"@solana/web3.js\";\nimport { size, slice, toBytes, toHex, type ByteArray, type Hex } from \"viem\";\nimport type { BaseSignerClient } from \"./client/base\";\nimport { NotAuthenticatedError } from \"./errors.js\";\n\n// TODO: I don't want this to be a class so that the flow is closer to how we do this for `toViemAccount`\nexport class SolanaSigner {\n private alchemyClient: BaseSignerClient;\n public address: string;\n\n constructor(client: BaseSignerClient) {\n this.alchemyClient = client;\n if (!client.getUser()) throw new Error(\"Must be authenticated!\");\n\n // TODO: also throw here\n this.address = client.getUser()!.solanaAddress!;\n }\n\n async addSignature(\n tx: Transaction | VersionedTransaction\n ): Promise<Transaction | VersionedTransaction> {\n const user = this.alchemyClient.getUser();\n if (!user) {\n throw new NotAuthenticatedError();\n }\n\n if (!user.solanaAddress) {\n throw new Error(\"no solana address\");\n }\n\n const fromKey = new PublicKey(user.solanaAddress);\n const messageToSign = this.getMessageToSign(tx);\n const signature = await this.alchemyClient.signRawMessage(\n messageToSign,\n \"SOLANA\"\n );\n\n tx.addSignature(\n fromKey,\n Buffer.from(toBytes(this.formatSignatureForSolana(signature)))\n );\n return tx;\n }\n\n async signMessage(message: Uint8Array): Promise<ByteArray> {\n const user = this.alchemyClient.getUser();\n if (!user) {\n throw new NotAuthenticatedError();\n }\n\n if (!user.solanaAddress) {\n throw new Error(\"no solana address\");\n }\n\n const messageToSign = toHex(message);\n const signature = await this.alchemyClient.signRawMessage(\n messageToSign,\n \"SOLANA\"\n );\n\n return toBytes(this.formatSignatureForSolana(signature));\n }\n\n private formatSignatureForSolana(signature: Hex): Hex {\n if (size(signature) === 64) return signature;\n\n return slice(signature, 0, 64);\n }\n\n private getMessageToSign(tx: Transaction | VersionedTransaction): Hex {\n let messageToSign;\n if (tx instanceof Transaction) {\n messageToSign = tx.serializeMessage();\n } else {\n messageToSign = Buffer.from(tx.message.serialize());\n }\n return toHex(messageToSign);\n }\n}\n"]}
@@ -1 +1 @@
1
- export declare const VERSION = "4.15.3";
1
+ export declare const VERSION = "4.16.0";
@@ -1,4 +1,4 @@
1
1
  // This file is autogenerated by inject-version.ts. Any changes will be
2
2
  // overwritten on commit!
3
- export const VERSION = "4.15.3";
3
+ export const VERSION = "4.16.0";
4
4
  //# sourceMappingURL=version.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"version.js","sourceRoot":"","sources":["../../src/version.ts"],"names":[],"mappings":"AAAA,uEAAuE;AACvE,yBAAyB;AACzB,MAAM,CAAC,MAAM,OAAO,GAAG,QAAQ,CAAC","sourcesContent":["// This file is autogenerated by inject-version.ts. Any changes will be\n// overwritten on commit!\nexport const VERSION = \"4.15.3\";\n"]}
1
+ {"version":3,"file":"version.js","sourceRoot":"","sources":["../../src/version.ts"],"names":[],"mappings":"AAAA,uEAAuE;AACvE,yBAAyB;AACzB,MAAM,CAAC,MAAM,OAAO,GAAG,QAAQ,CAAC","sourcesContent":["// This file is autogenerated by inject-version.ts. Any changes will be\n// overwritten on commit!\nexport const VERSION = \"4.16.0\";\n"]}
@@ -1,11 +1,12 @@
1
1
  import { type SmartAccountAuthenticator } from "@aa-sdk/core";
2
2
  import { type GetTransactionType, type Hex, type IsNarrowable, type LocalAccount, type SerializeTransactionFn, type SignableMessage, type TransactionSerializable, type TransactionSerialized, type TypedData, type TypedDataDefinition } from "viem";
3
+ import { type Authorization } from "viem/experimental";
3
4
  import type { BaseSignerClient } from "./client/base";
4
5
  import type { OauthConfig, User } from "./client/types";
5
6
  import { type SessionManagerParams } from "./session/manager.js";
6
7
  import type { AuthParams } from "./signer";
8
+ import { SolanaSigner } from "./solanaSigner.js";
7
9
  import { type AlchemySignerEvents, type ErrorInfo } from "./types.js";
8
- import { type Authorization } from "viem/experimental";
9
10
  export interface BaseAlchemySignerParams<TClient extends BaseSignerClient> {
10
11
  client: TClient;
11
12
  sessionConfig?: Omit<SessionManagerParams, "client">;
@@ -380,6 +381,31 @@ export declare abstract class BaseAlchemySigner<TClient extends BaseSignerClient
380
381
  * @returns {LocalAccount} a LocalAccount object that can be used with viem's wallet client
381
382
  */
382
383
  toViemAccount: () => LocalAccount;
384
+ /**
385
+ * Creates a new instance of `SolanaSigner` using the provided inner value.
386
+ * This requires the signer to be authenticated first
387
+ *
388
+ * @example
389
+ * ```ts
390
+ * import { AlchemyWebSigner } from "@account-kit/signer";
391
+ *
392
+ * const signer = new AlchemyWebSigner({
393
+ * client: {
394
+ * connection: {
395
+ * rpcUrl: "/api/rpc",
396
+ * },
397
+ * iframeConfig: {
398
+ * iframeContainerId: "alchemy-signer-iframe-container",
399
+ * },
400
+ * },
401
+ * });
402
+ *
403
+ * const solanaSigner = signer.toSolanaSigner();
404
+ * ```
405
+ *
406
+ * @returns {SolanaSigner} A new instance of `SolanaSigner`
407
+ */
408
+ experimental_toSolanaSigner: () => SolanaSigner;
383
409
  private authenticateWithEmail;
384
410
  private authenticateWithPasskey;
385
411
  private authenticateWithOauth;
@@ -1 +1 @@
1
- {"version":3,"file":"base.d.ts","sourceRoot":"","sources":["../../src/base.ts"],"names":[],"mappings":"AAAA,OAAO,EAAa,KAAK,yBAAyB,EAAE,MAAM,cAAc,CAAC;AACzE,OAAO,EAKL,KAAK,kBAAkB,EACvB,KAAK,GAAG,EACR,KAAK,YAAY,EACjB,KAAK,YAAY,EACjB,KAAK,sBAAsB,EAC3B,KAAK,eAAe,EACpB,KAAK,uBAAuB,EAC5B,KAAK,qBAAqB,EAC1B,KAAK,SAAS,EACd,KAAK,mBAAmB,EACzB,MAAM,MAAM,CAAC;AAKd,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,eAAe,CAAC;AACtD,OAAO,KAAK,EAAE,WAAW,EAAe,IAAI,EAAE,MAAM,gBAAgB,CAAC;AAGrE,OAAO,EAEL,KAAK,oBAAoB,EAC1B,MAAM,sBAAsB,CAAC;AAC9B,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,UAAU,CAAC;AAC3C,OAAO,EAGL,KAAK,mBAAmB,EACxB,KAAK,SAAS,EACf,MAAM,YAAY,CAAC;AAGpB,OAAO,EAAqB,KAAK,aAAa,EAAE,MAAM,mBAAmB,CAAC;AAE1E,MAAM,WAAW,uBAAuB,CAAC,OAAO,SAAS,gBAAgB;IACvE,MAAM,EAAE,OAAO,CAAC;IAChB,aAAa,CAAC,EAAE,IAAI,CAAC,oBAAoB,EAAE,QAAQ,CAAC,CAAC;IACrD,YAAY,CAAC,EAAE,SAAS,CAA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AK,EAAE,MAAM,CAAA;KAAE,GAAG,IAAI,CAAC,CAWxD;IAEL;;;;;;;;;;;;;;;;;;;;;;;OAuBG;IACH,UAAU,EAAE,CAAC,MAAM,CAAC,EAAE,yBAAyB,KAAK,OAAO,CAAC,MAAM,EAAE,CAAC,CAGhE;IAEL;;;;;;;;;;;;;;;;;;;;;;;;;;OA0BG;IACH,YAAY,EAAE,CACZ,MAAM,EAAE,UAAU,CAAC,CAAC,OAAO,IAAI,CAAC,KAAK,CAAC,CAAC,cAAc,CAAC,CAAC,CAAC,CAAC,CAAC,KACvD,OAAO,CAAC,OAAO,CAAC,CAEnB;IAEF;;;;;;;;;;;;;;;;;;;;;;;;OAwBG;IACH,aAAa,QAAO,YAAY,CAkB9B;IAEF;;;;;;;;;;;;;;;;;;;;;;;OAuBG;IACH,2BAA2B,QAAO,YAAY,CAM5C;IAEF,OAAO,CAAC,qBAAqB,CAmE3B;IAEF,OAAO,CAAC,uBAAuB,CAsC7B;IAEF,OAAO,CAAC,qBAAqB,CAY3B;IAEF,OAAO,CAAC,mBAAmB,CAkCzB;IAEF,OAAO,CAAC,iBAAiB,CAiBvB;IAEF,OAAO,CAAC,oBAAoB,CAC8B;IAE1D,OAAO,CAAC,iBAAiB,CA0DvB;IAEF,OAAO,CAAC,gBAAgB,CAGtB;CACH"}
@@ -135,9 +135,10 @@ export declare abstract class BaseSignerClient<TExportWalletParams = unknown> {
135
135
  * that result here.
136
136
  *
137
137
  * @param {Hex} msg the hex representation of the bytes to sign
138
+ * @param {string} mode specify if signing should happen for solana or ethereum
138
139
  * @returns {Promise<Hex>} the signature over the raw hex
139
140
  */
140
- signRawMessage: (msg: Hex) => Promise<Hex>;
141
+ signRawMessage: (msg: Hex, mode?: "SOLANA" | "ETHEREUM") => Promise<Hex>;
141
142
  /**
142
143
  * Returns the current user or null if no user is set.
143
144
  *
@@ -1 +1 @@
1
- {"version":3,"file":"base.d.ts","sourceRoot":"","sources":["../../../src/client/base.ts"],"names":[],"mappings":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ACI,MAAM,yCAED,MAAM,KACf,QAAQ,IAAI,CAAC,CAyCd;IAEF;;;;;;;;OAQG;IACI,WAAW,QAAa,QAAQ,cAAc,CAAC,CAQpD;IAEF;;;;;OAKG;IACI,iBAAiB,UAAiB,MAAM;;OAE7C;IAEF;;;;;;;;OAQG;IACI,cAAc,QACd,GAAG,SACF,QAAQ,GAAG,UAAU,KAC1B,QAAQ,GAAG,CAAC,CA+Bb;IAEF;;;;OAIG;IACI,OAAO,QAAO,IAAI,GAAG,IAAI,CAE9B;IAEF;;;;;;;OAOG;IACI,OAAO,0LA6BZ;IAKF,OAAO,CAAC,kBAAkB,CAmDxB;IAEF,OAAO,CAAC,kBAAkB,CA4BxB;IAEF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;OAgCG;IACH,SAAS,CAAC,mBAAmB,SACrB,uBAAuB,KAC5B,QAAQ,MAAM,CAAC,CAyGhB;IAEF,OAAO,CAAC,qBAAqB,CAY3B;IAGF,SAAS,CAAC,sBAAsB,0uCAKpB,QACR,WAAW,CAAC,OAAO,IAAI,CAAC,aAAa,CAAC,CAAC,aAAa,CAAC,CAAC,CACvD,CAAC,UAAU,CAAC,kBACG,MAAM;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;WAsCtB;IAGF;;;;;OAKG;IACH,SAAS,CAAC,aAAa,qBAAsB,MAAM,KAAG,MAAM,CAE1D;CACH"}
@@ -10,6 +10,7 @@ export type User = {
10
10
  orgId: string;
11
11
  userId: string;
12
12
  address: Address;
13
+ solanaAddress?: string;
13
14
  credentialId?: string;
14
15
  idToken?: string;
15
16
  claims?: Record<string, unknown>;
@@ -1 +1 @@
1
- {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../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CAAC,EAAE,OAAO,CAAC;CAC3B,CAAC"}
@@ -2,10 +2,11 @@ export { BaseAlchemySigner } from "./base.js";
2
2
  export { BaseSignerClient } from "./client/base.js";
3
3
  export { AlchemySignerWebClient, OauthCancelledError, OauthFailedError, } from "./client/index.js";
4
4
  export type * from "./client/types.js";
5
+ export { NotAuthenticatedError, OAuthProvidersError } from "./errors.js";
5
6
  export { DEFAULT_SESSION_MS, SessionManagerParamsSchema, } from "./session/manager.js";
6
7
  export type * from "./signer.js";
7
8
  export { AlchemyWebSigner } from "./signer.js";
9
+ export type * from "./solanaSigner.js";
8
10
  export type * from "./types.js";
9
11
  export { AlchemySignerStatus } from "./types.js";
10
- export { OAuthProvidersError, NotAuthenticatedError } from "./errors.js";
11
12
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,MAAM,WAAW,CAAC;AAC9C,OAAO,EAAE,gBAAgB,EAAE,MAAM,kBAAkB,CAAC;AACpD,OAAO,EACL,sBAAsB,EACtB,mBAAmB,EACnB,gBAAgB,GACjB,MAAM,mBAAmB,CAAC;AAC3B,mBAAmB,mBAAmB,CAAC;AACvC,OAAO,EACL,kBAAkB,EAClB,0BAA0B,GAC3B,MAAM,sBAAsB,CAAC;AAC9B,mBAAmB,aAAa,CAAC;AACjC,OAAO,EAAE,gBAAgB,EAAE,MAAM,aAAa,CAAC;AAC/C,mBAAmB,YAAY,CAAC;AAChC,OAAO,EAAE,mBAAmB,EAAE,MAAM,YAAY,CAAC;AACjD,OAAO,EAAE,mBAAmB,EAAE,qBAAqB,EAAE,MAAM,aAAa,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,MAAM,WAAW,CAAC;AAC9C,OAAO,EAAE,gBAAgB,EAAE,MAAM,kBAAkB,CAAC;AACpD,OAAO,EACL,sBAAsB,EACtB,mBAAmB,EACnB,gBAAgB,GACjB,MAAM,mBAAmB,CAAC;AAC3B,mBAAmB,mBAAmB,CAAC;AACvC,OAAO,EAAE,qBAAqB,EAAE,mBAAmB,EAAE,MAAM,aAAa,CAAC;AACzE,OAAO,EACL,kBAAkB,EAClB,0BAA0B,GAC3B,MAAM,sBAAsB,CAAC;AAC9B,mBAAmB,aAAa,CAAC;AACjC,OAAO,EAAE,gBAAgB,EAAE,MAAM,aAAa,CAAC;AAC/C,mBAAmB,mBAAmB,CAAC;AACvC,mBAAmB,YAAY,CAAC;AAChC,OAAO,EAAE,mBAAmB,EAAE,MAAM,YAAY,CAAC"}
@@ -0,0 +1,13 @@
1
+ import { Transaction, type VersionedTransaction } from "@solana/web3.js";
2
+ import { type ByteArray } from "viem";
3
+ import type { BaseSignerClient } from "./client/base";
4
+ export declare class SolanaSigner {
5
+ private alchemyClient;
6
+ address: string;
7
+ constructor(client: BaseSignerClient);
8
+ addSignature(tx: Transaction | VersionedTransaction): Promise<Transaction | VersionedTransaction>;
9
+ signMessage(message: Uint8Array): Promise<ByteArray>;
10
+ private formatSignatureForSolana;
11
+ private getMessageToSign;
12
+ }
13
+ //# sourceMappingURL=solanaSigner.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"solanaSigner.d.ts","sourceRoot":"","sources":["../../src/solanaSigner.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,WAAW,EACX,KAAK,oBAAoB,EAC1B,MAAM,iBAAiB,CAAC;AACzB,OAAO,EAA+B,KAAK,SAAS,EAAY,MAAM,MAAM,CAAC;AAC7E,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,eAAe,CAAC;AAItD,qBAAa,YAAY;IACvB,OAAO,CAAC,aAAa,CAAmB;IACjC,OAAO,EAAE,MAAM,CAAC;gBAEX,MAAM,EAAE,gBAAgB;IAQ9B,YAAY,CAChB,EAAE,EAAE,WAAW,GAAG,oBAAoB,GACrC,OAAO,CAAC,WAAW,GAAG,oBAAoB,CAAC;IAwBxC,WAAW,CAAC,OAAO,EAAE,UAAU,GAAG,OAAO,CAAC,SAAS,CAAC;IAmB1D,OAAO,CAAC,wBAAwB;IAMhC,OAAO,CAAC,gBAAgB;CASzB"}
@@ -1,2 +1,2 @@
1
- export declare const VERSION = "4.15.3";
1
+ export declare const VERSION = "4.16.0";
2
2
  //# sourceMappingURL=version.d.ts.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@account-kit/signer",
3
- "version": "4.15.3",
3
+ "version": "4.16.0",
4
4
  "description": "Core interfaces and clients for interfacing with the Alchemy Signer API",
5
5
  "author": "Alchemy",
6
6
  "license": "MIT",
@@ -49,8 +49,9 @@
49
49
  "vitest": "^2.0.4"
50
50
  },
51
51
  "dependencies": {
52
- "@aa-sdk/core": "^4.15.3",
53
- "@account-kit/logging": "^4.15.3",
52
+ "@aa-sdk/core": "^4.16.0",
53
+ "@account-kit/logging": "^4.16.0",
54
+ "@solana/web3.js": "^1.98.0",
54
55
  "@turnkey/http": "^2.6.2",
55
56
  "@turnkey/iframe-stamper": "^1.0.0",
56
57
  "@turnkey/viem": "^0.4.8",
@@ -73,5 +74,5 @@
73
74
  "url": "https://github.com/alchemyplatform/aa-sdk/issues"
74
75
  },
75
76
  "homepage": "https://github.com/alchemyplatform/aa-sdk#readme",
76
- "gitHead": "8395e6c7dbaa5b9634dcbc1221137f0c6f553bbf"
77
+ "gitHead": "d0a8f15fb7d10812c29b98f334d9705d46a31e7f"
77
78
  }
package/src/base.ts CHANGED
@@ -16,6 +16,7 @@ import {
16
16
  type TypedDataDefinition,
17
17
  } from "viem";
18
18
  import { toAccount } from "viem/accounts";
19
+ import { hashAuthorization, type Authorization } from "viem/experimental";
19
20
  import type { Mutate, StoreApi } from "zustand";
20
21
  import { subscribeWithSelector } from "zustand/middleware";
21
22
  import { createStore } from "zustand/vanilla";
@@ -27,7 +28,9 @@ import {
27
28
  SessionManager,
28
29
  type SessionManagerParams,
29
30
  } from "./session/manager.js";
31
+ import type { SessionManagerEvents } from "./session/types";
30
32
  import type { AuthParams } from "./signer";
33
+ import { SolanaSigner } from "./solanaSigner.js";
31
34
  import {
32
35
  AlchemySignerStatus,
33
36
  type AlchemySignerEvent,
@@ -35,8 +38,6 @@ import {
35
38
  type ErrorInfo,
36
39
  } from "./types.js";
37
40
  import { assertNever } from "./utils/typeAssertions.js";
38
- import type { SessionManagerEvents } from "./session/types";
39
- import { hashAuthorization, type Authorization } from "viem/experimental";
40
41
 
41
42
  export interface BaseAlchemySignerParams<TClient extends BaseSignerClient> {
42
43
  client: TClient;
@@ -733,6 +734,38 @@ export abstract class BaseAlchemySigner<TClient extends BaseSignerClient>
733
734
  });
734
735
  };
735
736
 
737
+ /**
738
+ * Creates a new instance of `SolanaSigner` using the provided inner value.
739
+ * This requires the signer to be authenticated first
740
+ *
741
+ * @example
742
+ * ```ts
743
+ * import { AlchemyWebSigner } from "@account-kit/signer";
744
+ *
745
+ * const signer = new AlchemyWebSigner({
746
+ * client: {
747
+ * connection: {
748
+ * rpcUrl: "/api/rpc",
749
+ * },
750
+ * iframeConfig: {
751
+ * iframeContainerId: "alchemy-signer-iframe-container",
752
+ * },
753
+ * },
754
+ * });
755
+ *
756
+ * const solanaSigner = signer.toSolanaSigner();
757
+ * ```
758
+ *
759
+ * @returns {SolanaSigner} A new instance of `SolanaSigner`
760
+ */
761
+ experimental_toSolanaSigner = (): SolanaSigner => {
762
+ if (!this.inner.getUser()) {
763
+ throw new NotAuthenticatedError();
764
+ }
765
+
766
+ return new SolanaSigner(this.inner);
767
+ };
768
+
736
769
  private authenticateWithEmail = async (
737
770
  params: Extract<AuthParams, { type: "email" }>
738
771
  ): Promise<User> => {
@@ -317,22 +317,35 @@ export abstract class BaseSignerClient<TExportWalletParams = unknown> {
317
317
  * that result here.
318
318
  *
319
319
  * @param {Hex} msg the hex representation of the bytes to sign
320
+ * @param {string} mode specify if signing should happen for solana or ethereum
320
321
  * @returns {Promise<Hex>} the signature over the raw hex
321
322
  */
322
- public signRawMessage = async (msg: Hex): Promise<Hex> => {
323
+ public signRawMessage = async (
324
+ msg: Hex,
325
+ mode: "SOLANA" | "ETHEREUM" = "ETHEREUM"
326
+ ): Promise<Hex> => {
323
327
  if (!this.user) {
324
328
  throw new NotAuthenticatedError();
325
329
  }
326
330
 
331
+ if (!this.user.solanaAddress && mode === "SOLANA") {
332
+ // TODO: we need to add backwards compatibility for users who signed up before we added Solana support
333
+ throw new Error("No Solana address available for the user");
334
+ }
335
+
327
336
  const stampedRequest = await this.turnkeyClient.stampSignRawPayload({
328
337
  organizationId: this.user.orgId,
329
338
  type: "ACTIVITY_TYPE_SIGN_RAW_PAYLOAD_V2",
330
339
  timestampMs: Date.now().toString(),
331
340
  parameters: {
332
341
  encoding: "PAYLOAD_ENCODING_HEXADECIMAL",
333
- hashFunction: "HASH_FUNCTION_NO_OP",
342
+ hashFunction:
343
+ mode === "ETHEREUM"
344
+ ? "HASH_FUNCTION_NO_OP"
345
+ : "HASH_FUNCTION_NOT_APPLICABLE",
334
346
  payload: msg,
335
- signWith: this.user.address,
347
+ signWith:
348
+ mode === "ETHEREUM" ? this.user.address : this.user.solanaAddress!,
336
349
  },
337
350
  });
338
351
 
@@ -13,6 +13,7 @@ export type User = {
13
13
  orgId: string;
14
14
  userId: string;
15
15
  address: Address;
16
+ solanaAddress?: string;
16
17
  credentialId?: string;
17
18
  idToken?: string;
18
19
  claims?: Record<string, unknown>;
package/src/index.ts CHANGED
@@ -6,12 +6,13 @@ export {
6
6
  OauthFailedError,
7
7
  } from "./client/index.js";
8
8
  export type * from "./client/types.js";
9
+ export { NotAuthenticatedError, OAuthProvidersError } from "./errors.js";
9
10
  export {
10
11
  DEFAULT_SESSION_MS,
11
12
  SessionManagerParamsSchema,
12
13
  } from "./session/manager.js";
13
14
  export type * from "./signer.js";
14
15
  export { AlchemyWebSigner } from "./signer.js";
16
+ export type * from "./solanaSigner.js";
15
17
  export type * from "./types.js";
16
18
  export { AlchemySignerStatus } from "./types.js";
17
- export { OAuthProvidersError, NotAuthenticatedError } from "./errors.js";
@@ -0,0 +1,83 @@
1
+ import {
2
+ PublicKey,
3
+ Transaction,
4
+ type VersionedTransaction,
5
+ } from "@solana/web3.js";
6
+ import { size, slice, toBytes, toHex, type ByteArray, type Hex } from "viem";
7
+ import type { BaseSignerClient } from "./client/base";
8
+ import { NotAuthenticatedError } from "./errors.js";
9
+
10
+ // TODO: I don't want this to be a class so that the flow is closer to how we do this for `toViemAccount`
11
+ export class SolanaSigner {
12
+ private alchemyClient: BaseSignerClient;
13
+ public address: string;
14
+
15
+ constructor(client: BaseSignerClient) {
16
+ this.alchemyClient = client;
17
+ if (!client.getUser()) throw new Error("Must be authenticated!");
18
+
19
+ // TODO: also throw here
20
+ this.address = client.getUser()!.solanaAddress!;
21
+ }
22
+
23
+ async addSignature(
24
+ tx: Transaction | VersionedTransaction
25
+ ): Promise<Transaction | VersionedTransaction> {
26
+ const user = this.alchemyClient.getUser();
27
+ if (!user) {
28
+ throw new NotAuthenticatedError();
29
+ }
30
+
31
+ if (!user.solanaAddress) {
32
+ throw new Error("no solana address");
33
+ }
34
+
35
+ const fromKey = new PublicKey(user.solanaAddress);
36
+ const messageToSign = this.getMessageToSign(tx);
37
+ const signature = await this.alchemyClient.signRawMessage(
38
+ messageToSign,
39
+ "SOLANA"
40
+ );
41
+
42
+ tx.addSignature(
43
+ fromKey,
44
+ Buffer.from(toBytes(this.formatSignatureForSolana(signature)))
45
+ );
46
+ return tx;
47
+ }
48
+
49
+ async signMessage(message: Uint8Array): Promise<ByteArray> {
50
+ const user = this.alchemyClient.getUser();
51
+ if (!user) {
52
+ throw new NotAuthenticatedError();
53
+ }
54
+
55
+ if (!user.solanaAddress) {
56
+ throw new Error("no solana address");
57
+ }
58
+
59
+ const messageToSign = toHex(message);
60
+ const signature = await this.alchemyClient.signRawMessage(
61
+ messageToSign,
62
+ "SOLANA"
63
+ );
64
+
65
+ return toBytes(this.formatSignatureForSolana(signature));
66
+ }
67
+
68
+ private formatSignatureForSolana(signature: Hex): Hex {
69
+ if (size(signature) === 64) return signature;
70
+
71
+ return slice(signature, 0, 64);
72
+ }
73
+
74
+ private getMessageToSign(tx: Transaction | VersionedTransaction): Hex {
75
+ let messageToSign;
76
+ if (tx instanceof Transaction) {
77
+ messageToSign = tx.serializeMessage();
78
+ } else {
79
+ messageToSign = Buffer.from(tx.message.serialize());
80
+ }
81
+ return toHex(messageToSign);
82
+ }
83
+ }
package/src/version.ts CHANGED
@@ -1,3 +1,3 @@
1
1
  // This file is autogenerated by inject-version.ts. Any changes will be
2
2
  // overwritten on commit!
3
- export const VERSION = "4.15.3";
3
+ export const VERSION = "4.16.0";