@pepu-chain/sdk 0.2.1 → 0.2.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -2
- package/dist/aa/kernel.cjs +10 -9
- package/dist/aa/kernel.js +5 -4
- package/dist/aa/react-direct.cjs +10 -9
- package/dist/aa/react-direct.cjs.map +1 -1
- package/dist/aa/react-direct.js +5 -4
- package/dist/aa/react-direct.js.map +1 -1
- package/dist/aa/react.cjs +5 -4
- package/dist/aa/react.cjs.map +1 -1
- package/dist/aa/react.js +3 -2
- package/dist/aa/react.js.map +1 -1
- package/dist/aa.cjs +18 -17
- package/dist/aa.js +5 -4
- package/dist/chunk-4GEC7GUU.cjs +283 -0
- package/dist/chunk-4GEC7GUU.cjs.map +1 -0
- package/dist/{chunk-PHM3ZORG.cjs → chunk-4L4CHIXE.cjs} +9 -9
- package/dist/{chunk-PHM3ZORG.cjs.map → chunk-4L4CHIXE.cjs.map} +1 -1
- package/dist/{chunk-A5LP2UCS.cjs → chunk-65Y5UCQ7.cjs} +2 -276
- package/dist/chunk-65Y5UCQ7.cjs.map +1 -0
- package/dist/{chunk-7MNJF2OB.cjs → chunk-DNWWZWUW.cjs} +4 -4
- package/dist/{chunk-7MNJF2OB.cjs.map → chunk-DNWWZWUW.cjs.map} +1 -1
- package/dist/{chunk-D52PADVY.js → chunk-GFKIM7HT.js} +25 -2
- package/dist/chunk-GFKIM7HT.js.map +1 -0
- package/dist/{chunk-IY3ALPUJ.js → chunk-GIZNH65Q.js} +5 -273
- package/dist/chunk-GIZNH65Q.js.map +1 -0
- package/dist/{chunk-WANILJZQ.cjs → chunk-HTCX46RJ.cjs} +25 -2
- package/dist/chunk-HTCX46RJ.cjs.map +1 -0
- package/dist/{chunk-KVG3AYYR.js → chunk-NHPWXIA2.js} +4 -4
- package/dist/{chunk-KVG3AYYR.js.map → chunk-NHPWXIA2.js.map} +1 -1
- package/dist/{chunk-ZB6SVBK4.js → chunk-QIDMFFAQ.js} +4 -4
- package/dist/{chunk-ZB6SVBK4.js.map → chunk-QIDMFFAQ.js.map} +1 -1
- package/dist/{chunk-IB2FSPMJ.js → chunk-QZKUPCUD.js} +3 -3
- package/dist/{chunk-IB2FSPMJ.js.map → chunk-QZKUPCUD.js.map} +1 -1
- package/dist/chunk-RSPAN44L.js +276 -0
- package/dist/chunk-RSPAN44L.js.map +1 -0
- package/dist/{chunk-NVOPDXTA.cjs → chunk-UQH4ZAXD.cjs} +10 -10
- package/dist/{chunk-NVOPDXTA.cjs.map → chunk-UQH4ZAXD.cjs.map} +1 -1
- package/dist/{chunk-BGALSKAF.cjs → chunk-VYMAZVIK.cjs} +4 -4
- package/dist/{chunk-BGALSKAF.cjs.map → chunk-VYMAZVIK.cjs.map} +1 -1
- package/dist/{chunk-F2R473FR.js → chunk-XR5ONV2Y.js} +3 -3
- package/dist/{chunk-F2R473FR.js.map → chunk-XR5ONV2Y.js.map} +1 -1
- package/dist/combo/react.cjs +61 -13
- package/dist/combo/react.cjs.map +1 -1
- package/dist/combo/react.d.cts +14 -2
- package/dist/combo/react.d.ts +14 -2
- package/dist/combo/react.guard.js +1 -1
- package/dist/combo/react.js +58 -11
- package/dist/combo/react.js.map +1 -1
- package/dist/combo.cjs +41 -26
- package/dist/combo.cjs.map +1 -1
- package/dist/combo.d.cts +11 -0
- package/dist/combo.d.ts +11 -0
- package/dist/combo.js +31 -16
- package/dist/combo.js.map +1 -1
- package/dist/index.cjs +10 -9
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +3 -2
- package/dist/index.js.map +1 -1
- package/dist/paymaster.cjs +37 -36
- package/dist/paymaster.cjs.map +1 -1
- package/dist/paymaster.js +3 -2
- package/dist/paymaster.js.map +1 -1
- package/dist/react.cjs +4 -3
- package/dist/react.cjs.map +1 -1
- package/dist/react.js +3 -2
- package/dist/react.js.map +1 -1
- package/dist/session/kernel.cjs +18 -17
- package/dist/session/kernel.js +6 -5
- package/package.json +1 -1
- package/dist/chunk-A5LP2UCS.cjs.map +0 -1
- package/dist/chunk-D52PADVY.js.map +0 -1
- package/dist/chunk-IY3ALPUJ.js.map +0 -1
- package/dist/chunk-WANILJZQ.cjs.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/aa/clients.ts"],"names":[],"mappings":";;;;;;;AAYO,IAAM,eAAA,GAAkB;AAAA,EAC7B,OAAA,EAAS,4CAAA;AAAA,EACT,OAAA,EAAS;AACX;AAGA,IAAM,gBAAA,GAAmB,GAAA;AACzB,IAAM,gBAAA,GAAmB,GAAA;AAWzB,eAAsB,uBACpB,YAAA,EACiE;AACjE,EAAA,MAAM,IAAA,GAAO,MAAM,YAAA,CAAa,kBAAA,EAAmB;AACnD,EAAA,OAAO;AAAA,IACL,YAAA,EAAe,IAAA,CAAK,YAAA,GAAe,gBAAA,GAAoB,gBAAA;AAAA,IACvD,sBAAsB,IAAA,CAAK;AAAA,GAC7B;AACF;AAGO,SAAS,kBAAkB,QAAA,EAA2B;AAC3D,EAAA,MAAM,EAAE,UAAA,EAAW,GAAI,oBAAA,CAAqB,QAAA,KAAa,MAAA,GAAY,EAAC,GAAI,EAAE,UAAA,EAAY,QAAA,EAAU,CAAA;AAClG,EAAA,IAAI,eAAe,IAAA,EAAM;AACvB,IAAA,MAAM,IAAI,eAAA,CAAgB,oBAAA,EAAsB,CAAA,oBAAA,EAAuB,QAAA,CAAS,UAAU,CAAA,oBAAA,CAAA,EAAwB;AAAA,MAChH,IAAA,EAAM;AAAA,KACP,CAAA;AAAA,EACH;AACA,EAAA,OAAO,UAAA;AACT;AAQO,SAAS,mBAAA,CAAoB,UAAmB,KAAA,EAAwB;AAC7E,EAAA,MAAM,EAAE,YAAA,EAAc,gBAAA,EAAiB,GAAI,oBAAA,CAAqB,QAAA,KAAa,MAAA,GAAY,EAAC,GAAI,EAAE,YAAA,EAAc,QAAA,EAAU,CAAA;AACxH,EAAA,IAAI,YAAA,KAAiB,MAAM,OAAO,YAAA;AAClC,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,CAAA,CAAE,OAAA,IAAW,GAAA,EAAK;AAAA,GAC9F;AACF;AAUO,SAAS,wBAAwB,CAAA,EAMtB;AAChB,EAAA,MAAM,MAAA,GAAS,sBAAqB,CAAE,MAAA;AACtC,EAAA,MAAM,YAAA,GAAe,CAAA,CAAE,YAAA,IAAgB,kBAAA,CAAmB,EAAE,KAAA,EAAO,WAAA,EAAa,SAAA,EAAW,IAAA,CAAK,MAAM,CAAA,EAAG,CAAA;AACzG,EAAA,OAAO,mBAAA,CAAoB;AAAA,IACzB,SAAS,CAAA,CAAE,OAAA;AAAA,IACX,KAAA,EAAO,WAAA;AAAA,IACP,MAAA,EAAQ,YAAA;AAAA,IACR,SAAA,EAAW,IAAA,CAAK,iBAAA,CAAkB,CAAA,CAAE,UAAU,CAAC,CAAA;AAAA,IAC/C,GAAI,EAAE,SAAA,GAAY,EAAE,WAAW,CAAA,CAAE,SAAA,KAAc,EAAC;AAAA,IAChD,GAAI,EAAE,gBAAA,GAAmB,EAAE,kBAAkB,CAAA,CAAE,gBAAA,KAAqB,EAAC;AAAA,IACrE,eAAe,EAAE,kBAAA,EAAoB,YAAY,sBAAA,CAAuB,YAAY,CAAA;AAAE,GACvF,CAAA;AACH","file":"chunk-QZKUPCUD.js","sourcesContent":["import { createPublicClient, http } from \"viem\";\nimport type { PublicClient } from \"viem\";\nimport { createBundlerClient, createPaymasterClient } from \"viem/account-abstraction\";\nimport type { BundlerClient, PaymasterClient, SmartAccount } from \"viem/account-abstraction\";\n\nimport { pepuMainnet } from \"../chains.js\";\nimport { PEPU_ENV, resolvePepuEndpoints } from \"../endpoints.js\";\nimport { PepuConfigError } from \"../errors.js\";\nimport type { PaymasterContext } from \"../erc7677.js\";\nimport { buildErc7677Url } from \"../paymaster/api.js\";\n\n/** EntryPoint v0.7, the only version PEPU's bundler and paymaster speak. */\nexport const ENTRY_POINT_V07 = {\n address: \"0x0000000071727De22E5E9d8BAf0edAc6f37da032\",\n version: \"0.7\",\n} as const;\n\n/** Fee headroom numerator/denominator: 12/10 = +20%. */\nconst FEE_HEADROOM_NUM = 12n;\nconst FEE_HEADROOM_DEN = 10n;\n\n/**\n * The Alto-compatible fee estimator: the chain's own `estimateFeesPerGas`,\n * with `maxFeePerGas` x 1.2. Alto does not implement ZeroDev's\n * `zd_getUserOperationGasPrice`, so the default estimator would fail.\n * Ported from `templates/sponsored-session-app/lib/kernel.ts`.\n *\n * @example\n * const fees = await estimatePepuUserOpFees(publicClient);\n */\nexport async function estimatePepuUserOpFees(\n publicClient: Pick<PublicClient, \"estimateFeesPerGas\">,\n): Promise<{ maxFeePerGas: bigint; maxPriorityFeePerGas: bigint }> {\n const fees = await publicClient.estimateFeesPerGas();\n return {\n maxFeePerGas: (fees.maxFeePerGas * FEE_HEADROOM_NUM) / FEE_HEADROOM_DEN,\n maxPriorityFeePerGas: fees.maxPriorityFeePerGas,\n };\n}\n\n/** Resolve the bundler URL or throw `CONFIG_MISSING_ENV` naming the variable. */\nexport function requireBundlerUrl(explicit?: string): string {\n const { bundlerUrl } = resolvePepuEndpoints(explicit === undefined ? {} : { bundlerUrl: explicit });\n if (bundlerUrl === null) {\n throw new PepuConfigError(\"CONFIG_MISSING_ENV\", `No bundler URL. Set ${PEPU_ENV.bundlerUrl} or pass bundlerUrl.`, {\n hint: \"The hosted PEPU bundler is the default; if it was cleared, set PEPU_BUNDLER_URL to https://bundler.pepeunchained.com or your own bundler.\",\n });\n }\n return bundlerUrl;\n}\n\n/**\n * Resolve the complete ERC-7677 paymaster URL or throw `CONFIG_MISSING_ENV`.\n * Order: `explicit` URL, then `PEPU_PAYMASTER_URL`, then `token` (a project client token, built against the\n * paymaster base: the hosted service unless a custom URL is configured). The hosted paymaster has no tokenless\n * ERC-7677 URL, because the token names the project (or free-tier app) that is billed.\n */\nexport function requirePaymasterUrl(explicit?: string, token?: string): string {\n const { paymasterUrl, paymasterBaseUrl } = resolvePepuEndpoints(explicit === undefined ? {} : { paymasterUrl: explicit });\n if (paymasterUrl !== null) return paymasterUrl;\n if (token !== undefined && token.trim() !== \"\" && paymasterBaseUrl !== null) {\n return buildErc7677Url({ baseUrl: paymasterBaseUrl, token });\n }\n throw new PepuConfigError(\"CONFIG_MISSING_ENV\", `No ERC-7677 paymaster URL. Set ${PEPU_ENV.paymasterUrl} or pass paymasterUrl / paymasterToken.`, {\n hint: \"The hosted paymaster (https://paymaster.pepeunchained.com) needs your project's client token: set PEPU_PAYMASTER_URL to https://paymaster.pepeunchained.com/v2/paymaster/<client token>.\",\n });\n}\n\n/**\n * An ERC-7677 paymaster client for PEPU (viem `createPaymasterClient`), using\n * the endpoints registry for the URL. A `context` (for example\n * `buildPaymasterContext({ privyAccessToken })`) is injected into every\n * `pm_getPaymasterStubData` and `pm_getPaymasterData` call unless the caller\n * passes one.\n *\n * @example\n * const paymaster = createPepuPaymasterClient({\n * context: buildPaymasterContext({ privyAccessToken }),\n * });\n */\nexport function createPepuPaymasterClient(\n o: { paymasterUrl?: string; paymasterToken?: string; context?: PaymasterContext } = {},\n): PaymasterClient {\n const client = createPaymasterClient({ transport: http(requirePaymasterUrl(o.paymasterUrl, o.paymasterToken)) });\n const ctx = o.context;\n if (!ctx) return client;\n return {\n ...client,\n getPaymasterData: (p) => client.getPaymasterData({ ...p, context: p.context ?? ctx }),\n getPaymasterStubData: (p) => client.getPaymasterStubData({ ...p, context: p.context ?? ctx }),\n };\n}\n\n/**\n * A viem bundler client for PEPU's bundler, with the fee estimator\n * pre-wired ({@link estimatePepuUserOpFees}).\n *\n * @example\n * const bundler = createPepuBundlerClient({ account, paymaster: createPepuPaymasterClient() });\n * const hash = await bundler.sendUserOperation({ calls: [{ to, data }] });\n */\nexport function createPepuBundlerClient(o: {\n bundlerUrl?: string;\n account: SmartAccount;\n paymaster?: PaymasterClient;\n paymasterContext?: PaymasterContext;\n publicClient?: PublicClient;\n}): BundlerClient {\n const rpcUrl = resolvePepuEndpoints().rpcUrl;\n const publicClient = o.publicClient ?? createPublicClient({ chain: pepuMainnet, transport: http(rpcUrl) });\n return createBundlerClient({\n account: o.account,\n chain: pepuMainnet,\n client: publicClient,\n transport: http(requireBundlerUrl(o.bundlerUrl)),\n ...(o.paymaster ? { paymaster: o.paymaster } : {}),\n ...(o.paymasterContext ? { paymasterContext: o.paymasterContext } : {}),\n userOperation: { estimateFeesPerGas: async () => estimatePepuUserOpFees(publicClient) },\n }) as BundlerClient;\n}\n"]}
|
|
@@ -0,0 +1,276 @@
|
|
|
1
|
+
import { paymasterReasonToError, mapPaymasterReason } from './chunk-GIZNH65Q.js';
|
|
2
|
+
import { PEPU_HOSTED, resolvePepuEndpoints } from './chunk-XC4IBCI2.js';
|
|
3
|
+
import { pepuMainnet } from './chunk-VTQIHMF3.js';
|
|
4
|
+
import { PepuConfigError, PepuPaymasterError } from './chunk-6DSZ4Z2N.js';
|
|
5
|
+
import { createSiweMessage } from 'viem/siwe';
|
|
6
|
+
import { isAddress, toHex } from 'viem';
|
|
7
|
+
|
|
8
|
+
var CLIENT_TOKEN_PREFIX = "ppt_";
|
|
9
|
+
var SERVER_KEY_PREFIX = "ppk_";
|
|
10
|
+
function credentialKind(credential) {
|
|
11
|
+
if (credential.startsWith(CLIENT_TOKEN_PREFIX)) return "client";
|
|
12
|
+
if (credential.startsWith(SERVER_KEY_PREFIX)) return "server";
|
|
13
|
+
return null;
|
|
14
|
+
}
|
|
15
|
+
function trimBase(url) {
|
|
16
|
+
return url.replace(/\/+$/, "");
|
|
17
|
+
}
|
|
18
|
+
function buildErc7677Url(options) {
|
|
19
|
+
const token = options.token.trim();
|
|
20
|
+
if (token === "") {
|
|
21
|
+
throw new PepuConfigError("CONFIG_MISSING_ENV", "buildErc7677Url needs a project client token or server key.");
|
|
22
|
+
}
|
|
23
|
+
if (credentialKind(token) === "server" && globalThis.window !== void 0) {
|
|
24
|
+
throw new PepuConfigError(
|
|
25
|
+
"CONFIG_SERVER_ONLY",
|
|
26
|
+
"Refusing to build an ERC-7677 URL from a server key (ppk_) in a browser: the URL embeds the secret. Use the client token (ppt_)."
|
|
27
|
+
);
|
|
28
|
+
}
|
|
29
|
+
let base;
|
|
30
|
+
try {
|
|
31
|
+
base = new URL(options.baseUrl);
|
|
32
|
+
} catch {
|
|
33
|
+
throw new PepuConfigError("CONFIG_BAD_URL", "buildErc7677Url: baseUrl is not a valid URL.");
|
|
34
|
+
}
|
|
35
|
+
if (base.protocol !== "http:" && base.protocol !== "https:") {
|
|
36
|
+
throw new PepuConfigError("CONFIG_BAD_URL", "buildErc7677Url: baseUrl must be an http(s) URL.");
|
|
37
|
+
}
|
|
38
|
+
const prefix = (options.version ?? 2) === 2 ? "/v2/paymaster/" : "/paymaster/";
|
|
39
|
+
return `${trimBase(options.baseUrl)}${prefix}${encodeURIComponent(token)}`;
|
|
40
|
+
}
|
|
41
|
+
function hostedErc7677Url(token) {
|
|
42
|
+
if (PEPU_HOSTED.paymasterBaseUrl === null) {
|
|
43
|
+
throw new PepuConfigError("CONFIG_MISSING_ENV", "No hosted paymaster base URL is set.");
|
|
44
|
+
}
|
|
45
|
+
return buildErc7677Url({ baseUrl: PEPU_HOSTED.paymasterBaseUrl, token });
|
|
46
|
+
}
|
|
47
|
+
function toQuantity(v) {
|
|
48
|
+
return typeof v === "bigint" ? toHex(v) : v;
|
|
49
|
+
}
|
|
50
|
+
function serializeUserOp(op) {
|
|
51
|
+
const out = {
|
|
52
|
+
sender: op.sender,
|
|
53
|
+
nonce: toQuantity(op.nonce),
|
|
54
|
+
callData: op.callData,
|
|
55
|
+
callGasLimit: toQuantity(op.callGasLimit),
|
|
56
|
+
verificationGasLimit: toQuantity(op.verificationGasLimit),
|
|
57
|
+
preVerificationGas: toQuantity(op.preVerificationGas),
|
|
58
|
+
maxFeePerGas: toQuantity(op.maxFeePerGas),
|
|
59
|
+
maxPriorityFeePerGas: toQuantity(op.maxPriorityFeePerGas)
|
|
60
|
+
};
|
|
61
|
+
if (op.factory !== void 0) out["factory"] = op.factory;
|
|
62
|
+
if (op.factoryData !== void 0) out["factoryData"] = op.factoryData;
|
|
63
|
+
return out;
|
|
64
|
+
}
|
|
65
|
+
function assertApproved(result) {
|
|
66
|
+
if (result.status === "approved") return result;
|
|
67
|
+
throw paymasterReasonToError(result.reason, result.message, result.detail ? { detail: result.detail } : void 0);
|
|
68
|
+
}
|
|
69
|
+
function retryAfter(res) {
|
|
70
|
+
const raw = res.headers.get("retry-after");
|
|
71
|
+
const n = raw === null ? NaN : Number(raw);
|
|
72
|
+
return Number.isFinite(n) ? n : void 0;
|
|
73
|
+
}
|
|
74
|
+
function isRecord(v) {
|
|
75
|
+
return typeof v === "object" && v !== null && !Array.isArray(v);
|
|
76
|
+
}
|
|
77
|
+
function missingBaseUrl() {
|
|
78
|
+
return new PepuConfigError(
|
|
79
|
+
"CONFIG_MISSING_ENV",
|
|
80
|
+
"No paymaster URL configured. Set PEPU_PAYMASTER_URL (or NEXT_PUBLIC_PEPU_PAYMASTER_URL), or pass baseUrl to createPaymasterApi."
|
|
81
|
+
);
|
|
82
|
+
}
|
|
83
|
+
function createPaymasterApi(options = {}) {
|
|
84
|
+
const resolved = options.baseUrl ?? resolvePepuEndpoints(options.env ? { env: options.env } : {}).paymasterBaseUrl;
|
|
85
|
+
if (resolved === null || resolved === void 0 || resolved.trim() === "") throw missingBaseUrl();
|
|
86
|
+
try {
|
|
87
|
+
const u = new URL(resolved);
|
|
88
|
+
if (u.protocol !== "http:" && u.protocol !== "https:") throw new Error("protocol");
|
|
89
|
+
} catch {
|
|
90
|
+
throw new PepuConfigError("CONFIG_BAD_URL", "The paymaster baseUrl is not a valid http(s) URL.");
|
|
91
|
+
}
|
|
92
|
+
const baseUrl = trimBase(resolved.trim());
|
|
93
|
+
const doFetch = options.fetch ?? ((...args) => fetch(...args));
|
|
94
|
+
const timeoutMs = options.timeoutMs ?? 15e3;
|
|
95
|
+
let sessionToken = options.sessionToken ?? null;
|
|
96
|
+
async function send(url, init) {
|
|
97
|
+
try {
|
|
98
|
+
return await doFetch(url, { ...init, signal: AbortSignal.timeout(timeoutMs) });
|
|
99
|
+
} catch (e) {
|
|
100
|
+
const timedOut = e instanceof Error && (e.name === "TimeoutError" || e.name === "AbortError");
|
|
101
|
+
throw new PepuPaymasterError(
|
|
102
|
+
"BUNDLER_UNREACHABLE",
|
|
103
|
+
timedOut ? "The paymaster did not answer in time." : "Could not reach the paymaster service.",
|
|
104
|
+
{ details: { path: new URL(url).pathname.replace(/\/(ppt_|ppk_)[^/]*/, "/<credential>") } }
|
|
105
|
+
);
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
async function readJson(res) {
|
|
109
|
+
const text = await res.text().catch(() => "");
|
|
110
|
+
if (text === "") return void 0;
|
|
111
|
+
try {
|
|
112
|
+
return JSON.parse(text);
|
|
113
|
+
} catch {
|
|
114
|
+
return void 0;
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
function apiError(res, body, quiet) {
|
|
118
|
+
const rec = isRecord(body) ? body : {};
|
|
119
|
+
const errorCode = typeof rec["error"] === "string" ? rec["error"] : void 0;
|
|
120
|
+
const reason = typeof rec["reason"] === "string" ? rec["reason"] : void 0;
|
|
121
|
+
const serverMessage = typeof rec["message"] === "string" && !quiet ? rec["message"] : void 0;
|
|
122
|
+
const details = { status: res.status, error: errorCode, reason, retryAfterSeconds: retryAfter(res) };
|
|
123
|
+
const tagged = reason ?? errorCode;
|
|
124
|
+
let code;
|
|
125
|
+
if (res.status === 401 && errorCode === "unauthenticated") code = "PAYMASTER_SESSION_REQUIRED";
|
|
126
|
+
else if (tagged !== void 0 && mapPaymasterReason(tagged) !== "PAYMASTER_DENIED") code = mapPaymasterReason(tagged);
|
|
127
|
+
else if (res.status === 401 && errorCode !== "login_failed") code = "PAYMASTER_SESSION_REQUIRED";
|
|
128
|
+
else if (res.status === 401) code = "PAYMASTER_DENIED";
|
|
129
|
+
else if (res.status === 429) code = "PAYMASTER_RATE_LIMITED";
|
|
130
|
+
else if (res.status === 403) code = "PAYMASTER_DENIED";
|
|
131
|
+
else code = "PAYMASTER_API_ERROR";
|
|
132
|
+
const label = `Paymaster API ${res.status}${errorCode ? ` ${errorCode}` : ""}${reason && reason !== errorCode ? ` (${reason})` : ""}`;
|
|
133
|
+
return new PepuPaymasterError(code, serverMessage ? `${label}: ${serverMessage}` : `${label}.`, {
|
|
134
|
+
details,
|
|
135
|
+
...res.status === 429 || res.status === 503 ? { retryable: true } : {}
|
|
136
|
+
});
|
|
137
|
+
}
|
|
138
|
+
async function request(method, path, o = {}) {
|
|
139
|
+
const headers = { accept: "application/json" };
|
|
140
|
+
if (o.body !== void 0) headers["content-type"] = "application/json";
|
|
141
|
+
if (o.session) {
|
|
142
|
+
if (!sessionToken) {
|
|
143
|
+
throw new PepuPaymasterError("PAYMASTER_SESSION_REQUIRED", "This call needs a SIWE session. Call loginWithWallet() first.");
|
|
144
|
+
}
|
|
145
|
+
headers["authorization"] = `Bearer ${sessionToken}`;
|
|
146
|
+
}
|
|
147
|
+
let url = `${baseUrl}${path}`;
|
|
148
|
+
if (o.query) {
|
|
149
|
+
const qs = new URLSearchParams();
|
|
150
|
+
for (const [k, v] of Object.entries(o.query)) if (v !== void 0) qs.set(k, String(v));
|
|
151
|
+
const s = qs.toString();
|
|
152
|
+
if (s) url += `?${s}`;
|
|
153
|
+
}
|
|
154
|
+
const res = await send(url, { method, headers, ...o.body !== void 0 ? { body: JSON.stringify(o.body) } : {} });
|
|
155
|
+
const body = await readJson(res);
|
|
156
|
+
if (!res.ok) throw apiError(res, body, o.quietErrors === true);
|
|
157
|
+
return body;
|
|
158
|
+
}
|
|
159
|
+
async function sponsor(path, userOp, auth) {
|
|
160
|
+
if (!auth.apiKey) {
|
|
161
|
+
throw new PepuConfigError("CONFIG_MISSING_ENV", "sponsor needs auth.apiKey (the project server key or client token).");
|
|
162
|
+
}
|
|
163
|
+
const headers = {
|
|
164
|
+
accept: "application/json",
|
|
165
|
+
"content-type": "application/json",
|
|
166
|
+
"x-api-key": auth.apiKey
|
|
167
|
+
};
|
|
168
|
+
if (auth.privyAccessToken) headers["authorization"] = `Bearer ${auth.privyAccessToken}`;
|
|
169
|
+
if (auth.origin) headers["origin"] = auth.origin;
|
|
170
|
+
const res = await send(`${baseUrl}${path}`, {
|
|
171
|
+
method: "POST",
|
|
172
|
+
headers,
|
|
173
|
+
body: JSON.stringify({ userOp: serializeUserOp(userOp) })
|
|
174
|
+
});
|
|
175
|
+
const body = await readJson(res);
|
|
176
|
+
if (isRecord(body) && (body["status"] === "approved" || body["status"] === "denied")) {
|
|
177
|
+
return body;
|
|
178
|
+
}
|
|
179
|
+
throw apiError(res, body, false);
|
|
180
|
+
}
|
|
181
|
+
const projectPath = (id, sub = "") => {
|
|
182
|
+
if (!/^0x[0-9a-fA-F]{64}$/.test(id)) {
|
|
183
|
+
throw new PepuPaymasterError("PAYMASTER_DENIED", "projectId must be a 0x-prefixed 32-byte hex string.");
|
|
184
|
+
}
|
|
185
|
+
return `/v2/projects/${id}${sub}`;
|
|
186
|
+
};
|
|
187
|
+
const v1 = {
|
|
188
|
+
sponsor: async (userOp, auth) => {
|
|
189
|
+
if (!auth.privyAccessToken) {
|
|
190
|
+
throw new PepuPaymasterError(
|
|
191
|
+
"PAYMASTER_IDENTITY_REQUIRED",
|
|
192
|
+
"The v1 /sponsor endpoint requires the user's Privy access token (auth.privyAccessToken)."
|
|
193
|
+
);
|
|
194
|
+
}
|
|
195
|
+
return sponsor("/sponsor", userOp, auth);
|
|
196
|
+
},
|
|
197
|
+
health: async () => {
|
|
198
|
+
const res = await send(`${baseUrl}/health`, { method: "GET" });
|
|
199
|
+
const body = await readJson(res);
|
|
200
|
+
if (!res.ok) throw apiError(res, body, false);
|
|
201
|
+
return isRecord(body) ? body : { status: "ok" };
|
|
202
|
+
},
|
|
203
|
+
erc7677Url: (token) => buildErc7677Url({ baseUrl, token, version: 1 })
|
|
204
|
+
};
|
|
205
|
+
const v2 = {
|
|
206
|
+
sponsor: (userOp, auth) => sponsor("/v2/sponsor", userOp, auth),
|
|
207
|
+
erc7677Url: (token) => buildErc7677Url({ baseUrl, token, version: 2 }),
|
|
208
|
+
config: () => request("GET", "/v2/config"),
|
|
209
|
+
contract: () => request("GET", "/v2/contract"),
|
|
210
|
+
freeTier: () => request("GET", "/v2/free-tier"),
|
|
211
|
+
auth: {
|
|
212
|
+
nonce: () => request("GET", "/v2/auth/nonce"),
|
|
213
|
+
login: async (message, signature) => {
|
|
214
|
+
const r = await request("POST", "/v2/auth/login", { body: { message, signature } });
|
|
215
|
+
sessionToken = r.token;
|
|
216
|
+
return r;
|
|
217
|
+
},
|
|
218
|
+
logout: async () => {
|
|
219
|
+
await request("POST", "/v2/auth/logout", { session: true });
|
|
220
|
+
sessionToken = null;
|
|
221
|
+
}
|
|
222
|
+
},
|
|
223
|
+
me: () => request("GET", "/v2/me", { session: true }),
|
|
224
|
+
loginWithWallet: async (sign, o) => {
|
|
225
|
+
if (!isAddress(o.address, { strict: false })) {
|
|
226
|
+
throw new PepuPaymasterError("PAYMASTER_DENIED", "loginWithWallet: address is not a valid address.");
|
|
227
|
+
}
|
|
228
|
+
const { nonce } = await v2.auth.nonce();
|
|
229
|
+
const now = (o.now ?? Date.now)();
|
|
230
|
+
const message = createSiweMessage({
|
|
231
|
+
address: o.address,
|
|
232
|
+
chainId: o.chainId ?? pepuMainnet.id,
|
|
233
|
+
domain: o.domain,
|
|
234
|
+
nonce,
|
|
235
|
+
uri: o.uri ?? `https://${o.domain}`,
|
|
236
|
+
version: "1",
|
|
237
|
+
statement: o.statement ?? "Sign in to manage your PEPU gas sponsorship project. This does not move any funds.",
|
|
238
|
+
issuedAt: new Date(now),
|
|
239
|
+
expirationTime: new Date(now + (o.lifetimeSeconds ?? 300) * 1e3)
|
|
240
|
+
});
|
|
241
|
+
const signature = await sign(message);
|
|
242
|
+
return v2.auth.login(message, signature);
|
|
243
|
+
},
|
|
244
|
+
getSessionToken: () => sessionToken,
|
|
245
|
+
setSessionToken: (t) => {
|
|
246
|
+
sessionToken = t;
|
|
247
|
+
},
|
|
248
|
+
projects: {
|
|
249
|
+
prepare: (body) => request("POST", "/v2/projects/prepare", { session: true, body }),
|
|
250
|
+
register: (body) => request("POST", "/v2/projects", { session: true, body }),
|
|
251
|
+
list: () => request("GET", "/v2/projects", { session: true }),
|
|
252
|
+
get: async (id) => request("GET", projectPath(id), { session: true }),
|
|
253
|
+
rotateClientToken: async (id) => request("POST", projectPath(id, "/token/rotate"), { session: true }),
|
|
254
|
+
rotateServerKey: async (id) => request("POST", projectPath(id, "/server-key/rotate"), { session: true }),
|
|
255
|
+
updateSettings: async (id, body) => request("PATCH", projectPath(id, "/settings"), { session: true, body }),
|
|
256
|
+
usage: async (id, q = {}) => request("GET", projectPath(id, "/usage"), { session: true, query: { ...q } }),
|
|
257
|
+
events: async (id, q = {}) => request("GET", projectPath(id, "/events"), { session: true, query: { ...q } }),
|
|
258
|
+
allowlist: async (id) => request("GET", projectPath(id, "/allowlist"), { session: true })
|
|
259
|
+
},
|
|
260
|
+
request
|
|
261
|
+
};
|
|
262
|
+
return { baseUrl, v1, v2 };
|
|
263
|
+
}
|
|
264
|
+
function serializeAttestation(a) {
|
|
265
|
+
return {
|
|
266
|
+
appId: a.appId,
|
|
267
|
+
newOwner: a.newOwner,
|
|
268
|
+
nonce: a.nonce.toString(),
|
|
269
|
+
deadline: a.deadline.toString(),
|
|
270
|
+
signature: a.signature
|
|
271
|
+
};
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
export { assertApproved, buildErc7677Url, createPaymasterApi, credentialKind, hostedErc7677Url, serializeAttestation };
|
|
275
|
+
//# sourceMappingURL=chunk-RSPAN44L.js.map
|
|
276
|
+
//# sourceMappingURL=chunk-RSPAN44L.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/paymaster/api.ts"],"names":[],"mappings":";;;;;;;AA8RA,IAAM,mBAAA,GAAsB,MAAA;AAC5B,IAAM,iBAAA,GAAoB,MAAA;AAGnB,SAAS,eAAe,UAAA,EAAgD;AAC7E,EAAA,IAAI,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,EAAS,WAAA,CAAY,EAAA,EAAI,WAAW,CAAA,EAAG,EAAE,OAAA,EAAS,IAAA,EAAM,MAAM,CAAA;AAAA,MAC1G,KAAA,EAAO,OAAO,EAAA,EAAI,CAAA,GAAI,EAAC,KAAM,OAAA,CAAQ,OAAO,WAAA,CAAY,EAAA,EAAI,QAAQ,CAAA,EAAG,EAAE,SAAS,IAAA,EAAM,KAAA,EAAO,EAAE,GAAG,CAAA,IAAK,CAAA;AAAA,MACzG,MAAA,EAAQ,OAAO,EAAA,EAAI,CAAA,GAAI,EAAC,KAAM,OAAA,CAAQ,OAAO,WAAA,CAAY,EAAA,EAAI,SAAS,CAAA,EAAG,EAAE,SAAS,IAAA,EAAM,KAAA,EAAO,EAAE,GAAG,CAAA,IAAK,CAAA;AAAA,MAC3G,SAAA,EAAW,OAAO,EAAA,KAAO,OAAA,CAAQ,KAAA,EAAO,WAAA,CAAY,EAAA,EAAI,YAAY,CAAA,EAAG,EAAE,OAAA,EAAS,IAAA,EAAM;AAAA,KAC1F;AAAA,IACA;AAAA,GACF;AAEA,EAAA,OAAO,EAAE,OAAA,EAAS,EAAA,EAAI,EAAA,EAAG;AAC3B;AAGO,SAAS,qBAAqB,CAAA,EAAmD;AACtF,EAAA,OAAO;AAAA,IACL,OAAO,CAAA,CAAE,KAAA;AAAA,IACT,UAAU,CAAA,CAAE,QAAA;AAAA,IACZ,KAAA,EAAO,CAAA,CAAE,KAAA,CAAM,QAAA,EAAS;AAAA,IACxB,QAAA,EAAU,CAAA,CAAE,QAAA,CAAS,QAAA,EAAS;AAAA,IAC9B,WAAW,CAAA,CAAE;AAAA,GACf;AACF","file":"chunk-RSPAN44L.js","sourcesContent":["import { createSiweMessage } from \"viem/siwe\";\nimport { isAddress, toHex } from \"viem\";\nimport type { Address, Hex } from \"viem\";\n\nimport { pepuMainnet } from \"../chains.js\";\nimport { PEPU_HOSTED, resolvePepuEndpoints } from \"../endpoints.js\";\nimport { PepuConfigError, PepuPaymasterError } from \"../errors.js\";\nimport type { PepuErrorCode } from \"../errors.js\";\nimport type { ProjectClaimAttestation } from \"./onchain.js\";\nimport { mapPaymasterReason, paymasterReasonToError } from \"./reasons.js\";\n\n/**\n * REST client for the PEPU paymaster policy service: v1 (`/sponsor`, ERC-7677 at `/paymaster/<token>`) and\n * v2 (`/v2/*`, tiered, on-chain projects). Isomorphic (plain `fetch`), so it is safe in a browser EXCEPT for\n * the claim attestation call that carries a Privy app secret, which lives in `@pepu-chain/sdk/paymaster/server`.\n *\n * Contract: services/paymaster/policy-service/openapi.yaml and SPONSORSHIP-SPEC.md. Credentials: a server key\n * (`ppk_...`, secret, any wallet) and a client token (`ppt_...`, publishable, bound to allowed origins).\n */\n\n// ---------------------------------------------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------------------------------------------\n\n/** A quantity as the service accepts it: `0x` hex or bigint (converted for you). */\nexport type Quantity = Hex | bigint;\n\n/** The UserOperation fields `POST /sponsor` and `POST /v2/sponsor` read (EntryPoint v0.7, unpacked). */\nexport interface SponsorUserOp {\n sender: Address;\n nonce: Quantity;\n factory?: Address;\n factoryData?: Hex;\n callData: Hex;\n callGasLimit: Quantity;\n verificationGasLimit: Quantity;\n preVerificationGas: Quantity;\n maxFeePerGas: Quantity;\n maxPriorityFeePerGas: Quantity;\n}\n\nexport interface SponsorApproval {\n status: \"approved\";\n chainId: number;\n paymaster: Address;\n paymasterVerificationGasLimit: Hex;\n paymasterPostOpGasLimit: Hex;\n paymasterData: Hex;\n validUntil: number;\n validAfter: number;\n /** EntryPoint's canonical userOpHash. */\n userOpHash: Hex;\n /** v2 only. */\n sponsor?: { kind: \"project\" | \"free\"; sponsorId: Hex; projectKey: string };\n /** v2 only: worst-case cost, decimal wei. */\n maxCostWei?: string;\n}\n\nexport interface SponsorDenial {\n status: \"denied\";\n /** Machine-readable reason, see {@link PAYMASTER_DENIAL_REASONS}. */\n reason: string;\n message: string;\n /** v2: per-tier reasons when both tiers were tried. */\n detail?: { project?: string; free?: string };\n}\n\nexport type SponsorResult = SponsorApproval | SponsorDenial;\n\n/** Credentials for a sponsor call. */\nexport interface SponsorAuth {\n /** The project's server key (`ppk_`) or client token (`ppt_`). Sent as `X-Api-Key`. */\n apiKey: string;\n /** The user's Privy access token. REQUIRED by v1 and by the v2 free tier. Sent as `Authorization: Bearer`. */\n privyAccessToken?: string;\n /** Origin header, for server-side calls with a client token (browsers set it themselves). */\n origin?: string;\n}\n\nexport interface V2LoginResult {\n token: string;\n address: Address;\n /** ISO timestamp. */\n expiresAt: string;\n}\n\nexport type V2ConfigResponse = Record<string, unknown>;\nexport type V2FreeTierInfo = Record<string, unknown>;\n\nexport interface V2ContractInfo {\n address: Address;\n chainId: number;\n entryPoint: Address;\n abi: readonly unknown[];\n}\n\n/** `POST /v2/projects/prepare` response: a transaction for the owner's wallet to send. */\nexport interface PreparedTx {\n chainId: number;\n to: Address;\n data: Hex;\n /** Decimal wei string. */\n value: string;\n function: string;\n description: string;\n}\n\ntype Wei = string;\ntype Bytes32 = Hex;\n\n/** Body of `POST /v2/projects/prepare`. */\nexport type PrepareRequest =\n | { action: \"claimProject\" | \"reclaimProject\"; attestation: SerializedAttestation }\n | { action: \"depositFor\"; projectId: Bytes32; amountWei: Wei }\n | { action: \"executeReclaim\" | \"cancelReclaim\" | \"acceptProjectOwnership\"; projectId: Bytes32 }\n | { action: \"setTargets\"; projectId: Bytes32; targets: Address[]; allowed: boolean }\n | { action: \"setDailyLimit\" | \"setSenderDailyLimit\"; projectId: Bytes32; limitWei: Wei }\n | { action: \"setPaused\"; projectId: Bytes32; paused: boolean }\n | { action: \"proposeProjectOwner\"; projectId: Bytes32; newOwner: Address };\n\n/** Attestation in the service's wire format (decimal strings). */\nexport interface SerializedAttestation {\n appId: string;\n newOwner: Address;\n nonce: string;\n deadline: string;\n signature: Hex;\n}\n\nexport interface RegisterProjectRequest {\n /** Give `projectId` or `appId` (the id is keccak256(appId)). */\n projectId?: Bytes32;\n appId?: string;\n perUserDailyCapWei?: Wei;\n /** Opt in: refuse wallets without a verified Privy token. Default false (any wallet). */\n requireIdentity?: boolean;\n /** Plain origins (scheme://host[:port], http only for localhost). Max 20. None means server-key only. */\n allowedOrigins?: string[];\n}\n\nexport interface RegisterProjectResponse {\n /** Publishable client token (`ppt_...`), shown once. */\n token: string;\n /** ERC-7677 URL embedding the client token. */\n paymasterUrl: string;\n /** SECRET server key (`ppk_...`), shown once. Backend only. */\n serverKey?: string;\n}\n\nexport interface ProjectSettings {\n perUserDailyCapWei?: Wei;\n requireIdentity?: boolean;\n allowedOrigins?: string[];\n}\n\nexport interface ProjectDetail {\n projectId: Bytes32;\n appId: string | null;\n indexed: boolean;\n owner: Address;\n onchain: {\n balance: Wei;\n spendable: Wei;\n outstandingApprovals: Wei;\n paused: boolean;\n dailyLimit: Wei;\n senderDailyLimit: Wei;\n spentToday: Wei;\n dailyRemaining: Wei;\n };\n adminChangeDelaySeconds: number | null;\n allowlist: Address[] | null;\n offchain: Record<string, unknown> | null;\n usage24h: { ops: number; projectFundedWei: Wei; freeTierFundedWei: Wei } | null;\n contract: { address: Address; chainId: number };\n}\n\n/** Options for the low-level request escape hatch. */\nexport interface V2RequestOptions {\n body?: unknown;\n query?: Record<string, string | number | undefined>;\n /** Send the stored SIWE session as a bearer token. Default false. */\n session?: boolean;\n /**\n * Never put the service's message into thrown errors (only the HTTP status and error code). Set for calls whose\n * request body holds a secret.\n */\n quietErrors?: boolean;\n}\n\nexport interface CreatePaymasterApiOptions {\n /**\n * Policy-service base URL (no trailing path). Defaults to `PEPU_PAYMASTER_URL` /\n * `NEXT_PUBLIC_PEPU_PAYMASTER_URL`, then the hosted default once it exists.\n */\n baseUrl?: string;\n /** Fetch implementation (tests, custom agents). Defaults to global `fetch`. */\n fetch?: typeof fetch;\n /** Environment for URL resolution. Defaults to `process.env`. */\n env?: Record<string, string | undefined>;\n /** Request timeout in milliseconds. Default 15000. */\n timeoutMs?: number;\n /** Start with an existing SIWE session token. */\n sessionToken?: string;\n}\n\nexport interface PaymasterApiV1 {\n /** `POST /sponsor`. Needs the user's Privy access token and the app API key. */\n sponsor(userOp: SponsorUserOp, auth: SponsorAuth): Promise<SponsorResult>;\n /** `GET /health`. */\n health(): Promise<{ status: string }>;\n /** ERC-7677 URL for this service (`<base>/paymaster/<token>`). */\n erc7677Url(appToken: string): string;\n}\n\nexport interface PaymasterApiV2 {\n /** `POST /v2/sponsor`. Denials are returned (not thrown); use {@link assertApproved}. */\n sponsor(userOp: SponsorUserOp, auth: SponsorAuth): Promise<SponsorResult>;\n /** ERC-7677 URL for this service (`<base>/v2/paymaster/<token>`). */\n erc7677Url(appToken: string): string;\n config(): Promise<V2ConfigResponse>;\n contract(): Promise<V2ContractInfo>;\n freeTier(): Promise<V2FreeTierInfo>;\n auth: {\n nonce(): Promise<{ nonce: string; expiresAt: string }>;\n /** Stores the returned session token on this client. */\n login(message: string, signature: Hex): Promise<V2LoginResult>;\n logout(): Promise<void>;\n };\n /** `GET /v2/me`: the session address. */\n me(): Promise<{ address: Address }>;\n /**\n * Full SIWE sign-in: nonce, EIP-4361 message, your signature, login. The session lasts 1 hour and is stored\n * on this client.\n */\n loginWithWallet(sign: (message: string) => Promise<Hex>, o: LoginWithWalletOptions): Promise<V2LoginResult>;\n /** Current session token, if signed in. */\n getSessionToken(): string | null;\n setSessionToken(token: string | null): void;\n projects: {\n /** `POST /v2/projects/prepare`: calldata for the owner's wallet. Sends nothing. */\n prepare(request: PrepareRequest): Promise<PreparedTx>;\n /** `POST /v2/projects`: index a claimed project and get its credentials. */\n register(request: RegisterProjectRequest): Promise<RegisterProjectResponse>;\n list(): Promise<{ projects: unknown[]; onchainUnindexed?: unknown[] }>;\n get(projectId: Hex): Promise<ProjectDetail>;\n rotateClientToken(projectId: Hex): Promise<{ token: string; paymasterUrl: string; note?: string }>;\n rotateServerKey(projectId: Hex): Promise<{ serverKey: string; note?: string }>;\n updateSettings(projectId: Hex, settings: ProjectSettings): Promise<Record<string, unknown>>;\n usage(projectId: Hex, q?: { limit?: number; before?: number }): Promise<Record<string, unknown>>;\n events(projectId: Hex, q?: { fromBlock?: number; limit?: number }): Promise<{ projectId: Hex; events: unknown[] }>;\n allowlist(projectId: Hex): Promise<{ projectId: Hex; source: string; targets: Address[] }>;\n };\n /**\n * Low-level call to any `/v2` path, with the same error mapping. Used by `@pepu-chain/sdk/paymaster/server`\n * for `POST /v2/projects/verify`. Prefer the typed methods.\n */\n request<T>(method: \"GET\" | \"POST\" | \"PATCH\", path: string, options?: V2RequestOptions): Promise<T>;\n}\n\nexport interface PaymasterApi {\n /** Resolved base URL, no trailing slash. */\n readonly baseUrl: string;\n v1: PaymasterApiV1;\n v2: PaymasterApiV2;\n}\n\nexport interface LoginWithWalletOptions {\n /** The signing wallet's address. */\n address: Address;\n /** SIWE domain; must be one of the service's `SIWE_DOMAINS` (for example `app.example.com`). */\n domain: string;\n /** SIWE `uri`. Default `https://<domain>`. */\n uri?: string;\n /** Chain id in the message. Default 97741. */\n chainId?: number;\n statement?: string;\n /** Message lifetime in seconds (service maximum is 600 by default). Default 300. */\n lifetimeSeconds?: number;\n now?: () => number;\n}\n\n// ---------------------------------------------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------------------------------------------\n\nconst CLIENT_TOKEN_PREFIX = \"ppt_\";\nconst SERVER_KEY_PREFIX = \"ppk_\";\n\n/** `\"client\"` for `ppt_` tokens, `\"server\"` for `ppk_` keys, otherwise `null`. Never inspects beyond the prefix. */\nexport function credentialKind(credential: string): \"client\" | \"server\" | null {\n if (credential.startsWith(CLIENT_TOKEN_PREFIX)) return \"client\";\n if (credential.startsWith(SERVER_KEY_PREFIX)) return \"server\";\n return null;\n}\n\nfunction trimBase(url: string): string {\n return url.replace(/\\/+$/, \"\");\n}\n\nexport interface BuildErc7677UrlOptions {\n /** Policy-service base URL. */\n baseUrl: string;\n /** Client token (`ppt_`, browser-safe) or server key (`ppk_`, secret). */\n token: string;\n /** Default 2. v1 serves `/paymaster/<token>`, v2 serves `/v2/paymaster/<token>`. */\n version?: 1 | 2;\n}\n\n/**\n * Build the ERC-7677 paymaster URL for a project credential (paste it into a Privy \"Paymaster URL\" or pass it\n * to a viem paymaster client). Refuses a server key (`ppk_`) in a browser, because the URL embeds it.\n *\n * @example\n * ```ts\n * const url = buildErc7677Url({ baseUrl: \"https://paymaster.example.com\", token: \"ppt_abc\" });\n * // https://paymaster.example.com/v2/paymaster/ppt_abc\n * ```\n */\nexport function buildErc7677Url(options: BuildErc7677UrlOptions): string {\n const token = options.token.trim();\n if (token === \"\") {\n throw new PepuConfigError(\"CONFIG_MISSING_ENV\", \"buildErc7677Url needs a project client token or server key.\");\n }\n if (credentialKind(token) === \"server\" && (globalThis as { window?: unknown }).window !== undefined) {\n throw new PepuConfigError(\n \"CONFIG_SERVER_ONLY\",\n \"Refusing to build an ERC-7677 URL from a server key (ppk_) in a browser: the URL embeds the secret. Use the client token (ppt_).\",\n );\n }\n let base: URL;\n try {\n base = new URL(options.baseUrl);\n } catch {\n throw new PepuConfigError(\"CONFIG_BAD_URL\", \"buildErc7677Url: baseUrl is not a valid URL.\");\n }\n if (base.protocol !== \"http:\" && base.protocol !== \"https:\") {\n throw new PepuConfigError(\"CONFIG_BAD_URL\", \"buildErc7677Url: baseUrl must be an http(s) URL.\");\n }\n const prefix = (options.version ?? 2) === 2 ? \"/v2/paymaster/\" : \"/paymaster/\";\n return `${trimBase(options.baseUrl)}${prefix}${encodeURIComponent(token)}`;\n}\n\n/**\n * The hosted ERC-7677 URL for a project credential: `<hosted base>/v2/paymaster/<token>`.\n * Pass the project's client token (`ppt_`, browser-safe); a server key is refused in a browser.\n *\n * @example\n * const url = hostedErc7677Url(\"ppt_abc\");\n * // https://paymaster.pepeunchained.com/v2/paymaster/ppt_abc\n */\nexport function hostedErc7677Url(token: string): string {\n if (PEPU_HOSTED.paymasterBaseUrl === null) {\n throw new PepuConfigError(\"CONFIG_MISSING_ENV\", \"No hosted paymaster base URL is set.\");\n }\n return buildErc7677Url({ baseUrl: PEPU_HOSTED.paymasterBaseUrl, token });\n}\n\nfunction toQuantity(v: Quantity): Hex {\n return typeof v === \"bigint\" ? toHex(v) : v;\n}\n\nfunction serializeUserOp(op: SponsorUserOp): Record<string, string> {\n const out: Record<string, string> = {\n sender: op.sender,\n nonce: toQuantity(op.nonce),\n callData: op.callData,\n callGasLimit: toQuantity(op.callGasLimit),\n verificationGasLimit: toQuantity(op.verificationGasLimit),\n preVerificationGas: toQuantity(op.preVerificationGas),\n maxFeePerGas: toQuantity(op.maxFeePerGas),\n maxPriorityFeePerGas: toQuantity(op.maxPriorityFeePerGas),\n };\n if (op.factory !== undefined) out[\"factory\"] = op.factory;\n if (op.factoryData !== undefined) out[\"factoryData\"] = op.factoryData;\n return out;\n}\n\n/**\n * Turn a sponsor result into the approval, or throw the mapped {@link PepuPaymasterError}\n * (`project_not_claimed_onchain` becomes `PAYMASTER_PROJECT_NOT_CLAIMED`, and so on).\n *\n * @example\n * ```ts\n * const approval = assertApproved(await api.v2.sponsor(userOp, { apiKey }));\n * ```\n */\nexport function assertApproved(result: SponsorResult): SponsorApproval {\n if (result.status === \"approved\") return result;\n throw paymasterReasonToError(result.reason, result.message, result.detail ? { detail: result.detail } : undefined);\n}\n\n/** Pull `retryAfterSeconds` out of a Retry-After header. */\nfunction retryAfter(res: Response): number | undefined {\n const raw = res.headers.get(\"retry-after\");\n const n = raw === null ? NaN : Number(raw);\n return Number.isFinite(n) ? n : undefined;\n}\n\nfunction isRecord(v: unknown): v is Record<string, unknown> {\n return typeof v === \"object\" && v !== null && !Array.isArray(v);\n}\n\nfunction missingBaseUrl(): PepuConfigError {\n return new PepuConfigError(\n \"CONFIG_MISSING_ENV\",\n \"No paymaster URL configured. Set PEPU_PAYMASTER_URL (or NEXT_PUBLIC_PEPU_PAYMASTER_URL), or pass baseUrl to createPaymasterApi.\",\n );\n}\n\n// ---------------------------------------------------------------------------------------------------------------\n// Client\n// ---------------------------------------------------------------------------------------------------------------\n\n/**\n * Create the paymaster REST client.\n *\n * @example\n * ```ts\n * const api = createPaymasterApi({ baseUrl: \"https://paymaster.example.com\" });\n * const free = await api.v2.freeTier();\n * const result = await api.v2.sponsor(userOp, { apiKey: process.env.PEPU_SERVER_KEY!, privyAccessToken });\n * if (result.status === \"denied\") console.log(result.reason);\n * ```\n */\nexport function createPaymasterApi(options: CreatePaymasterApiOptions = {}): PaymasterApi {\n const resolved = options.baseUrl ?? resolvePepuEndpoints(options.env ? { env: options.env } : {}).paymasterBaseUrl;\n if (resolved === null || resolved === undefined || resolved.trim() === \"\") throw missingBaseUrl();\n try {\n const u = new URL(resolved);\n if (u.protocol !== \"http:\" && u.protocol !== \"https:\") throw new Error(\"protocol\");\n } catch {\n throw new PepuConfigError(\"CONFIG_BAD_URL\", \"The paymaster baseUrl is not a valid http(s) URL.\");\n }\n const baseUrl = trimBase(resolved.trim());\n const doFetch = options.fetch ?? ((...args: Parameters<typeof fetch>) => fetch(...args));\n const timeoutMs = options.timeoutMs ?? 15_000;\n let sessionToken: string | null = options.sessionToken ?? null;\n\n /** Fetch with timeout; network failures become BUNDLER_UNREACHABLE without echoing request details. */\n async function send(url: string, init: RequestInit): Promise<Response> {\n try {\n return await doFetch(url, { ...init, signal: AbortSignal.timeout(timeoutMs) });\n } catch (e) {\n const timedOut = e instanceof Error && (e.name === \"TimeoutError\" || e.name === \"AbortError\");\n throw new PepuPaymasterError(\n \"BUNDLER_UNREACHABLE\",\n timedOut ? \"The paymaster did not answer in time.\" : \"Could not reach the paymaster service.\",\n { details: { path: new URL(url).pathname.replace(/\\/(ppt_|ppk_)[^/]*/, \"/<credential>\") } },\n );\n }\n }\n\n async function readJson(res: Response): Promise<unknown> {\n const text = await res.text().catch(() => \"\");\n if (text === \"\") return undefined;\n try {\n return JSON.parse(text) as unknown;\n } catch {\n return undefined;\n }\n }\n\n function apiError(res: Response, body: unknown, quiet: boolean): PepuPaymasterError {\n const rec = isRecord(body) ? body : {};\n const errorCode = typeof rec[\"error\"] === \"string\" ? rec[\"error\"] : undefined;\n const reason = typeof rec[\"reason\"] === \"string\" ? rec[\"reason\"] : undefined;\n const serverMessage = typeof rec[\"message\"] === \"string\" && !quiet ? rec[\"message\"] : undefined;\n const details = { status: res.status, error: errorCode, reason, retryAfterSeconds: retryAfter(res) };\n const tagged = reason ?? errorCode;\n let code: PepuErrorCode;\n if (res.status === 401 && errorCode === \"unauthenticated\") code = \"PAYMASTER_SESSION_REQUIRED\";\n else if (tagged !== undefined && mapPaymasterReason(tagged) !== \"PAYMASTER_DENIED\") code = mapPaymasterReason(tagged);\n else if (res.status === 401 && errorCode !== \"login_failed\") code = \"PAYMASTER_SESSION_REQUIRED\";\n else if (res.status === 401) code = \"PAYMASTER_DENIED\";\n else if (res.status === 429) code = \"PAYMASTER_RATE_LIMITED\";\n else if (res.status === 403) code = \"PAYMASTER_DENIED\";\n else code = \"PAYMASTER_API_ERROR\";\n const label = `Paymaster API ${res.status}${errorCode ? ` ${errorCode}` : \"\"}${reason && reason !== errorCode ? ` (${reason})` : \"\"}`;\n return new PepuPaymasterError(code, serverMessage ? `${label}: ${serverMessage}` : `${label}.`, {\n details,\n ...(res.status === 429 || res.status === 503 ? { retryable: true } : {}),\n });\n }\n\n async function request<T>(method: \"GET\" | \"POST\" | \"PATCH\", path: string, o: V2RequestOptions = {}): Promise<T> {\n const headers: Record<string, string> = { accept: \"application/json\" };\n if (o.body !== undefined) headers[\"content-type\"] = \"application/json\";\n if (o.session) {\n if (!sessionToken) {\n throw new PepuPaymasterError(\"PAYMASTER_SESSION_REQUIRED\", \"This call needs a SIWE session. Call loginWithWallet() first.\");\n }\n headers[\"authorization\"] = `Bearer ${sessionToken}`;\n }\n let url = `${baseUrl}${path}`;\n if (o.query) {\n const qs = new URLSearchParams();\n for (const [k, v] of Object.entries(o.query)) if (v !== undefined) qs.set(k, String(v));\n const s = qs.toString();\n if (s) url += `?${s}`;\n }\n const res = await send(url, { method, headers, ...(o.body !== undefined ? { body: JSON.stringify(o.body) } : {}) });\n const body = await readJson(res);\n if (!res.ok) throw apiError(res, body, o.quietErrors === true);\n return body as T;\n }\n\n async function sponsor(path: string, userOp: SponsorUserOp, auth: SponsorAuth): Promise<SponsorResult> {\n if (!auth.apiKey) {\n throw new PepuConfigError(\"CONFIG_MISSING_ENV\", \"sponsor needs auth.apiKey (the project server key or client token).\");\n }\n const headers: Record<string, string> = {\n accept: \"application/json\",\n \"content-type\": \"application/json\",\n \"x-api-key\": auth.apiKey,\n };\n if (auth.privyAccessToken) headers[\"authorization\"] = `Bearer ${auth.privyAccessToken}`;\n if (auth.origin) headers[\"origin\"] = auth.origin;\n const res = await send(`${baseUrl}${path}`, {\n method: \"POST\",\n headers,\n body: JSON.stringify({ userOp: serializeUserOp(userOp) }),\n });\n const body = await readJson(res);\n if (isRecord(body) && (body[\"status\"] === \"approved\" || body[\"status\"] === \"denied\")) {\n return body as unknown as SponsorResult;\n }\n throw apiError(res, body, false);\n }\n\n const projectPath = (id: Hex, sub = \"\"): string => {\n if (!/^0x[0-9a-fA-F]{64}$/.test(id)) {\n throw new PepuPaymasterError(\"PAYMASTER_DENIED\", \"projectId must be a 0x-prefixed 32-byte hex string.\");\n }\n return `/v2/projects/${id}${sub}`;\n };\n\n const v1: PaymasterApiV1 = {\n sponsor: async (userOp, auth) => {\n if (!auth.privyAccessToken) {\n throw new PepuPaymasterError(\n \"PAYMASTER_IDENTITY_REQUIRED\",\n \"The v1 /sponsor endpoint requires the user's Privy access token (auth.privyAccessToken).\",\n );\n }\n return sponsor(\"/sponsor\", userOp, auth);\n },\n health: async () => {\n const res = await send(`${baseUrl}/health`, { method: \"GET\" });\n const body = await readJson(res);\n if (!res.ok) throw apiError(res, body, false);\n return (isRecord(body) ? body : { status: \"ok\" }) as { status: string };\n },\n erc7677Url: (token) => buildErc7677Url({ baseUrl, token, version: 1 }),\n };\n\n const v2: PaymasterApiV2 = {\n sponsor: (userOp, auth) => sponsor(\"/v2/sponsor\", userOp, auth),\n erc7677Url: (token) => buildErc7677Url({ baseUrl, token, version: 2 }),\n config: () => request(\"GET\", \"/v2/config\"),\n contract: () => request(\"GET\", \"/v2/contract\"),\n freeTier: () => request(\"GET\", \"/v2/free-tier\"),\n auth: {\n nonce: () => request(\"GET\", \"/v2/auth/nonce\"),\n login: async (message, signature) => {\n const r = await request<V2LoginResult>(\"POST\", \"/v2/auth/login\", { body: { message, signature } });\n sessionToken = r.token;\n return r;\n },\n logout: async () => {\n await request(\"POST\", \"/v2/auth/logout\", { session: true });\n sessionToken = null;\n },\n },\n me: () => request(\"GET\", \"/v2/me\", { session: true }),\n loginWithWallet: async (sign, o) => {\n if (!isAddress(o.address, { strict: false })) {\n throw new PepuPaymasterError(\"PAYMASTER_DENIED\", \"loginWithWallet: address is not a valid address.\");\n }\n const { nonce } = await v2.auth.nonce();\n const now = (o.now ?? Date.now)();\n const message = createSiweMessage({\n address: o.address,\n chainId: o.chainId ?? pepuMainnet.id,\n domain: o.domain,\n nonce,\n uri: o.uri ?? `https://${o.domain}`,\n version: \"1\",\n statement: o.statement ?? \"Sign in to manage your PEPU gas sponsorship project. This does not move any funds.\",\n issuedAt: new Date(now),\n expirationTime: new Date(now + (o.lifetimeSeconds ?? 300) * 1000),\n });\n const signature = await sign(message);\n return v2.auth.login(message, signature);\n },\n getSessionToken: () => sessionToken,\n setSessionToken: (t) => {\n sessionToken = t;\n },\n projects: {\n prepare: (body) => request(\"POST\", \"/v2/projects/prepare\", { session: true, body }),\n register: (body) => request(\"POST\", \"/v2/projects\", { session: true, body }),\n list: () => request(\"GET\", \"/v2/projects\", { session: true }),\n get: async (id) => request(\"GET\", projectPath(id), { session: true }),\n rotateClientToken: async (id) => request(\"POST\", projectPath(id, \"/token/rotate\"), { session: true }),\n rotateServerKey: async (id) => request(\"POST\", projectPath(id, \"/server-key/rotate\"), { session: true }),\n updateSettings: async (id, body) => request(\"PATCH\", projectPath(id, \"/settings\"), { session: true, body }),\n usage: async (id, q = {}) => request(\"GET\", projectPath(id, \"/usage\"), { session: true, query: { ...q } }),\n events: async (id, q = {}) => request(\"GET\", projectPath(id, \"/events\"), { session: true, query: { ...q } }),\n allowlist: async (id) => request(\"GET\", projectPath(id, \"/allowlist\"), { session: true }),\n },\n request,\n };\n\n return { baseUrl, v1, v2 };\n}\n\n/** Serialize a typed attestation into the wire format for `projects.prepare`. */\nexport function serializeAttestation(a: ProjectClaimAttestation): SerializedAttestation {\n return {\n appId: a.appId,\n newOwner: a.newOwner,\n nonce: a.nonce.toString(),\n deadline: a.deadline.toString(),\n signature: a.signature,\n };\n}\n"]}
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
|
-
var
|
|
3
|
+
var chunkDNWWZWUW_cjs = require('./chunk-DNWWZWUW.cjs');
|
|
4
4
|
var chunkAJS4UFQX_cjs = require('./chunk-AJS4UFQX.cjs');
|
|
5
|
-
var
|
|
5
|
+
var chunkHTCX46RJ_cjs = require('./chunk-HTCX46RJ.cjs');
|
|
6
6
|
var chunk4GINFJO6_cjs = require('./chunk-4GINFJO6.cjs');
|
|
7
7
|
var chunkVF3D6KLQ_cjs = require('./chunk-VF3D6KLQ.cjs');
|
|
8
8
|
var chunkDPCZJLB3_cjs = require('./chunk-DPCZJLB3.cjs');
|
|
@@ -20,11 +20,11 @@ function defaultPublicClient() {
|
|
|
20
20
|
async function toPepuKernelAccount(p) {
|
|
21
21
|
const sudo = await ecdsaValidator.signerToEcdsaValidator(zd(p.publicClient), {
|
|
22
22
|
signer: p.owner,
|
|
23
|
-
entryPoint:
|
|
23
|
+
entryPoint: chunkDNWWZWUW_cjs.ENTRY_POINT_V07,
|
|
24
24
|
kernelVersion: KERNEL_VERSION
|
|
25
25
|
});
|
|
26
26
|
return sdk.createKernelAccount(zd(p.publicClient), {
|
|
27
|
-
entryPoint:
|
|
27
|
+
entryPoint: chunkDNWWZWUW_cjs.ENTRY_POINT_V07,
|
|
28
28
|
kernelVersion: KERNEL_VERSION,
|
|
29
29
|
plugins: { sudo, ...p.plugins?.regular ? { regular: p.plugins.regular } : {} },
|
|
30
30
|
...p.index !== void 0 ? { index: p.index } : {}
|
|
@@ -50,7 +50,7 @@ async function getKernelAddress(publicClient, owner) {
|
|
|
50
50
|
}
|
|
51
51
|
function createPepuSponsoredClient(p) {
|
|
52
52
|
const publicClient = p.publicClient ?? defaultPublicClient();
|
|
53
|
-
const paymaster =
|
|
53
|
+
const paymaster = chunkDNWWZWUW_cjs.createPepuPaymasterClient({
|
|
54
54
|
...p.paymasterUrl !== void 0 ? { paymasterUrl: p.paymasterUrl } : {},
|
|
55
55
|
...p.paymasterToken !== void 0 ? { paymasterToken: p.paymasterToken } : {},
|
|
56
56
|
...p.paymasterContext ? { context: p.paymasterContext } : {}
|
|
@@ -59,9 +59,9 @@ function createPepuSponsoredClient(p) {
|
|
|
59
59
|
account: p.account,
|
|
60
60
|
chain: chunkDPCZJLB3_cjs.pepuMainnet,
|
|
61
61
|
client: zd(publicClient),
|
|
62
|
-
bundlerTransport: viem.http(
|
|
62
|
+
bundlerTransport: viem.http(chunkDNWWZWUW_cjs.requireBundlerUrl(p.bundlerUrl)),
|
|
63
63
|
paymaster,
|
|
64
|
-
userOperation: { estimateFeesPerGas: async () =>
|
|
64
|
+
userOperation: { estimateFeesPerGas: async () => chunkDNWWZWUW_cjs.estimatePepuUserOpFees(publicClient) }
|
|
65
65
|
});
|
|
66
66
|
}
|
|
67
67
|
async function sendSponsored(p) {
|
|
@@ -82,7 +82,7 @@ async function sendSponsored(p) {
|
|
|
82
82
|
explorerUrl: chunk4GINFJO6_cjs.txUrl(chunkDPCZJLB3_cjs.pepuMainnet, transactionHash)
|
|
83
83
|
};
|
|
84
84
|
} catch (e) {
|
|
85
|
-
throw
|
|
85
|
+
throw chunkHTCX46RJ_cjs.describeUserOpFailure(e);
|
|
86
86
|
}
|
|
87
87
|
}
|
|
88
88
|
|
|
@@ -91,5 +91,5 @@ exports.createPepuSponsoredClient = createPepuSponsoredClient;
|
|
|
91
91
|
exports.getKernelAddress = getKernelAddress;
|
|
92
92
|
exports.sendSponsored = sendSponsored;
|
|
93
93
|
exports.toPepuKernelAccount = toPepuKernelAccount;
|
|
94
|
-
//# sourceMappingURL=chunk-
|
|
95
|
-
//# sourceMappingURL=chunk-
|
|
94
|
+
//# sourceMappingURL=chunk-UQH4ZAXD.cjs.map
|
|
95
|
+
//# sourceMappingURL=chunk-UQH4ZAXD.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/aa/kernel.ts"],"names":["constants","createPublicClient","pepuMainnet","http","resolvePepuEndpoints","signerToEcdsaValidator","ENTRY_POINT_V07","createKernelAccount","createPepuPaymasterClient","createKernelAccountClient","requireBundlerUrl","estimatePepuUserOpFees","normalizeCalls","txUrl","describeUserOpFailure"],"mappings":";;;;;;;;;;;;AAiCO,IAAM,iBAAiBA,aAAA,CAAU;AAUxC,SAAS,GAAG,MAAA,EAAqC;AAC/C,EAAA,OAAO,MAAA;AACT;AAUA,SAAS,mBAAA,GAAoC;AAC3C,EAAA,OAAOC,uBAAA,CAAmB,EAAE,KAAA,EAAOC,6BAAA,EAAa,SAAA,EAAWC,UAAKC,sCAAA,EAAqB,CAAE,MAAM,CAAA,EAAG,CAAA;AAClG;AAWA,eAAsB,oBAAoB,CAAA,EAUV;AAC9B,EAAA,MAAM,OAAO,MAAMC,qCAAA,CAAuB,EAAA,CAAG,CAAA,CAAE,YAAY,CAAA,EAAG;AAAA,IAC5D,QAAQ,CAAA,CAAE,KAAA;AAAA,IACV,UAAA,EAAYC,iCAAA;AAAA,IACZ,aAAA,EAAe;AAAA,GAChB,CAAA;AACD,EAAA,OAAOC,uBAAA,CAAoB,EAAA,CAAG,CAAA,CAAE,YAAY,CAAA,EAAG;AAAA,IAC7C,UAAA,EAAYD,iCAAA;AAAA,IACZ,aAAA,EAAe,cAAA;AAAA,IACf,OAAA,EAAS,EAAE,IAAA,EAAM,GAAI,EAAE,OAAA,EAAS,OAAA,GAAU,EAAE,OAAA,EAAS,CAAA,CAA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unk-NVOPDXTA.cjs","sourcesContent":["/**\n * @pepu-chain/sdk/aa/kernel: Kernel v3.1 smart account plus sponsored-send\n * helpers for the \"direct\" transport (your own bundler and paymaster URLs).\n * Needs the optional peers `@zerodev/sdk` and `@zerodev/ecdsa-validator`.\n *\n * This is the only module in the SDK (with `session/kernel` and `combo`) that\n * imports ZeroDev. Ported from `templates/sponsored-session-app/lib/kernel.ts`\n * (Kernel v3.1 build, 20% fee headroom because Alto lacks\n * `zd_getUserOperationGasPrice`).\n *\n * Session keys: `toPepuKernelAccount` takes an optional `plugins.regular`\n * validator, which is the plug point WP-B6 (`/session/kernel`, `/combo`) uses\n * to add a permission validator on top of the ECDSA root.\n */\nimport { signerToEcdsaValidator } from \"@zerodev/ecdsa-validator\";\nimport { constants, createKernelAccount, createKernelAccountClient } from \"@zerodev/sdk\";\nimport type { Signer } from \"@zerodev/sdk/types\";\nimport { createPublicClient, http } from \"viem\";\nimport type { Address, Hex, LocalAccount, PublicClient, WalletClient } from \"viem\";\n\nimport { pepuMainnet } from \"../chains.js\";\nimport { resolvePepuEndpoints } from \"../endpoints.js\";\nimport { txUrl } from \"../explorer.js\";\nimport type { PaymasterContext } from \"../erc7677.js\";\nimport { normalizeCalls } from \"./calls.js\";\nimport { ENTRY_POINT_V07, createPepuPaymasterClient, estimatePepuUserOpFees, requireBundlerUrl } from \"./clients.js\";\nimport { describeUserOpFailure } from \"./describe.js\";\nimport type { Call } from \"./types.js\";\n\nexport type { Call } from \"./types.js\";\nexport { encodeKernelExecute } from \"./calls.js\";\n\n/** Kernel v3.1, the version deployed on PEPU mainnet (factory in the contract registry). */\nexport const KERNEL_VERSION = constants.KERNEL_V3_1;\n\ntype ZeroDevClient = Parameters<typeof createKernelAccount>[0];\ntype KernelAccountParams = Parameters<typeof createKernelAccount>[1];\n\n/**\n * The ZeroDev packages resolve their own copy of viem as a peer. In a monorepo\n * with several viem installs two identical `PublicClient` types are nominally\n * different; this is a type-level bridge only (same object at runtime).\n */\nfunction zd(client: PublicClient): ZeroDevClient {\n return client as unknown as ZeroDevClient;\n}\n\n/** The Kernel account type this module builds. */\nexport type KernelSmartAccount = Awaited<ReturnType<typeof createKernelAccount>>;\n/** The sponsored client type {@link createPepuSponsoredClient} returns. */\nexport type KernelAccountClient = ReturnType<typeof createKernelAccountClient>;\n\n/** Anything that can sign for the Kernel owner. */\nexport type KernelOwner = LocalAccount | Signer | WalletClient;\n\nfunction defaultPublicClient(): PublicClient {\n return createPublicClient({ chain: pepuMainnet, transport: http(resolvePepuEndpoints().rpcUrl) }) as PublicClient;\n}\n\n/**\n * Build a Kernel v3.1 smart account owned by `owner` (ECDSA root validator).\n * The address depends only on the owner and `index`, never on a session.\n * Pass `plugins.regular` to add a permission (session-key) validator on top\n * of the root; that is how `@pepu-chain/sdk/session/kernel` builds on this.\n *\n * @example\n * const account = await toPepuKernelAccount({ publicClient, owner: privateKeyToAccount(key) });\n */\nexport async function toPepuKernelAccount(p: {\n publicClient: PublicClient;\n owner: KernelOwner;\n index?: bigint;\n /**\n * `regular` is a ZeroDev validator plugin, for example the permission\n * validator from `@zerodev/permissions` (see `@pepu-chain/sdk/session/kernel`).\n * Typed as `object` so this entry does not need `@zerodev/permissions` types.\n */\n plugins?: { regular?: object };\n}): Promise<KernelSmartAccount> {\n const sudo = await signerToEcdsaValidator(zd(p.publicClient), {\n signer: p.owner as Signer,\n entryPoint: ENTRY_POINT_V07,\n kernelVersion: KERNEL_VERSION,\n });\n return createKernelAccount(zd(p.publicClient), {\n entryPoint: ENTRY_POINT_V07,\n kernelVersion: KERNEL_VERSION,\n plugins: { sudo, ...(p.plugins?.regular ? { regular: p.plugins.regular } : {}) },\n ...(p.index !== undefined ? { index: p.index } : {}),\n } as KernelAccountParams);\n}\n\nfunction toEmptyAccount(address: Address): LocalAccount {\n const refuse = async (): Promise<never> => {\n throw new Error(\"read-only account cannot sign\");\n };\n return {\n address,\n type: \"local\",\n source: \"custom\",\n publicKey: \"0x\" as Hex,\n signMessage: refuse,\n signTransaction: refuse,\n signTypedData: refuse,\n } as unknown as LocalAccount;\n}\n\n/**\n * The counterfactual Kernel address for an owner, with no signature needed.\n * Lifted from `templates/sponsored-session-app/lib/kernel.ts`.\n *\n * @example\n * const smartAccount = await getKernelAddress(publicClient, ownerAddress);\n */\nexport async function getKernelAddress(publicClient: PublicClient, owner: Address): Promise<Address> {\n const account = await toPepuKernelAccount({ publicClient, owner: toEmptyAccount(owner) });\n return account.address;\n}\n\n/**\n * A Kernel client that sends through YOUR bundler and has gas paid by YOUR\n * paymaster (ERC-7677). Fees come from the chain with 20% headroom.\n *\n * @example\n * const client = createPepuSponsoredClient({ account, paymasterContext: { privyAccessToken } });\n */\nexport function createPepuSponsoredClient(p: {\n account: KernelSmartAccount;\n bundlerUrl?: string;\n paymasterUrl?: string;\n /** Project client token; builds the ERC-7677 URL against the paymaster base when no URL is configured. */\n paymasterToken?: string;\n paymasterContext?: PaymasterContext;\n publicClient?: PublicClient;\n}): KernelAccountClient {\n const publicClient = p.publicClient ?? defaultPublicClient();\n const paymaster = createPepuPaymasterClient({\n ...(p.paymasterUrl !== undefined ? { paymasterUrl: p.paymasterUrl } : {}),\n ...(p.paymasterToken !== undefined ? { paymasterToken: p.paymasterToken } : {}),\n ...(p.paymasterContext ? { context: p.paymasterContext } : {}),\n });\n return createKernelAccountClient({\n account: p.account,\n chain: pepuMainnet,\n client: zd(publicClient),\n bundlerTransport: http(requireBundlerUrl(p.bundlerUrl)),\n paymaster,\n userOperation: { estimateFeesPerGas: async () => estimatePepuUserOpFees(publicClient) },\n } as unknown as Parameters<typeof createKernelAccountClient>[0]);\n}\n\n/** Result of {@link sendSponsored}. */\nexport interface SendSponsoredResult {\n userOpHash: Hex;\n transactionHash: Hex;\n success: boolean;\n paymaster: Address | null;\n actualGasCostWei: bigint;\n explorerUrl: string;\n}\n\n/**\n * Encode `calls`, send one UserOperation, wait for its receipt, and report\n * who paid. Failures are mapped through `describeUserOpFailure` (AAxx and\n * paymaster reasons become typed PepuErrors). Flow ported from\n * `sendSessionTap` in the sponsored-session-app template.\n *\n * @example\n * const r = await sendSponsored({ client, calls: [{ to, abi, functionName: \"tap\" }] });\n * console.log(r.paymaster, r.explorerUrl);\n */\nexport async function sendSponsored(p: {\n client: KernelAccountClient;\n calls: Call[];\n timeoutMs?: number;\n}): Promise<SendSponsoredResult> {\n const calls = normalizeCalls(p.calls);\n try {\n const account = p.client.account;\n if (!account) throw new Error(\"The Kernel client has no account.\");\n const callData = await account.encodeCalls(calls);\n const userOpHash = await p.client.sendUserOperation({ callData });\n const receipt = await p.client.waitForUserOperationReceipt({ hash: userOpHash, timeout: p.timeoutMs ?? 90_000 });\n const transactionHash = receipt.receipt.transactionHash;\n return {\n userOpHash,\n transactionHash,\n success: receipt.success,\n paymaster: receipt.paymaster ?? null,\n actualGasCostWei: receipt.actualGasCost,\n explorerUrl: txUrl(pepuMainnet, transactionHash),\n };\n } catch (e) {\n throw describeUserOpFailure(e);\n }\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/aa/kernel.ts"],"names":["constants","createPublicClient","pepuMainnet","http","resolvePepuEndpoints","signerToEcdsaValidator","ENTRY_POINT_V07","createKernelAccount","createPepuPaymasterClient","createKernelAccountClient","requireBundlerUrl","estimatePepuUserOpFees","normalizeCalls","txUrl","describeUserOpFailure"],"mappings":";;;;;;;;;;;;AAiCO,IAAM,iBAAiBA,aAAA,CAAU;AAUxC,SAAS,GAAG,MAAA,EAAqC;AAC/C,EAAA,OAAO,MAAA;AACT;AAUA,SAAS,mBAAA,GAAoC;AAC3C,EAAA,OAAOC,uBAAA,CAAmB,EAAE,KAAA,EAAOC,6BAAA,EAAa,SAAA,EAAWC,UAAKC,sCAAA,EAAqB,CAAE,MAAM,CAAA,EAAG,CAAA;AAClG;AAWA,eAAsB,oBAAoB,CAAA,EAUV;AAC9B,EAAA,MAAM,OAAO,MAAMC,qCAAA,CAAuB,EAAA,CAAG,CAAA,CAAE,YAAY,CAAA,EAAG;AAAA,IAC5D,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A;AACxC,IAAA,OAAO;AAAA,MACL,UAAA;AAAA,MACA,eAAA;AAAA,MACA,SAAS,OAAA,CAAQ,OAAA;AAAA,MACjB,SAAA,EAAW,QAAQ,SAAA,IAAa,IAAA;AAAA,MAChC,kBAAkB,OAAA,CAAQ,aAAA;AAAA,MAC1B,WAAA,EAAaC,uBAAA,CAAMX,6BAAA,EAAa,eAAe;AAAA,KACjD;AAAA,EACF,SAAS,CAAA,EAAG;AACV,IAAA,MAAMY,wCAAsB,CAAC,CAAA;AAAA,EAC/B;AACF","file":"chunk-UQH4ZAXD.cjs","sourcesContent":["/**\n * @pepu-chain/sdk/aa/kernel: Kernel v3.1 smart account plus sponsored-send\n * helpers for the \"direct\" transport (your own bundler and paymaster URLs).\n * Needs the optional peers `@zerodev/sdk` and `@zerodev/ecdsa-validator`.\n *\n * This is the only module in the SDK (with `session/kernel` and `combo`) that\n * imports ZeroDev. Ported from `templates/sponsored-session-app/lib/kernel.ts`\n * (Kernel v3.1 build, 20% fee headroom because Alto lacks\n * `zd_getUserOperationGasPrice`).\n *\n * Session keys: `toPepuKernelAccount` takes an optional `plugins.regular`\n * validator, which is the plug point WP-B6 (`/session/kernel`, `/combo`) uses\n * to add a permission validator on top of the ECDSA root.\n */\nimport { signerToEcdsaValidator } from \"@zerodev/ecdsa-validator\";\nimport { constants, createKernelAccount, createKernelAccountClient } from \"@zerodev/sdk\";\nimport type { Signer } from \"@zerodev/sdk/types\";\nimport { createPublicClient, http } from \"viem\";\nimport type { Address, Hex, LocalAccount, PublicClient, WalletClient } from \"viem\";\n\nimport { pepuMainnet } from \"../chains.js\";\nimport { resolvePepuEndpoints } from \"../endpoints.js\";\nimport { txUrl } from \"../explorer.js\";\nimport type { PaymasterContext } from \"../erc7677.js\";\nimport { normalizeCalls } from \"./calls.js\";\nimport { ENTRY_POINT_V07, createPepuPaymasterClient, estimatePepuUserOpFees, requireBundlerUrl } from \"./clients.js\";\nimport { describeUserOpFailure } from \"./describe.js\";\nimport type { Call } from \"./types.js\";\n\nexport type { Call } from \"./types.js\";\nexport { encodeKernelExecute } from \"./calls.js\";\n\n/** Kernel v3.1, the version deployed on PEPU mainnet (factory in the contract registry). */\nexport const KERNEL_VERSION = constants.KERNEL_V3_1;\n\ntype ZeroDevClient = Parameters<typeof createKernelAccount>[0];\ntype KernelAccountParams = Parameters<typeof createKernelAccount>[1];\n\n/**\n * The ZeroDev packages resolve their own copy of viem as a peer. In a monorepo\n * with several viem installs two identical `PublicClient` types are nominally\n * different; this is a type-level bridge only (same object at runtime).\n */\nfunction zd(client: PublicClient): ZeroDevClient {\n return client as unknown as ZeroDevClient;\n}\n\n/** The Kernel account type this module builds. */\nexport type KernelSmartAccount = Awaited<ReturnType<typeof createKernelAccount>>;\n/** The sponsored client type {@link createPepuSponsoredClient} returns. */\nexport type KernelAccountClient = ReturnType<typeof createKernelAccountClient>;\n\n/** Anything that can sign for the Kernel owner. */\nexport type KernelOwner = LocalAccount | Signer | WalletClient;\n\nfunction defaultPublicClient(): PublicClient {\n return createPublicClient({ chain: pepuMainnet, transport: http(resolvePepuEndpoints().rpcUrl) }) as PublicClient;\n}\n\n/**\n * Build a Kernel v3.1 smart account owned by `owner` (ECDSA root validator).\n * The address depends only on the owner and `index`, never on a session.\n * Pass `plugins.regular` to add a permission (session-key) validator on top\n * of the root; that is how `@pepu-chain/sdk/session/kernel` builds on this.\n *\n * @example\n * const account = await toPepuKernelAccount({ publicClient, owner: privateKeyToAccount(key) });\n */\nexport async function toPepuKernelAccount(p: {\n publicClient: PublicClient;\n owner: KernelOwner;\n index?: bigint;\n /**\n * `regular` is a ZeroDev validator plugin, for example the permission\n * validator from `@zerodev/permissions` (see `@pepu-chain/sdk/session/kernel`).\n * Typed as `object` so this entry does not need `@zerodev/permissions` types.\n */\n plugins?: { regular?: object };\n}): Promise<KernelSmartAccount> {\n const sudo = await signerToEcdsaValidator(zd(p.publicClient), {\n signer: p.owner as Signer,\n entryPoint: ENTRY_POINT_V07,\n kernelVersion: KERNEL_VERSION,\n });\n return createKernelAccount(zd(p.publicClient), {\n entryPoint: ENTRY_POINT_V07,\n kernelVersion: KERNEL_VERSION,\n plugins: { sudo, ...(p.plugins?.regular ? { regular: p.plugins.regular } : {}) },\n ...(p.index !== undefined ? { index: p.index } : {}),\n } as KernelAccountParams);\n}\n\nfunction toEmptyAccount(address: Address): LocalAccount {\n const refuse = async (): Promise<never> => {\n throw new Error(\"read-only account cannot sign\");\n };\n return {\n address,\n type: \"local\",\n source: \"custom\",\n publicKey: \"0x\" as Hex,\n signMessage: refuse,\n signTransaction: refuse,\n signTypedData: refuse,\n } as unknown as LocalAccount;\n}\n\n/**\n * The counterfactual Kernel address for an owner, with no signature needed.\n * Lifted from `templates/sponsored-session-app/lib/kernel.ts`.\n *\n * @example\n * const smartAccount = await getKernelAddress(publicClient, ownerAddress);\n */\nexport async function getKernelAddress(publicClient: PublicClient, owner: Address): Promise<Address> {\n const account = await toPepuKernelAccount({ publicClient, owner: toEmptyAccount(owner) });\n return account.address;\n}\n\n/**\n * A Kernel client that sends through YOUR bundler and has gas paid by YOUR\n * paymaster (ERC-7677). Fees come from the chain with 20% headroom.\n *\n * @example\n * const client = createPepuSponsoredClient({ account, paymasterContext: { privyAccessToken } });\n */\nexport function createPepuSponsoredClient(p: {\n account: KernelSmartAccount;\n bundlerUrl?: string;\n paymasterUrl?: string;\n /** Project client token; builds the ERC-7677 URL against the paymaster base when no URL is configured. */\n paymasterToken?: string;\n paymasterContext?: PaymasterContext;\n publicClient?: PublicClient;\n}): KernelAccountClient {\n const publicClient = p.publicClient ?? defaultPublicClient();\n const paymaster = createPepuPaymasterClient({\n ...(p.paymasterUrl !== undefined ? { paymasterUrl: p.paymasterUrl } : {}),\n ...(p.paymasterToken !== undefined ? { paymasterToken: p.paymasterToken } : {}),\n ...(p.paymasterContext ? { context: p.paymasterContext } : {}),\n });\n return createKernelAccountClient({\n account: p.account,\n chain: pepuMainnet,\n client: zd(publicClient),\n bundlerTransport: http(requireBundlerUrl(p.bundlerUrl)),\n paymaster,\n userOperation: { estimateFeesPerGas: async () => estimatePepuUserOpFees(publicClient) },\n } as unknown as Parameters<typeof createKernelAccountClient>[0]);\n}\n\n/** Result of {@link sendSponsored}. */\nexport interface SendSponsoredResult {\n userOpHash: Hex;\n transactionHash: Hex;\n success: boolean;\n paymaster: Address | null;\n actualGasCostWei: bigint;\n explorerUrl: string;\n}\n\n/**\n * Encode `calls`, send one UserOperation, wait for its receipt, and report\n * who paid. Failures are mapped through `describeUserOpFailure` (AAxx and\n * paymaster reasons become typed PepuErrors). Flow ported from\n * `sendSessionTap` in the sponsored-session-app template.\n *\n * @example\n * const r = await sendSponsored({ client, calls: [{ to, abi, functionName: \"tap\" }] });\n * console.log(r.paymaster, r.explorerUrl);\n */\nexport async function sendSponsored(p: {\n client: KernelAccountClient;\n calls: Call[];\n timeoutMs?: number;\n}): Promise<SendSponsoredResult> {\n const calls = normalizeCalls(p.calls);\n try {\n const account = p.client.account;\n if (!account) throw new Error(\"The Kernel client has no account.\");\n const callData = await account.encodeCalls(calls);\n const userOpHash = await p.client.sendUserOperation({ callData });\n const receipt = await p.client.waitForUserOperationReceipt({ hash: userOpHash, timeout: p.timeoutMs ?? 90_000 });\n const transactionHash = receipt.receipt.transactionHash;\n return {\n userOpHash,\n transactionHash,\n success: receipt.success,\n paymaster: receipt.paymaster ?? null,\n actualGasCostWei: receipt.actualGasCost,\n explorerUrl: txUrl(pepuMainnet, transactionHash),\n };\n } catch (e) {\n throw describeUserOpFailure(e);\n }\n}\n"]}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
|
-
var
|
|
3
|
+
var chunkHTCX46RJ_cjs = require('./chunk-HTCX46RJ.cjs');
|
|
4
4
|
var chunkK7JSQPZO_cjs = require('./chunk-K7JSQPZO.cjs');
|
|
5
5
|
var chunkVF3D6KLQ_cjs = require('./chunk-VF3D6KLQ.cjs');
|
|
6
6
|
var chunkDPCZJLB3_cjs = require('./chunk-DPCZJLB3.cjs');
|
|
@@ -92,7 +92,7 @@ async function rpc(f, url, method, params, timeoutMs) {
|
|
|
92
92
|
return body;
|
|
93
93
|
}
|
|
94
94
|
function unreachable(url, e) {
|
|
95
|
-
const reason = e instanceof Error && e.name === "AbortError" ? "timed out" :
|
|
95
|
+
const reason = e instanceof Error && e.name === "AbortError" ? "timed out" : chunkHTCX46RJ_cjs.redactSecrets(e instanceof Error ? e.message : String(e)).replace(/https?:\/\/\S+/g, "[url]");
|
|
96
96
|
return new chunkYQL7NISX_cjs.PepuBundlerError("BUNDLER_UNREACHABLE", `Could not reach ${hostOf(url)}: ${reason}`, { cause: e });
|
|
97
97
|
}
|
|
98
98
|
async function probeBundler(url, o = {}) {
|
|
@@ -311,5 +311,5 @@ exports.getSponsorshipStatus = getSponsorshipStatus;
|
|
|
311
311
|
exports.kernelFactoryAbi = kernelFactoryAbi;
|
|
312
312
|
exports.probeBundler = probeBundler;
|
|
313
313
|
exports.probePaymaster = probePaymaster;
|
|
314
|
-
//# sourceMappingURL=chunk-
|
|
315
|
-
//# sourceMappingURL=chunk-
|
|
314
|
+
//# sourceMappingURL=chunk-VYMAZVIK.cjs.map
|
|
315
|
+
//# sourceMappingURL=chunk-VYMAZVIK.cjs.map
|