@rhinestone/1auth 0.6.8 → 0.6.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/README.md +171 -12
  2. package/dist/chunk-GUAI55LL.mjs +179 -0
  3. package/dist/chunk-GUAI55LL.mjs.map +1 -0
  4. package/dist/chunk-IHBVEU33.mjs +20 -0
  5. package/dist/chunk-IHBVEU33.mjs.map +1 -0
  6. package/dist/chunk-IIACVHR3.mjs +28 -0
  7. package/dist/chunk-IIACVHR3.mjs.map +1 -0
  8. package/dist/chunk-N6KE5CII.mjs +72 -0
  9. package/dist/chunk-N6KE5CII.mjs.map +1 -0
  10. package/dist/{chunk-SXISYG2P.mjs → chunk-THKG3FAG.mjs} +137 -255
  11. package/dist/chunk-THKG3FAG.mjs.map +1 -0
  12. package/dist/{client-BrMrhetG.d.mts → client-B_CzDa_I.d.ts} +360 -857
  13. package/dist/{client-BrMrhetG.d.ts → client-F4DnFM8d.d.mts} +360 -857
  14. package/dist/headless.d.mts +109 -0
  15. package/dist/headless.d.ts +109 -0
  16. package/dist/headless.js +467 -0
  17. package/dist/headless.js.map +1 -0
  18. package/dist/headless.mjs +382 -0
  19. package/dist/headless.mjs.map +1 -0
  20. package/dist/index.d.mts +96 -144
  21. package/dist/index.d.ts +96 -144
  22. package/dist/index.js +3212 -756
  23. package/dist/index.js.map +1 -1
  24. package/dist/index.mjs +3010 -705
  25. package/dist/index.mjs.map +1 -1
  26. package/dist/{provider-CDl9wYEc.d.mts → provider-Cd7Ip5L-.d.ts} +6 -5
  27. package/dist/{provider-Dgv533YQ.d.ts → provider-IvYXPMpk.d.mts} +6 -5
  28. package/dist/react.d.mts +42 -2
  29. package/dist/react.d.ts +42 -2
  30. package/dist/react.js +92 -2
  31. package/dist/react.js.map +1 -1
  32. package/dist/react.mjs +66 -1
  33. package/dist/react.mjs.map +1 -1
  34. package/dist/server.d.mts +118 -0
  35. package/dist/server.d.ts +118 -0
  36. package/dist/server.js +356 -0
  37. package/dist/server.js.map +1 -0
  38. package/dist/server.mjs +282 -0
  39. package/dist/server.mjs.map +1 -0
  40. package/dist/types-U_dwxbtS.d.mts +1488 -0
  41. package/dist/types-U_dwxbtS.d.ts +1488 -0
  42. package/dist/verify-BLgZzwmJ.d.ts +150 -0
  43. package/dist/verify-C8-a5c3K.d.mts +150 -0
  44. package/dist/wagmi.d.mts +5 -2
  45. package/dist/wagmi.d.ts +5 -2
  46. package/dist/wagmi.js +138 -43
  47. package/dist/wagmi.js.map +1 -1
  48. package/dist/wagmi.mjs +3 -1
  49. package/dist/wagmi.mjs.map +1 -1
  50. package/package.json +15 -2
  51. package/dist/chunk-SXISYG2P.mjs.map +0 -1
@@ -0,0 +1,118 @@
1
+ import { Address, Hex } from 'viem';
2
+ export { e as encodeWebAuthnSignature, a as hashMessage, v as verifyMessageHash } from './verify-C8-a5c3K.mjs';
3
+ export { W as WebAuthnSignature } from './types-U_dwxbtS.mjs';
4
+ import '@rhinestone/sdk';
5
+
6
+ /**
7
+ * Server-side utilities for JWT sponsorship.
8
+ *
9
+ * The recommended entry point is `createSponsorshipSigner`, a
10
+ * framework-agnostic factory that reads credentials from environment
11
+ * variables and exposes the two operations each sponsorship endpoint
12
+ * needs: `accessToken()` and `extensionToken(intentOp)`.
13
+ *
14
+ * For custom claims or non-standard flows, `createJwtSigner` is exposed as
15
+ * an escape hatch. The implementation lives here instead of re-exporting
16
+ * `@rhinestone/sdk/jwt-server` directly so downstream app builds do not need
17
+ * to resolve the SDK's optional Express adapter surface.
18
+ *
19
+ * @example Next.js App Router
20
+ * ```ts
21
+ * // app/api/sponsorship/access-token/route.ts
22
+ * import { createSponsorshipSigner } from "@rhinestone/1auth/server";
23
+ *
24
+ * const signer = createSponsorshipSigner();
25
+ *
26
+ * export async function GET() {
27
+ * // Guard with your own session/auth before minting.
28
+ * return Response.json({ token: await signer.accessToken() });
29
+ * }
30
+ * ```
31
+ */
32
+
33
+ interface JwtCredentials {
34
+ privateKey: JsonWebKey;
35
+ integratorId: string;
36
+ projectId: string;
37
+ appId: string;
38
+ keyId: string;
39
+ audience?: string;
40
+ }
41
+ interface SponsorshipFilter {
42
+ chain?: (chain: {
43
+ id: number;
44
+ }) => boolean | Promise<boolean>;
45
+ account?: (address: Address) => boolean | Promise<boolean>;
46
+ calls?: (calls: {
47
+ to: Address;
48
+ value: bigint;
49
+ data: Hex;
50
+ }[]) => boolean | Promise<boolean>;
51
+ }
52
+ interface JwtSignerConfig {
53
+ jwt: JwtCredentials;
54
+ shouldSponsor?: SponsorshipFilter;
55
+ }
56
+ declare class SponsorshipDeniedError extends Error {
57
+ constructor();
58
+ }
59
+ /**
60
+ * Sponsorship signer used by the two endpoints the SDK client calls:
61
+ *
62
+ * - `accessToken()` — mints the app's identity token; return as
63
+ * `{ token }` from `GET /sponsorship/access-token`.
64
+ * - `extensionToken(intentOp)` — mints a per-intent sponsorship grant;
65
+ * return as `{ token }` from `POST /sponsorship/extension-token`.
66
+ * Accepts either the JSON-stringified `intentOp` the SDK sends or a
67
+ * pre-parsed object.
68
+ */
69
+ interface SponsorshipSigner {
70
+ accessToken(): Promise<string>;
71
+ extensionToken(intentOp: string | object): Promise<string>;
72
+ }
73
+ interface CreateSponsorshipSignerOptions {
74
+ /** Override all credentials explicitly (skips env lookup). */
75
+ credentials?: JwtCredentials;
76
+ /** Override the env source (defaults to `process.env`). */
77
+ env?: NodeJS.ProcessEnv;
78
+ /** Optional per-intent sponsorship filter (see `@rhinestone/sdk/jwt-server`). */
79
+ shouldSponsor?: SponsorshipFilter;
80
+ }
81
+ interface VerifyOneAuthAccountOptions {
82
+ /** 1auth provider origin, for example `https://passkey.1auth.box`. */
83
+ providerUrl: string;
84
+ /** Smart account address returned by a successful 1auth auth result. */
85
+ address: Address;
86
+ /** Optional app client id forwarded to provider APIs that scope by app. */
87
+ clientId?: string;
88
+ /** Injectable fetch implementation for tests and non-standard runtimes. */
89
+ fetch?: typeof fetch;
90
+ }
91
+ interface VerifiedOneAuthAccount {
92
+ address: Address;
93
+ deployed?: boolean;
94
+ chainId?: number;
95
+ }
96
+ /** Error raised when the provider cannot bind an address to a 1auth account. */
97
+ declare class OneAuthAccountVerificationError extends Error {
98
+ constructor(message: string);
99
+ }
100
+ /**
101
+ * Verify that an address belongs to a 1auth account known by the configured
102
+ * provider. This is intended for server-side app sessions that already have a
103
+ * fresh challenge signature and need to reject arbitrary ERC-1271 contracts.
104
+ */
105
+ declare function verifyOneAuthAccount(options: VerifyOneAuthAccountOptions): Promise<VerifiedOneAuthAccount>;
106
+ /**
107
+ * Create a low-level JWT signer compatible with Rhinestone sponsorship flows.
108
+ *
109
+ * This mirrors the upstream SDK behavior while keeping our public server entry
110
+ * point self-contained for app bundlers.
111
+ */
112
+ declare function createJwtSigner(config: JwtSignerConfig): {
113
+ accessToken: () => Promise<string>;
114
+ getIntentExtensionToken: (intentInput: unknown) => Promise<string>;
115
+ };
116
+ declare function createSponsorshipSigner(options?: CreateSponsorshipSignerOptions): SponsorshipSigner;
117
+
118
+ export { type CreateSponsorshipSignerOptions, type JwtCredentials, type JwtSignerConfig, OneAuthAccountVerificationError, SponsorshipDeniedError, type SponsorshipFilter, type SponsorshipSigner, type VerifiedOneAuthAccount, type VerifyOneAuthAccountOptions, createJwtSigner, createSponsorshipSigner, verifyOneAuthAccount };
@@ -0,0 +1,118 @@
1
+ import { Address, Hex } from 'viem';
2
+ export { e as encodeWebAuthnSignature, a as hashMessage, v as verifyMessageHash } from './verify-BLgZzwmJ.js';
3
+ export { W as WebAuthnSignature } from './types-U_dwxbtS.js';
4
+ import '@rhinestone/sdk';
5
+
6
+ /**
7
+ * Server-side utilities for JWT sponsorship.
8
+ *
9
+ * The recommended entry point is `createSponsorshipSigner`, a
10
+ * framework-agnostic factory that reads credentials from environment
11
+ * variables and exposes the two operations each sponsorship endpoint
12
+ * needs: `accessToken()` and `extensionToken(intentOp)`.
13
+ *
14
+ * For custom claims or non-standard flows, `createJwtSigner` is exposed as
15
+ * an escape hatch. The implementation lives here instead of re-exporting
16
+ * `@rhinestone/sdk/jwt-server` directly so downstream app builds do not need
17
+ * to resolve the SDK's optional Express adapter surface.
18
+ *
19
+ * @example Next.js App Router
20
+ * ```ts
21
+ * // app/api/sponsorship/access-token/route.ts
22
+ * import { createSponsorshipSigner } from "@rhinestone/1auth/server";
23
+ *
24
+ * const signer = createSponsorshipSigner();
25
+ *
26
+ * export async function GET() {
27
+ * // Guard with your own session/auth before minting.
28
+ * return Response.json({ token: await signer.accessToken() });
29
+ * }
30
+ * ```
31
+ */
32
+
33
+ interface JwtCredentials {
34
+ privateKey: JsonWebKey;
35
+ integratorId: string;
36
+ projectId: string;
37
+ appId: string;
38
+ keyId: string;
39
+ audience?: string;
40
+ }
41
+ interface SponsorshipFilter {
42
+ chain?: (chain: {
43
+ id: number;
44
+ }) => boolean | Promise<boolean>;
45
+ account?: (address: Address) => boolean | Promise<boolean>;
46
+ calls?: (calls: {
47
+ to: Address;
48
+ value: bigint;
49
+ data: Hex;
50
+ }[]) => boolean | Promise<boolean>;
51
+ }
52
+ interface JwtSignerConfig {
53
+ jwt: JwtCredentials;
54
+ shouldSponsor?: SponsorshipFilter;
55
+ }
56
+ declare class SponsorshipDeniedError extends Error {
57
+ constructor();
58
+ }
59
+ /**
60
+ * Sponsorship signer used by the two endpoints the SDK client calls:
61
+ *
62
+ * - `accessToken()` — mints the app's identity token; return as
63
+ * `{ token }` from `GET /sponsorship/access-token`.
64
+ * - `extensionToken(intentOp)` — mints a per-intent sponsorship grant;
65
+ * return as `{ token }` from `POST /sponsorship/extension-token`.
66
+ * Accepts either the JSON-stringified `intentOp` the SDK sends or a
67
+ * pre-parsed object.
68
+ */
69
+ interface SponsorshipSigner {
70
+ accessToken(): Promise<string>;
71
+ extensionToken(intentOp: string | object): Promise<string>;
72
+ }
73
+ interface CreateSponsorshipSignerOptions {
74
+ /** Override all credentials explicitly (skips env lookup). */
75
+ credentials?: JwtCredentials;
76
+ /** Override the env source (defaults to `process.env`). */
77
+ env?: NodeJS.ProcessEnv;
78
+ /** Optional per-intent sponsorship filter (see `@rhinestone/sdk/jwt-server`). */
79
+ shouldSponsor?: SponsorshipFilter;
80
+ }
81
+ interface VerifyOneAuthAccountOptions {
82
+ /** 1auth provider origin, for example `https://passkey.1auth.box`. */
83
+ providerUrl: string;
84
+ /** Smart account address returned by a successful 1auth auth result. */
85
+ address: Address;
86
+ /** Optional app client id forwarded to provider APIs that scope by app. */
87
+ clientId?: string;
88
+ /** Injectable fetch implementation for tests and non-standard runtimes. */
89
+ fetch?: typeof fetch;
90
+ }
91
+ interface VerifiedOneAuthAccount {
92
+ address: Address;
93
+ deployed?: boolean;
94
+ chainId?: number;
95
+ }
96
+ /** Error raised when the provider cannot bind an address to a 1auth account. */
97
+ declare class OneAuthAccountVerificationError extends Error {
98
+ constructor(message: string);
99
+ }
100
+ /**
101
+ * Verify that an address belongs to a 1auth account known by the configured
102
+ * provider. This is intended for server-side app sessions that already have a
103
+ * fresh challenge signature and need to reject arbitrary ERC-1271 contracts.
104
+ */
105
+ declare function verifyOneAuthAccount(options: VerifyOneAuthAccountOptions): Promise<VerifiedOneAuthAccount>;
106
+ /**
107
+ * Create a low-level JWT signer compatible with Rhinestone sponsorship flows.
108
+ *
109
+ * This mirrors the upstream SDK behavior while keeping our public server entry
110
+ * point self-contained for app bundlers.
111
+ */
112
+ declare function createJwtSigner(config: JwtSignerConfig): {
113
+ accessToken: () => Promise<string>;
114
+ getIntentExtensionToken: (intentInput: unknown) => Promise<string>;
115
+ };
116
+ declare function createSponsorshipSigner(options?: CreateSponsorshipSignerOptions): SponsorshipSigner;
117
+
118
+ export { type CreateSponsorshipSignerOptions, type JwtCredentials, type JwtSignerConfig, OneAuthAccountVerificationError, SponsorshipDeniedError, type SponsorshipFilter, type SponsorshipSigner, type VerifiedOneAuthAccount, type VerifyOneAuthAccountOptions, createJwtSigner, createSponsorshipSigner, verifyOneAuthAccount };
package/dist/server.js ADDED
@@ -0,0 +1,356 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/server.ts
21
+ var server_exports = {};
22
+ __export(server_exports, {
23
+ OneAuthAccountVerificationError: () => OneAuthAccountVerificationError,
24
+ SponsorshipDeniedError: () => SponsorshipDeniedError,
25
+ createJwtSigner: () => createJwtSigner,
26
+ createSponsorshipSigner: () => createSponsorshipSigner,
27
+ encodeWebAuthnSignature: () => encodeWebAuthnSignature,
28
+ hashMessage: () => hashMessage,
29
+ verifyMessageHash: () => verifyMessageHash,
30
+ verifyOneAuthAccount: () => verifyOneAuthAccount
31
+ });
32
+ module.exports = __toCommonJS(server_exports);
33
+ var import_jose = require("jose");
34
+ var import_viem3 = require("viem");
35
+
36
+ // src/verify.ts
37
+ var import_viem = require("viem");
38
+ var ETHEREUM_MESSAGE_PREFIX = "Ethereum Signed Message:\n";
39
+ function hashMessage(message) {
40
+ const messageBytes = (0, import_viem.toBytes)(message);
41
+ const prefixed = ETHEREUM_MESSAGE_PREFIX + messageBytes.length.toString() + message;
42
+ return (0, import_viem.keccak256)((0, import_viem.toBytes)(prefixed));
43
+ }
44
+ function verifyMessageHash(message, signedHash) {
45
+ if (!signedHash) return false;
46
+ const expectedHash = hashMessage(message);
47
+ return expectedHash.toLowerCase() === signedHash.toLowerCase();
48
+ }
49
+
50
+ // src/walletClient/utils.ts
51
+ var import_viem2 = require("viem");
52
+ var P256_N = BigInt(
53
+ "0xFFFFFFFF00000000FFFFFFFFFFFFFFFFBCE6FAADA7179E84F3B9CAC2FC632551"
54
+ );
55
+ var P256_N_DIV_2 = P256_N / 2n;
56
+ var WEBAUTHN_AUTH_TYPE = {
57
+ type: "tuple",
58
+ components: [
59
+ { type: "bytes", name: "authenticatorData" },
60
+ { type: "string", name: "clientDataJSON" },
61
+ { type: "uint256", name: "challengeIndex" },
62
+ { type: "uint256", name: "typeIndex" },
63
+ { type: "uint256", name: "r" },
64
+ { type: "uint256", name: "s" }
65
+ ]
66
+ };
67
+ function encodeWebAuthnSignature(sig) {
68
+ let s = BigInt(sig.s);
69
+ if (s > P256_N_DIV_2) {
70
+ s = P256_N - s;
71
+ }
72
+ return (0, import_viem2.encodeAbiParameters)([WEBAUTHN_AUTH_TYPE], [
73
+ {
74
+ authenticatorData: sig.authenticatorData,
75
+ clientDataJSON: sig.clientDataJSON,
76
+ challengeIndex: BigInt(sig.challengeIndex),
77
+ typeIndex: BigInt(sig.typeIndex),
78
+ r: BigInt(sig.r),
79
+ s
80
+ }
81
+ ]);
82
+ }
83
+
84
+ // src/server.ts
85
+ var SponsorshipDeniedError = class extends Error {
86
+ constructor() {
87
+ super("Sponsorship denied");
88
+ this.name = "SponsorshipDeniedError";
89
+ }
90
+ };
91
+ var OneAuthAccountVerificationError = class extends Error {
92
+ constructor(message) {
93
+ super(message);
94
+ this.name = "OneAuthAccountVerificationError";
95
+ }
96
+ };
97
+ var ENV_KEYS = {
98
+ privateKey: "RHINESTONE_JWT_PRIVATE_KEY",
99
+ integratorId: "RHINESTONE_INTEGRATOR_ID",
100
+ projectId: "RHINESTONE_PROJECT_ID",
101
+ appId: "RHINESTONE_APP_ID",
102
+ keyId: "RHINESTONE_KEY_ID"
103
+ };
104
+ function accountLookupUrl(providerUrl, address) {
105
+ return new URL(`/api/account/${address.toLowerCase()}`, providerUrl).toString();
106
+ }
107
+ async function parseAccountLookupResponse(response) {
108
+ try {
109
+ return await response.json();
110
+ } catch {
111
+ return null;
112
+ }
113
+ }
114
+ async function verifyOneAuthAccount(options) {
115
+ if (!(0, import_viem3.isAddress)(options.address)) {
116
+ throw new OneAuthAccountVerificationError(
117
+ "A valid 1auth account address is required"
118
+ );
119
+ }
120
+ const fetchImpl = options.fetch ?? globalThis.fetch;
121
+ if (typeof fetchImpl !== "function") {
122
+ throw new OneAuthAccountVerificationError(
123
+ "No fetch implementation is available to verify the 1auth account"
124
+ );
125
+ }
126
+ const url = accountLookupUrl(options.providerUrl, options.address);
127
+ const headers = { accept: "application/json" };
128
+ if (options.clientId) headers["x-client-id"] = options.clientId;
129
+ let response;
130
+ try {
131
+ response = await fetchImpl(url, {
132
+ headers,
133
+ cache: "no-store"
134
+ });
135
+ } catch (error) {
136
+ throw new OneAuthAccountVerificationError(
137
+ `Unable to reach the configured 1auth provider: ${error instanceof Error ? error.message : String(error)}`
138
+ );
139
+ }
140
+ const body = await parseAccountLookupResponse(response);
141
+ if (!response.ok) {
142
+ const message = body && typeof body === "object" && "error" in body ? String(body.error) : response.statusText || "account lookup failed";
143
+ throw new OneAuthAccountVerificationError(
144
+ `Configured 1auth provider did not recognize this account (${response.status}: ${message})`
145
+ );
146
+ }
147
+ const account = body;
148
+ if (!account?.address || !(0, import_viem3.isAddress)(account.address)) {
149
+ throw new OneAuthAccountVerificationError(
150
+ "Configured 1auth provider returned a malformed account record"
151
+ );
152
+ }
153
+ if (account.address.toLowerCase() !== options.address.toLowerCase()) {
154
+ throw new OneAuthAccountVerificationError(
155
+ "Configured 1auth provider returned a different account address"
156
+ );
157
+ }
158
+ return {
159
+ address: account.address,
160
+ deployed: typeof account.deployed === "boolean" ? account.deployed : void 0,
161
+ chainId: typeof account.chainId === "number" ? account.chainId : void 0
162
+ };
163
+ }
164
+ function jcsCanonicalise(value) {
165
+ return serialize(value);
166
+ }
167
+ function serialize(value) {
168
+ if (value === null || value === void 0) {
169
+ return "null";
170
+ }
171
+ switch (typeof value) {
172
+ case "boolean":
173
+ return value ? "true" : "false";
174
+ case "number":
175
+ if (!Number.isFinite(value)) {
176
+ throw new Error(`JCS: non-finite number: ${value}`);
177
+ }
178
+ return Object.is(value, -0) ? "0" : String(value);
179
+ case "string":
180
+ return JSON.stringify(value);
181
+ case "bigint":
182
+ if (value > BigInt(Number.MAX_SAFE_INTEGER) || value < BigInt(-Number.MAX_SAFE_INTEGER)) {
183
+ throw new Error(
184
+ `JCS: BigInt ${value} exceeds safe integer range \u2014 convert to string before calling`
185
+ );
186
+ }
187
+ return String(value);
188
+ default:
189
+ break;
190
+ }
191
+ if (Array.isArray(value)) {
192
+ return `[${value.map((item) => serialize(item)).join(",")}]`;
193
+ }
194
+ const obj = value;
195
+ const members = [];
196
+ for (const key of Object.keys(obj).sort()) {
197
+ const item = obj[key];
198
+ if (item === void 0) continue;
199
+ members.push(`${JSON.stringify(key)}:${serialize(item)}`);
200
+ }
201
+ return `{${members.join(",")}}`;
202
+ }
203
+ async function computeIntentInputDigest(intentInput) {
204
+ const canonical = jcsCanonicalise(intentInput);
205
+ const encoded = new TextEncoder().encode(canonical);
206
+ const hashBuffer = await crypto.subtle.digest("SHA-256", encoded);
207
+ return Array.from(new Uint8Array(hashBuffer)).map((byte) => byte.toString(16).padStart(2, "0")).join("");
208
+ }
209
+ function parseIntentInput(intentInput) {
210
+ if (typeof intentInput !== "object" || intentInput === null) {
211
+ throw new Error("intentInput must be a non-null object");
212
+ }
213
+ const input = intentInput;
214
+ if (typeof input.destinationChainId !== "number") {
215
+ throw new Error("intentInput.destinationChainId must be a number");
216
+ }
217
+ if (typeof input.account !== "object" || input.account === null) {
218
+ throw new Error("intentInput.account must be a non-null object");
219
+ }
220
+ if (typeof input.account.address !== "string") {
221
+ throw new Error("intentInput.account.address must be a string");
222
+ }
223
+ if (!Array.isArray(input.destinationExecutions)) {
224
+ throw new Error("intentInput.destinationExecutions must be an array");
225
+ }
226
+ return {
227
+ chain: { id: input.destinationChainId },
228
+ account: input.account.address,
229
+ calls: input.destinationExecutions.map((execution) => ({
230
+ to: execution.to,
231
+ value: BigInt(execution.value),
232
+ data: execution.data
233
+ }))
234
+ };
235
+ }
236
+ async function shouldSponsor(intentInput, filters) {
237
+ const parsed = parseIntentInput(intentInput);
238
+ if (filters.chain && !await filters.chain(parsed.chain)) {
239
+ return false;
240
+ }
241
+ if (filters.account && !await filters.account(parsed.account)) {
242
+ return false;
243
+ }
244
+ if (filters.calls && !await filters.calls(parsed.calls)) {
245
+ return false;
246
+ }
247
+ return true;
248
+ }
249
+ function pickAlg(jwk) {
250
+ if (jwk.kty === "EC") {
251
+ if (jwk.crv === "P-256") return "ES256";
252
+ if (jwk.crv === "P-384") return "ES384";
253
+ if (jwk.crv === "P-521") return "ES512";
254
+ throw new Error(`Unsupported EC curve: ${jwk.crv}`);
255
+ }
256
+ if (jwk.kty === "RSA") return "RS256";
257
+ throw new Error(`Unsupported JWK kty: ${jwk.kty}`);
258
+ }
259
+ function createJwtSigner(config) {
260
+ const {
261
+ jwt: {
262
+ privateKey,
263
+ integratorId,
264
+ projectId,
265
+ appId,
266
+ keyId,
267
+ audience = "rhinestone-api"
268
+ },
269
+ shouldSponsor: filters
270
+ } = config;
271
+ const alg = pickAlg(privateKey);
272
+ let cachedKey = null;
273
+ async function getKey() {
274
+ if (!cachedKey) {
275
+ cachedKey = await (0, import_jose.importJWK)(privateKey, alg);
276
+ }
277
+ return cachedKey;
278
+ }
279
+ return {
280
+ accessToken: async () => {
281
+ const key = await getKey();
282
+ return new import_jose.SignJWT({ typ: "access", app_id: appId }).setProtectedHeader({ alg, kid: keyId }).setIssuer(integratorId).setSubject(projectId).setAudience(audience).setIssuedAt().setExpirationTime("1h").sign(key);
283
+ },
284
+ getIntentExtensionToken: async (intentInput) => {
285
+ if (filters && !await shouldSponsor(intentInput, filters)) {
286
+ throw new SponsorshipDeniedError();
287
+ }
288
+ const key = await getKey();
289
+ const digest = await computeIntentInputDigest(intentInput);
290
+ return new import_jose.SignJWT({
291
+ typ: "intent_extension",
292
+ app_id: appId,
293
+ jti: crypto.randomUUID(),
294
+ policy: {
295
+ sponsorship: {
296
+ scope: "intent",
297
+ intent_input: { digest }
298
+ }
299
+ }
300
+ }).setProtectedHeader({ alg, kid: keyId }).setIssuer(integratorId).setSubject(projectId).setAudience(audience).setIssuedAt().setExpirationTime("5m").sign(key);
301
+ }
302
+ };
303
+ }
304
+ function readCredentialsFromEnv(env) {
305
+ const missing = [];
306
+ const read = (key) => {
307
+ const value = env[key];
308
+ if (!value) missing.push(key);
309
+ return value ?? "";
310
+ };
311
+ const privateKeyRaw = read(ENV_KEYS.privateKey);
312
+ const integratorId = read(ENV_KEYS.integratorId);
313
+ const projectId = read(ENV_KEYS.projectId);
314
+ const appId = read(ENV_KEYS.appId);
315
+ const keyId = read(ENV_KEYS.keyId);
316
+ if (missing.length > 0) {
317
+ throw new Error(
318
+ `createSponsorshipSigner: missing env var(s): ${missing.join(", ")}`
319
+ );
320
+ }
321
+ let privateKey;
322
+ try {
323
+ privateKey = JSON.parse(privateKeyRaw);
324
+ } catch {
325
+ throw new Error(
326
+ `createSponsorshipSigner: ${ENV_KEYS.privateKey} must be a JSON-encoded JWK`
327
+ );
328
+ }
329
+ return { privateKey, integratorId, projectId, appId, keyId };
330
+ }
331
+ function createSponsorshipSigner(options = {}) {
332
+ const credentials = options.credentials ?? readCredentialsFromEnv(options.env ?? process.env);
333
+ const inner = createJwtSigner({
334
+ jwt: credentials,
335
+ shouldSponsor: options.shouldSponsor
336
+ });
337
+ return {
338
+ accessToken: () => inner.accessToken(),
339
+ extensionToken: (intentOp) => {
340
+ const intentInput = typeof intentOp === "string" ? JSON.parse(intentOp) : intentOp;
341
+ return inner.getIntentExtensionToken(intentInput);
342
+ }
343
+ };
344
+ }
345
+ // Annotate the CommonJS export names for ESM import in node:
346
+ 0 && (module.exports = {
347
+ OneAuthAccountVerificationError,
348
+ SponsorshipDeniedError,
349
+ createJwtSigner,
350
+ createSponsorshipSigner,
351
+ encodeWebAuthnSignature,
352
+ hashMessage,
353
+ verifyMessageHash,
354
+ verifyOneAuthAccount
355
+ });
356
+ //# sourceMappingURL=server.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/server.ts","../src/verify.ts","../src/walletClient/utils.ts"],"sourcesContent":["/**\n * Server-side utilities for JWT sponsorship.\n *\n * The recommended entry point is `createSponsorshipSigner`, a\n * framework-agnostic factory that reads credentials from environment\n * variables and exposes the two operations each sponsorship endpoint\n * needs: `accessToken()` and `extensionToken(intentOp)`.\n *\n * For custom claims or non-standard flows, `createJwtSigner` is exposed as\n * an escape hatch. The implementation lives here instead of re-exporting\n * `@rhinestone/sdk/jwt-server` directly so downstream app builds do not need\n * to resolve the SDK's optional Express adapter surface.\n *\n * @example Next.js App Router\n * ```ts\n * // app/api/sponsorship/access-token/route.ts\n * import { createSponsorshipSigner } from \"@rhinestone/1auth/server\";\n *\n * const signer = createSponsorshipSigner();\n *\n * export async function GET() {\n * // Guard with your own session/auth before minting.\n * return Response.json({ token: await signer.accessToken() });\n * }\n * ```\n */\n\nimport { SignJWT, importJWK } from \"jose\";\nimport { isAddress, type Address, type Hex } from \"viem\";\n\nexport { hashMessage, verifyMessageHash } from \"./verify\";\nexport { encodeWebAuthnSignature } from \"./walletClient/utils\";\nexport type { WebAuthnSignature } from \"./types\";\n\nexport interface JwtCredentials {\n privateKey: JsonWebKey;\n integratorId: string;\n projectId: string;\n appId: string;\n keyId: string;\n audience?: string;\n}\n\nexport interface SponsorshipFilter {\n chain?: (chain: { id: number }) => boolean | Promise<boolean>;\n account?: (address: Address) => boolean | Promise<boolean>;\n calls?: (\n calls: {\n to: Address;\n value: bigint;\n data: Hex;\n }[],\n ) => boolean | Promise<boolean>;\n}\n\nexport interface JwtSignerConfig {\n jwt: JwtCredentials;\n shouldSponsor?: SponsorshipFilter;\n}\n\nexport class SponsorshipDeniedError extends Error {\n constructor() {\n super(\"Sponsorship denied\");\n this.name = \"SponsorshipDeniedError\";\n }\n}\n\n/**\n * Sponsorship signer used by the two endpoints the SDK client calls:\n *\n * - `accessToken()` — mints the app's identity token; return as\n * `{ token }` from `GET /sponsorship/access-token`.\n * - `extensionToken(intentOp)` — mints a per-intent sponsorship grant;\n * return as `{ token }` from `POST /sponsorship/extension-token`.\n * Accepts either the JSON-stringified `intentOp` the SDK sends or a\n * pre-parsed object.\n */\nexport interface SponsorshipSigner {\n accessToken(): Promise<string>;\n extensionToken(intentOp: string | object): Promise<string>;\n}\n\nexport interface CreateSponsorshipSignerOptions {\n /** Override all credentials explicitly (skips env lookup). */\n credentials?: JwtCredentials;\n /** Override the env source (defaults to `process.env`). */\n env?: NodeJS.ProcessEnv;\n /** Optional per-intent sponsorship filter (see `@rhinestone/sdk/jwt-server`). */\n shouldSponsor?: SponsorshipFilter;\n}\n\nexport interface VerifyOneAuthAccountOptions {\n /** 1auth provider origin, for example `https://passkey.1auth.box`. */\n providerUrl: string;\n /** Smart account address returned by a successful 1auth auth result. */\n address: Address;\n /** Optional app client id forwarded to provider APIs that scope by app. */\n clientId?: string;\n /** Injectable fetch implementation for tests and non-standard runtimes. */\n fetch?: typeof fetch;\n}\n\nexport interface VerifiedOneAuthAccount {\n address: Address;\n deployed?: boolean;\n chainId?: number;\n}\n\n/** Error raised when the provider cannot bind an address to a 1auth account. */\nexport class OneAuthAccountVerificationError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"OneAuthAccountVerificationError\";\n }\n}\n\nconst ENV_KEYS = {\n privateKey: \"RHINESTONE_JWT_PRIVATE_KEY\",\n integratorId: \"RHINESTONE_INTEGRATOR_ID\",\n projectId: \"RHINESTONE_PROJECT_ID\",\n appId: \"RHINESTONE_APP_ID\",\n keyId: \"RHINESTONE_KEY_ID\",\n} as const;\n\n/** Build the documented account-lookup URL for a 1auth provider. */\nfunction accountLookupUrl(providerUrl: string, address: Address): string {\n return new URL(`/api/account/${address.toLowerCase()}`, providerUrl).toString();\n}\n\n/** Safely parse a provider account lookup response. */\nasync function parseAccountLookupResponse(response: Response): Promise<unknown> {\n try {\n return await response.json();\n } catch {\n return null;\n }\n}\n\n/**\n * Verify that an address belongs to a 1auth account known by the configured\n * provider. This is intended for server-side app sessions that already have a\n * fresh challenge signature and need to reject arbitrary ERC-1271 contracts.\n */\nexport async function verifyOneAuthAccount(\n options: VerifyOneAuthAccountOptions,\n): Promise<VerifiedOneAuthAccount> {\n if (!isAddress(options.address)) {\n throw new OneAuthAccountVerificationError(\n \"A valid 1auth account address is required\",\n );\n }\n\n const fetchImpl = options.fetch ?? globalThis.fetch;\n if (typeof fetchImpl !== \"function\") {\n throw new OneAuthAccountVerificationError(\n \"No fetch implementation is available to verify the 1auth account\",\n );\n }\n\n const url = accountLookupUrl(options.providerUrl, options.address);\n const headers: HeadersInit = { accept: \"application/json\" };\n if (options.clientId) headers[\"x-client-id\"] = options.clientId;\n\n let response: Response;\n try {\n response = await fetchImpl(url, {\n headers,\n cache: \"no-store\",\n });\n } catch (error) {\n throw new OneAuthAccountVerificationError(\n `Unable to reach the configured 1auth provider: ${\n error instanceof Error ? error.message : String(error)\n }`,\n );\n }\n\n const body = await parseAccountLookupResponse(response);\n if (!response.ok) {\n const message =\n body && typeof body === \"object\" && \"error\" in body\n ? String((body as { error: unknown }).error)\n : response.statusText || \"account lookup failed\";\n throw new OneAuthAccountVerificationError(\n `Configured 1auth provider did not recognize this account (${response.status}: ${message})`,\n );\n }\n\n const account = body as Partial<VerifiedOneAuthAccount> | null;\n if (!account?.address || !isAddress(account.address)) {\n throw new OneAuthAccountVerificationError(\n \"Configured 1auth provider returned a malformed account record\",\n );\n }\n if (account.address.toLowerCase() !== options.address.toLowerCase()) {\n throw new OneAuthAccountVerificationError(\n \"Configured 1auth provider returned a different account address\",\n );\n }\n\n return {\n address: account.address,\n deployed:\n typeof account.deployed === \"boolean\" ? account.deployed : undefined,\n chainId: typeof account.chainId === \"number\" ? account.chainId : undefined,\n };\n}\n\n/**\n * RFC 8785 JSON Canonicalization Scheme (JCS).\n *\n * The digest embedded in extension tokens must be byte-for-byte stable across\n * environments, so we canonicalize JSON before hashing instead of trusting\n * ordinary `JSON.stringify` object key order.\n */\nfunction jcsCanonicalise(value: unknown): string {\n return serialize(value);\n}\n\nfunction serialize(value: unknown): string {\n if (value === null || value === undefined) {\n return \"null\";\n }\n\n switch (typeof value) {\n case \"boolean\":\n return value ? \"true\" : \"false\";\n case \"number\":\n if (!Number.isFinite(value)) {\n throw new Error(`JCS: non-finite number: ${value}`);\n }\n return Object.is(value, -0) ? \"0\" : String(value);\n case \"string\":\n return JSON.stringify(value);\n case \"bigint\":\n if (\n value > BigInt(Number.MAX_SAFE_INTEGER) ||\n value < BigInt(-Number.MAX_SAFE_INTEGER)\n ) {\n throw new Error(\n `JCS: BigInt ${value} exceeds safe integer range — convert to string before calling`,\n );\n }\n return String(value);\n default:\n break;\n }\n\n if (Array.isArray(value)) {\n return `[${value.map((item) => serialize(item)).join(\",\")}]`;\n }\n\n const obj = value as Record<string, unknown>;\n const members: string[] = [];\n for (const key of Object.keys(obj).sort()) {\n const item = obj[key];\n if (item === undefined) continue;\n members.push(`${JSON.stringify(key)}:${serialize(item)}`);\n }\n return `{${members.join(\",\")}}`;\n}\n\n/**\n * Compute the canonical digest embedded in per-intent sponsorship grants.\n */\nasync function computeIntentInputDigest(intentInput: unknown): Promise<string> {\n const canonical = jcsCanonicalise(intentInput);\n const encoded = new TextEncoder().encode(canonical);\n const hashBuffer = await crypto.subtle.digest(\"SHA-256\", encoded);\n return Array.from(new Uint8Array(hashBuffer))\n .map((byte) => byte.toString(16).padStart(2, \"0\"))\n .join(\"\");\n}\n\nfunction parseIntentInput(intentInput: unknown) {\n if (typeof intentInput !== \"object\" || intentInput === null) {\n throw new Error(\"intentInput must be a non-null object\");\n }\n\n const input = intentInput as {\n destinationChainId?: number;\n account?: { address?: string };\n destinationExecutions?: { to: Address; value: string; data: Hex }[];\n };\n\n if (typeof input.destinationChainId !== \"number\") {\n throw new Error(\"intentInput.destinationChainId must be a number\");\n }\n\n if (typeof input.account !== \"object\" || input.account === null) {\n throw new Error(\"intentInput.account must be a non-null object\");\n }\n\n if (typeof input.account.address !== \"string\") {\n throw new Error(\"intentInput.account.address must be a string\");\n }\n\n if (!Array.isArray(input.destinationExecutions)) {\n throw new Error(\"intentInput.destinationExecutions must be an array\");\n }\n\n return {\n chain: { id: input.destinationChainId },\n account: input.account.address as Address,\n calls: input.destinationExecutions.map((execution) => ({\n to: execution.to,\n value: BigInt(execution.value),\n data: execution.data,\n })),\n };\n}\n\nasync function shouldSponsor(\n intentInput: unknown,\n filters: SponsorshipFilter,\n): Promise<boolean> {\n const parsed = parseIntentInput(intentInput);\n if (filters.chain && !(await filters.chain(parsed.chain))) {\n return false;\n }\n if (filters.account && !(await filters.account(parsed.account))) {\n return false;\n }\n if (filters.calls && !(await filters.calls(parsed.calls))) {\n return false;\n }\n return true;\n}\n\nfunction pickAlg(jwk: JsonWebKey): \"ES256\" | \"ES384\" | \"ES512\" | \"RS256\" {\n if (jwk.kty === \"EC\") {\n if (jwk.crv === \"P-256\") return \"ES256\";\n if (jwk.crv === \"P-384\") return \"ES384\";\n if (jwk.crv === \"P-521\") return \"ES512\";\n throw new Error(`Unsupported EC curve: ${jwk.crv}`);\n }\n if (jwk.kty === \"RSA\") return \"RS256\";\n throw new Error(`Unsupported JWK kty: ${jwk.kty}`);\n}\n\n/**\n * Create a low-level JWT signer compatible with Rhinestone sponsorship flows.\n *\n * This mirrors the upstream SDK behavior while keeping our public server entry\n * point self-contained for app bundlers.\n */\nexport function createJwtSigner(config: JwtSignerConfig) {\n const {\n jwt: {\n privateKey,\n integratorId,\n projectId,\n appId,\n keyId,\n audience = \"rhinestone-api\",\n },\n shouldSponsor: filters,\n } = config;\n\n const alg = pickAlg(privateKey);\n let cachedKey: Awaited<ReturnType<typeof importJWK>> | null = null;\n\n async function getKey() {\n if (!cachedKey) {\n cachedKey = await importJWK(privateKey, alg);\n }\n return cachedKey;\n }\n\n return {\n accessToken: async () => {\n const key = await getKey();\n return new SignJWT({ typ: \"access\", app_id: appId })\n .setProtectedHeader({ alg, kid: keyId })\n .setIssuer(integratorId)\n .setSubject(projectId)\n .setAudience(audience)\n .setIssuedAt()\n .setExpirationTime(\"1h\")\n .sign(key);\n },\n getIntentExtensionToken: async (intentInput: unknown) => {\n if (filters && !(await shouldSponsor(intentInput, filters))) {\n throw new SponsorshipDeniedError();\n }\n\n const key = await getKey();\n const digest = await computeIntentInputDigest(intentInput);\n return new SignJWT({\n typ: \"intent_extension\",\n app_id: appId,\n jti: crypto.randomUUID(),\n policy: {\n sponsorship: {\n scope: \"intent\",\n intent_input: { digest },\n },\n },\n })\n .setProtectedHeader({ alg, kid: keyId })\n .setIssuer(integratorId)\n .setSubject(projectId)\n .setAudience(audience)\n .setIssuedAt()\n .setExpirationTime(\"5m\")\n .sign(key);\n },\n };\n}\n\nfunction readCredentialsFromEnv(env: NodeJS.ProcessEnv): JwtCredentials {\n const missing: string[] = [];\n const read = (key: string) => {\n const value = env[key];\n if (!value) missing.push(key);\n return value ?? \"\";\n };\n\n const privateKeyRaw = read(ENV_KEYS.privateKey);\n const integratorId = read(ENV_KEYS.integratorId);\n const projectId = read(ENV_KEYS.projectId);\n const appId = read(ENV_KEYS.appId);\n const keyId = read(ENV_KEYS.keyId);\n\n if (missing.length > 0) {\n throw new Error(\n `createSponsorshipSigner: missing env var(s): ${missing.join(\", \")}`,\n );\n }\n\n let privateKey: JsonWebKey;\n try {\n privateKey = JSON.parse(privateKeyRaw) as JsonWebKey;\n } catch {\n throw new Error(\n `createSponsorshipSigner: ${ENV_KEYS.privateKey} must be a JSON-encoded JWK`,\n );\n }\n\n return { privateKey, integratorId, projectId, appId, keyId };\n}\n\nexport function createSponsorshipSigner(\n options: CreateSponsorshipSignerOptions = {},\n): SponsorshipSigner {\n const credentials =\n options.credentials ?? readCredentialsFromEnv(options.env ?? process.env);\n\n const inner = createJwtSigner({\n jwt: credentials,\n shouldSponsor: options.shouldSponsor,\n });\n\n return {\n accessToken: () => inner.accessToken(),\n extensionToken: (intentOp) => {\n const intentInput =\n typeof intentOp === \"string\" ? JSON.parse(intentOp) : intentOp;\n return inner.getIntentExtensionToken(intentInput);\n },\n };\n}\n","import { keccak256, toBytes } from \"viem\";\n\n/**\n * The EIP-191 prefix used for personal message signing.\n * This is the standard Ethereum message prefix for `personal_sign`.\n */\nexport const ETHEREUM_MESSAGE_PREFIX = \"\\x19Ethereum Signed Message:\\n\";\n\n/**\n * Hash a message with the EIP-191 Ethereum prefix.\n *\n * This is the same hashing function used by the passkey sign dialog.\n * Use this to verify that the `signedHash` returned from `signMessage()`\n * matches your original message.\n *\n * Format: keccak256(\"\\x19Ethereum Signed Message:\\n\" + len + message)\n *\n * @example\n * ```typescript\n * const message = \"Sign in to MyApp\\nTimestamp: 1234567890\";\n * const result = await client.signMessage({ username: 'alice', message });\n *\n * // Verify the hash matches\n * const expectedHash = hashMessage(message);\n * if (result.signedHash === expectedHash) {\n * console.log('Hash matches - signature is for this message');\n * }\n * ```\n */\nexport function hashMessage(message: string): `0x${string}` {\n const messageBytes = toBytes(message);\n const prefixed = ETHEREUM_MESSAGE_PREFIX + messageBytes.length.toString() + message;\n return keccak256(toBytes(prefixed));\n}\n\n/**\n * Verify that a signedHash matches the expected message.\n *\n * This is a convenience wrapper around `hashMessage()` that returns\n * a boolean. For full cryptographic verification of the P256 signature,\n * use on-chain verification via the WebAuthn.sol contract.\n *\n * @example\n * ```typescript\n * const result = await client.signMessage({ username: 'alice', message });\n *\n * if (result.success && verifyMessageHash(message, result.signedHash)) {\n * // The signature is for this exact message\n * // For full verification, verify the P256 signature on-chain or server-side\n * }\n * ```\n */\nexport function verifyMessageHash(\n message: string,\n signedHash: string | undefined\n): boolean {\n if (!signedHash) return false;\n const expectedHash = hashMessage(message);\n return expectedHash.toLowerCase() === signedHash.toLowerCase();\n}\n","import { encodeAbiParameters, keccak256 } from 'viem';\nimport type { Hex } from 'viem';\nimport type { WebAuthnSignature } from '../types';\nimport type { TransactionCall } from './types';\n\n/**\n * P-256 curve order (n)\n * Used for signature malleability normalization\n */\nconst P256_N = BigInt(\n '0xFFFFFFFF00000000FFFFFFFFFFFFFFFFBCE6FAADA7179E84F3B9CAC2FC632551'\n);\nconst P256_N_DIV_2 = P256_N / 2n;\n\n/**\n * WebAuthnAuth struct type for ABI encoding\n */\nconst WEBAUTHN_AUTH_TYPE = {\n type: 'tuple',\n components: [\n { type: 'bytes', name: 'authenticatorData' },\n { type: 'string', name: 'clientDataJSON' },\n { type: 'uint256', name: 'challengeIndex' },\n { type: 'uint256', name: 'typeIndex' },\n { type: 'uint256', name: 'r' },\n { type: 'uint256', name: 's' },\n ],\n} as const;\n\n/**\n * Encode a WebAuthn signature for ERC-1271 verification on-chain\n *\n * @param sig - The WebAuthn signature from the passkey\n * @returns ABI-encoded signature bytes\n */\nexport function encodeWebAuthnSignature(sig: WebAuthnSignature): Hex {\n // Normalize s to prevent signature malleability\n let s = BigInt(sig.s);\n if (s > P256_N_DIV_2) {\n s = P256_N - s;\n }\n\n return encodeAbiParameters([WEBAUTHN_AUTH_TYPE], [\n {\n authenticatorData: sig.authenticatorData as Hex,\n clientDataJSON: sig.clientDataJSON,\n challengeIndex: BigInt(sig.challengeIndex),\n typeIndex: BigInt(sig.typeIndex),\n r: BigInt(sig.r),\n s,\n },\n ]);\n}\n\n/**\n * Hash an array of transaction calls for signing\n *\n * @param calls - Array of transaction calls\n * @returns keccak256 hash of the encoded calls\n */\nexport function hashCalls(calls: TransactionCall[]): Hex {\n const encoded = encodeAbiParameters(\n [\n {\n type: 'tuple[]',\n components: [\n { type: 'address', name: 'to' },\n { type: 'bytes', name: 'data' },\n { type: 'uint256', name: 'value' },\n ],\n },\n ],\n [\n calls.map((c) => ({\n to: c.to,\n data: c.data || '0x',\n value: c.value || 0n,\n })),\n ]\n );\n return keccak256(encoded);\n}\n\n/**\n * Build transaction review display data from calls\n *\n * @param calls - Array of transaction calls\n * @returns TransactionDetails for the signing modal\n */\nexport function buildTransactionReview(calls: TransactionCall[]) {\n return {\n actions: calls.map((call, i) => ({\n type: 'custom' as const,\n label: call.label || `Contract Call ${i + 1}`,\n sublabel: call.sublabel || `To: ${call.to.slice(0, 10)}...${call.to.slice(-8)}`,\n amount: call.value ? `${call.value} wei` : undefined,\n })),\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AA2BA,kBAAmC;AACnC,IAAAA,eAAkD;;;AC5BlD,kBAAmC;AAM5B,IAAM,0BAA0B;AAuBhC,SAAS,YAAY,SAAgC;AAC1D,QAAM,mBAAe,qBAAQ,OAAO;AACpC,QAAM,WAAW,0BAA0B,aAAa,OAAO,SAAS,IAAI;AAC5E,aAAO,2BAAU,qBAAQ,QAAQ,CAAC;AACpC;AAmBO,SAAS,kBACd,SACA,YACS;AACT,MAAI,CAAC,WAAY,QAAO;AACxB,QAAM,eAAe,YAAY,OAAO;AACxC,SAAO,aAAa,YAAY,MAAM,WAAW,YAAY;AAC/D;;;AC3DA,IAAAC,eAA+C;AAS/C,IAAM,SAAS;AAAA,EACb;AACF;AACA,IAAM,eAAe,SAAS;AAK9B,IAAM,qBAAqB;AAAA,EACzB,MAAM;AAAA,EACN,YAAY;AAAA,IACV,EAAE,MAAM,SAAS,MAAM,oBAAoB;AAAA,IAC3C,EAAE,MAAM,UAAU,MAAM,iBAAiB;AAAA,IACzC,EAAE,MAAM,WAAW,MAAM,iBAAiB;AAAA,IAC1C,EAAE,MAAM,WAAW,MAAM,YAAY;AAAA,IACrC,EAAE,MAAM,WAAW,MAAM,IAAI;AAAA,IAC7B,EAAE,MAAM,WAAW,MAAM,IAAI;AAAA,EAC/B;AACF;AAQO,SAAS,wBAAwB,KAA6B;AAEnE,MAAI,IAAI,OAAO,IAAI,CAAC;AACpB,MAAI,IAAI,cAAc;A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