@pafi-dev/issuer 0.19.0 → 0.21.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -50,12 +50,14 @@ __export(index_exports, {
50
50
  PTRedeemHandler: () => PTRedeemHandler,
51
51
  PafiBackendClient: () => PafiBackendClient,
52
52
  PafiBackendError: () => PafiBackendError,
53
+ PafiEstimatorHttpError: () => PafiEstimatorHttpError,
53
54
  PafiSdkError: () => import_core.PafiSdkError,
54
55
  PendingUserOpForbiddenError: () => PendingUserOpForbiddenError,
55
56
  PendingUserOpNotFoundError: () => PendingUserOpNotFoundError,
56
57
  PerpDepositError: () => PerpDepositError,
57
58
  PerpDepositHandler: () => PerpDepositHandler,
58
59
  PointIndexer: () => PointIndexer,
60
+ PointTokenDomainResolver: () => PointTokenDomainResolver,
59
61
  PolicyProvider: () => PolicyProvider,
60
62
  REDEMPTION_HISTORY_WINDOW_SEC: () => REDEMPTION_HISTORY_WINDOW_SEC,
61
63
  RedemptionService: () => RedemptionService,
@@ -70,6 +72,7 @@ __export(index_exports, {
70
72
  buildSdkErrorBody: () => buildSdkErrorBody,
71
73
  createIssuerService: () => createIssuerService,
72
74
  createNativePtQuoter: () => createNativePtQuoter,
75
+ createPafiEstimatorClient: () => createPafiEstimatorClient,
73
76
  createSdkErrorMapper: () => createSdkErrorMapper,
74
77
  createSubgraphNativeUsdtQuoter: () => createSubgraphNativeUsdtQuoter,
75
78
  createSubgraphPoolsProvider: () => createSubgraphPoolsProvider,
@@ -1093,58 +1096,265 @@ var RelayService = class {
1093
1096
  }
1094
1097
  });
1095
1098
  }
1099
+ // =========================================================================
1100
+ // Preview methods — produce bundler-ready partial UserOps WITHOUT signing.
1101
+ //
1102
+ // These exist so callers can fetch an accurate gas estimate from PAFI's
1103
+ // `/v1/estimate-gas-fee` BEFORE committing to a signed MintRequest /
1104
+ // BurnRequest (HSM/KMS signing is expensive in production). The
1105
+ // returned `callData` matches the SHAPE of the real call; the EIP-712
1106
+ // signature bytes are a placeholder. Bundler simulation doesn't
1107
+ // validate the signature, so the gas estimate comes back accurate.
1108
+ //
1109
+ // Cache-wise: same SC version + same scenario produce identical
1110
+ // calldata shape → identical bundler-returned gas units. The first
1111
+ // call seeds the cache; subsequent ones hit it.
1112
+ // =========================================================================
1113
+ /**
1114
+ * Build a dummy `PartialUserOperation` for the mint scenario, suitable
1115
+ * for `feeManager.estimateGasFee({ partialUserOp, ... })`. NO signing —
1116
+ * uses a 65-byte zero signature placeholder.
1117
+ */
1118
+ previewMintUserOp(params) {
1119
+ const useWrapper = params.mintFeeWrapperAddress !== void 0;
1120
+ let mintCallData;
1121
+ let mintTarget;
1122
+ if (useWrapper) {
1123
+ mintCallData = (0, import_viem3.encodeFunctionData)({
1124
+ abi: import_core5.mintFeeWrapperAbi,
1125
+ functionName: "mintWithFee",
1126
+ args: [
1127
+ params.pointTokenAddress,
1128
+ params.userAddress,
1129
+ params.amount,
1130
+ params.deadline,
1131
+ PLACEHOLDER_SIG_65
1132
+ ]
1133
+ });
1134
+ mintTarget = params.mintFeeWrapperAddress;
1135
+ } else {
1136
+ mintCallData = (0, import_viem3.encodeFunctionData)({
1137
+ abi: import_core5.POINT_TOKEN_ABI,
1138
+ functionName: "mint",
1139
+ args: [
1140
+ params.userAddress,
1141
+ params.amount,
1142
+ params.deadline,
1143
+ PLACEHOLDER_SIG_65
1144
+ ]
1145
+ });
1146
+ mintTarget = params.pointTokenAddress;
1147
+ }
1148
+ return (0, import_core5.buildPartialUserOperation)({
1149
+ sender: params.userAddress,
1150
+ nonce: params.aaNonce,
1151
+ operations: [{ target: mintTarget, value: 0n, data: mintCallData }],
1152
+ // Gas limits ignored by bundler estimate — it computes them.
1153
+ gasLimits: {
1154
+ callGasLimit: 1n,
1155
+ verificationGasLimit: 1n,
1156
+ preVerificationGas: 1n
1157
+ }
1158
+ });
1159
+ }
1160
+ /** Burn-side mirror of `previewMintUserOp`. */
1161
+ previewBurnUserOp(params) {
1162
+ const burnCallData = (0, import_viem3.encodeFunctionData)({
1163
+ abi: import_core5.POINT_TOKEN_ABI,
1164
+ functionName: "burn",
1165
+ args: [
1166
+ params.userAddress,
1167
+ params.amount,
1168
+ params.deadline,
1169
+ PLACEHOLDER_SIG_65
1170
+ ]
1171
+ });
1172
+ return (0, import_core5.buildPartialUserOperation)({
1173
+ sender: params.userAddress,
1174
+ nonce: params.aaNonce,
1175
+ operations: [
1176
+ { target: params.pointTokenAddress, value: 0n, data: burnCallData }
1177
+ ],
1178
+ gasLimits: {
1179
+ callGasLimit: 1n,
1180
+ verificationGasLimit: 1n,
1181
+ preVerificationGas: 1n
1182
+ }
1183
+ });
1184
+ }
1096
1185
  };
1186
+ var PLACEHOLDER_SIG_65 = `0x${"00".repeat(65)}`;
1097
1187
  function errorMessage(err) {
1098
1188
  return err instanceof Error ? err.message : String(err);
1099
1189
  }
1100
1190
 
1101
1191
  // src/relay/feeManager.ts
1102
1192
  var DEFAULT_GAS_UNITS = 500000n;
1103
- var DEFAULT_PREMIUM_BPS = 12e3;
1193
+ var DEFAULT_PREMIUM_BPS = 1e4;
1104
1194
  var FeeManager = class _FeeManager {
1105
1195
  provider;
1106
- gasUnits;
1196
+ fallbackGasUnits;
1107
1197
  gasPremiumBps;
1108
1198
  quoteNativeToFee;
1199
+ bundlerClient;
1200
+ metrics;
1201
+ // Short-lived fee-value cache. Distinct from the estimator's cache:
1202
+ // this absorbs burst calls (e.g. 5 user requests in 5s all hit the
1203
+ // /gas-fee endpoint) by remembering the COMPUTED PT amount, not the
1204
+ // gas units. Only used by the no-opts legacy path; estimator path
1205
+ // gets its caching from the PAFI side instead.
1109
1206
  cachedFee = null;
1110
1207
  cacheExpiresAt = 0;
1111
- static CACHE_TTL_MS = 1e4;
1208
+ static FEE_CACHE_TTL_MS = 1e4;
1112
1209
  constructor(config) {
1113
1210
  if (!config.provider) throw new Error("FeeManager: provider required");
1114
1211
  if (!config.quoteNativeToFee)
1115
1212
  throw new Error("FeeManager: quoteNativeToFee required");
1116
1213
  this.provider = config.provider;
1117
- this.gasUnits = config.gasUnits ?? DEFAULT_GAS_UNITS;
1214
+ this.fallbackGasUnits = config.gasUnits ?? DEFAULT_GAS_UNITS;
1118
1215
  this.gasPremiumBps = config.gasPremiumBps ?? DEFAULT_PREMIUM_BPS;
1119
1216
  this.quoteNativeToFee = config.quoteNativeToFee;
1217
+ this.bundlerClient = config.bundlerClient;
1218
+ this.metrics = config.metrics;
1120
1219
  }
1121
1220
  /**
1122
- * Estimate the fee (in the caller's fee currency) to charge for the
1123
- * next sponsored UserOp:
1221
+ * Estimate the operator fee for the next sponsored UserOp.
1124
1222
  *
1125
- * nativeCost = gasUnits × gasPrice
1126
- * withPremium = nativeCost × premiumBps / 10_000
1127
- * fee = quoteNativeToFee(withPremium)
1223
+ * Without `opts` → legacy path: `gasUnits × gasPrice × premium →
1224
+ * quoteNativeToFee`. Cached for 10 s to absorb bursts.
1128
1225
  *
1129
- * For backward compatibility with v0.2.x code that reads `gasFeeUsdt`
1130
- * from the response, the name `estimateGasFee` is kept but the
1131
- * currency depends on how the caller wired `quoteNativeToFee`.
1226
+ * With `opts` AND `bundlerClient` → estimator path. Each call may
1227
+ * hit a different bundler-cached result; the SDK does NOT add its
1228
+ * own value cache because the estimator's cache TTL is the source
1229
+ * of truth for "how long is this estimate good for".
1132
1230
  */
1133
- async estimateGasFee() {
1231
+ async estimateGasFee(opts = {}) {
1232
+ const isLegacyCall = !opts.partialUserOp && !opts.scenario && !opts.contractAddress;
1134
1233
  const now = Date.now();
1135
- if (this.cachedFee !== null && now < this.cacheExpiresAt) {
1234
+ if (isLegacyCall && this.cachedFee !== null && now < this.cacheExpiresAt) {
1136
1235
  return this.cachedFee;
1137
1236
  }
1237
+ const t0 = Date.now();
1238
+ const { gasUnits, source } = await this.resolveGasUnits(opts);
1239
+ const latencyMs = Date.now() - t0;
1240
+ this.safeEmit(
1241
+ () => this.metrics?.onEstimate?.({
1242
+ source,
1243
+ scenario: opts.scenario,
1244
+ gasUnits,
1245
+ latencyMs
1246
+ })
1247
+ );
1138
1248
  const gasPrice = await this.provider.getGasPrice();
1139
- const nativeCost = gasPrice * this.gasUnits;
1249
+ const nativeCost = gasPrice * gasUnits;
1140
1250
  const withPremium = nativeCost * BigInt(this.gasPremiumBps) / 10000n;
1141
1251
  const fee = await this.quoteNativeToFee(withPremium);
1142
- this.cachedFee = fee;
1143
- this.cacheExpiresAt = now + _FeeManager.CACHE_TTL_MS;
1252
+ if (isLegacyCall) {
1253
+ this.cachedFee = fee;
1254
+ this.cacheExpiresAt = now + _FeeManager.FEE_CACHE_TTL_MS;
1255
+ }
1144
1256
  return fee;
1145
1257
  }
1258
+ /** Manually purge the legacy 10s fee cache. */
1259
+ invalidateCache() {
1260
+ this.cachedFee = null;
1261
+ this.cacheExpiresAt = 0;
1262
+ }
1263
+ async resolveGasUnits(opts) {
1264
+ if (!this.bundlerClient || !opts.partialUserOp || !opts.scenario || !opts.contractAddress) {
1265
+ return { gasUnits: this.fallbackGasUnits, source: "fallback" };
1266
+ }
1267
+ try {
1268
+ const result = await this.bundlerClient.getGasUnits({
1269
+ scenario: opts.scenario,
1270
+ contractAddress: opts.contractAddress,
1271
+ paymasterAddress: opts.paymasterAddress,
1272
+ partialUserOp: opts.partialUserOp
1273
+ });
1274
+ return { gasUnits: result.gasUnits, source: "estimator" };
1275
+ } catch (err) {
1276
+ const reason = err instanceof Error ? err.message : String(err);
1277
+ this.safeEmit(
1278
+ () => this.metrics?.onEstimatorError?.({
1279
+ scenario: opts.scenario,
1280
+ reason
1281
+ })
1282
+ );
1283
+ return { gasUnits: this.fallbackGasUnits, source: "fallback" };
1284
+ }
1285
+ }
1286
+ safeEmit(fn) {
1287
+ try {
1288
+ fn();
1289
+ } catch {
1290
+ }
1291
+ }
1146
1292
  };
1147
1293
 
1294
+ // src/relay/bundlerEstimator.ts
1295
+ var PafiEstimatorHttpError = class extends Error {
1296
+ status;
1297
+ body;
1298
+ constructor(status, body, message) {
1299
+ super(message ?? `PAFI estimator HTTP ${status}`);
1300
+ this.status = status;
1301
+ this.body = body;
1302
+ }
1303
+ };
1304
+ function createPafiEstimatorClient(config) {
1305
+ const { baseUrl, apiKey, issuerId } = config;
1306
+ if (!baseUrl) throw new Error("createPafiEstimatorClient: baseUrl required");
1307
+ if (!apiKey) throw new Error("createPafiEstimatorClient: apiKey required");
1308
+ if (!issuerId) throw new Error("createPafiEstimatorClient: issuerId required");
1309
+ const fetchImpl = config.fetchImpl ?? globalThis.fetch;
1310
+ if (!fetchImpl) {
1311
+ throw new Error(
1312
+ "createPafiEstimatorClient: no fetch implementation available \u2014 pass `fetchImpl`"
1313
+ );
1314
+ }
1315
+ const url = `${baseUrl.replace(/\/$/, "")}/v1/estimate-gas-fee`;
1316
+ return {
1317
+ async getGasUnits(input) {
1318
+ const body = JSON.stringify({
1319
+ partialUserOp: {
1320
+ sender: input.partialUserOp.sender,
1321
+ // Hex-encode bigint for JSON safety. Sponsor-relayer parses
1322
+ // back to bigint at the DTO layer.
1323
+ nonce: `0x${input.partialUserOp.nonce.toString(16)}`,
1324
+ callData: input.partialUserOp.callData,
1325
+ signature: input.partialUserOp.signature
1326
+ },
1327
+ scenario: input.scenario,
1328
+ contractAddress: input.contractAddress,
1329
+ paymasterAddress: input.paymasterAddress
1330
+ });
1331
+ const res = await fetchImpl(url, {
1332
+ method: "POST",
1333
+ headers: {
1334
+ "content-type": "application/json",
1335
+ authorization: `Bearer ${apiKey}`,
1336
+ "x-issuer-id": issuerId
1337
+ },
1338
+ body
1339
+ });
1340
+ if (!res.ok) {
1341
+ let errBody = null;
1342
+ try {
1343
+ errBody = await res.json();
1344
+ } catch {
1345
+ }
1346
+ throw new PafiEstimatorHttpError(res.status, errBody);
1347
+ }
1348
+ const json = await res.json();
1349
+ return {
1350
+ gasUnits: BigInt(json.gasUnits),
1351
+ source: json.source,
1352
+ expiresAt: json.expiresAt
1353
+ };
1354
+ }
1355
+ };
1356
+ }
1357
+
1148
1358
  // src/indexer/types.ts
1149
1359
  var InMemoryCursorStore = class {
1150
1360
  cursor;
@@ -1934,8 +2144,59 @@ var IssuerApiHandlers = class _IssuerApiHandlers {
1934
2144
  }
1935
2145
  };
1936
2146
 
1937
- // src/api/handlers/ptRedeemHandler.ts
2147
+ // src/api/pointTokenDomainResolver.ts
1938
2148
  var import_viem7 = require("viem");
2149
+ var NAME_ABI = [
2150
+ {
2151
+ type: "function",
2152
+ name: "name",
2153
+ stateMutability: "view",
2154
+ inputs: [],
2155
+ outputs: [{ type: "string" }]
2156
+ }
2157
+ ];
2158
+ var PointTokenDomainResolver = class {
2159
+ provider;
2160
+ overrides;
2161
+ cache = /* @__PURE__ */ new Map();
2162
+ constructor(config) {
2163
+ this.provider = config.provider;
2164
+ this.overrides = /* @__PURE__ */ new Map();
2165
+ if (config.overrides) {
2166
+ for (const [addr, name] of Object.entries(config.overrides)) {
2167
+ this.overrides.set((0, import_viem7.getAddress)(addr).toLowerCase(), name);
2168
+ }
2169
+ }
2170
+ }
2171
+ async resolve(pointTokenAddress) {
2172
+ const key = (0, import_viem7.getAddress)(pointTokenAddress).toLowerCase();
2173
+ const cached = this.cache.get(key);
2174
+ if (cached !== void 0) return cached;
2175
+ const override = this.overrides.get(key);
2176
+ if (override !== void 0) {
2177
+ this.cache.set(key, override);
2178
+ return override;
2179
+ }
2180
+ const name = await this.provider.readContract({
2181
+ address: pointTokenAddress,
2182
+ abi: NAME_ABI,
2183
+ functionName: "name"
2184
+ });
2185
+ this.cache.set(key, name);
2186
+ return name;
2187
+ }
2188
+ /** Invalidate one address (after deploy / proxy upgrade) or all. */
2189
+ invalidate(pointTokenAddress) {
2190
+ if (pointTokenAddress) {
2191
+ this.cache.delete((0, import_viem7.getAddress)(pointTokenAddress).toLowerCase());
2192
+ } else {
2193
+ this.cache.clear();
2194
+ }
2195
+ }
2196
+ };
2197
+
2198
+ // src/api/handlers/ptRedeemHandler.ts
2199
+ var import_viem8 = require("viem");
1939
2200
  var import_core7 = require("@pafi-dev/core");
1940
2201
  var DEFAULT_REDEEM_LOCK_MS = 15 * 60 * 1e3;
1941
2202
  var DEFAULT_SIG_DEADLINE_SEC = 15 * 60;
@@ -1956,10 +2217,9 @@ var PTRedeemHandler = class {
1956
2217
  relayService;
1957
2218
  provider;
1958
2219
  feeService;
1959
- pointTokenAddress;
1960
2220
  batchExecutorAddress;
1961
2221
  chainId;
1962
- domain;
2222
+ domainResolver;
1963
2223
  burnerSignerWallet;
1964
2224
  redeemLockDurationMs;
1965
2225
  signatureDeadlineSeconds;
@@ -1996,10 +2256,9 @@ var PTRedeemHandler = class {
1996
2256
  this.relayService = config.relayService;
1997
2257
  this.provider = config.provider;
1998
2258
  this.feeService = config.feeService;
1999
- this.pointTokenAddress = (0, import_viem7.getAddress)(config.pointTokenAddress);
2000
- this.batchExecutorAddress = (0, import_viem7.getAddress)(config.batchExecutorAddress);
2259
+ this.batchExecutorAddress = (0, import_viem8.getAddress)(config.batchExecutorAddress);
2001
2260
  this.chainId = config.chainId;
2002
- this.domain = config.domain;
2261
+ this.domainResolver = config.domainResolver;
2003
2262
  this.burnerSignerWallet = config.burnerSignerWallet;
2004
2263
  if (this.burnerSignerWallet?.account?.type === "local") {
2005
2264
  console.warn("[PAFI] PTRedeemHandler: burnerSignerWallet uses a local (private key) account. Use a KMS-backed signer in production.");
@@ -2012,7 +2271,7 @@ var PTRedeemHandler = class {
2012
2271
  }
2013
2272
  }
2014
2273
  async handle(request) {
2015
- if ((0, import_viem7.getAddress)(request.authenticatedAddress) !== (0, import_viem7.getAddress)(request.userAddress)) {
2274
+ if ((0, import_viem8.getAddress)(request.authenticatedAddress) !== (0, import_viem8.getAddress)(request.userAddress)) {
2016
2275
  throw new PTRedeemError(
2017
2276
  "UNAUTHORIZED",
2018
2277
  `userAddress (${request.userAddress}) does not match authenticated session (${request.authenticatedAddress})`
@@ -2021,11 +2280,12 @@ var PTRedeemHandler = class {
2021
2280
  if (request.amount <= 0n) {
2022
2281
  throw new PTRedeemError("INVALID_AMOUNT", "redeem amount must be positive");
2023
2282
  }
2283
+ const pointTokenAddress = (0, import_viem8.getAddress)(request.pointTokenAddress);
2024
2284
  if (this.redemptionService) {
2025
2285
  const decision = await this.redemptionService.evaluate(
2026
2286
  request.userAddress,
2027
2287
  request.amount,
2028
- this.pointTokenAddress
2288
+ pointTokenAddress
2029
2289
  );
2030
2290
  if (!decision.allowed) {
2031
2291
  const denial = decision.denial;
@@ -2039,7 +2299,7 @@ var PTRedeemHandler = class {
2039
2299
  let burnNonce;
2040
2300
  try {
2041
2301
  burnNonce = await this.provider.readContract({
2042
- address: this.pointTokenAddress,
2302
+ address: pointTokenAddress,
2043
2303
  abi: import_core7.POINT_TOKEN_ABI,
2044
2304
  functionName: "burnRequestNonces",
2045
2305
  args: [request.userAddress]
@@ -2050,32 +2310,50 @@ var PTRedeemHandler = class {
2050
2310
  `failed to read burnRequestNonces(${request.userAddress}): ${err instanceof Error ? err.message : String(err)}`
2051
2311
  );
2052
2312
  }
2053
- const userKey = (0, import_viem7.getAddress)(request.userAddress).toLowerCase();
2054
- let userNonces = this.inFlightNonces.get(userKey);
2313
+ const nonceKey = `${(0, import_viem8.getAddress)(request.userAddress).toLowerCase()}:${pointTokenAddress.toLowerCase()}`;
2314
+ let userNonces = this.inFlightNonces.get(nonceKey);
2055
2315
  if (!userNonces) {
2056
2316
  userNonces = /* @__PURE__ */ new Set();
2057
- this.inFlightNonces.set(userKey, userNonces);
2317
+ this.inFlightNonces.set(nonceKey, userNonces);
2058
2318
  }
2059
2319
  if (userNonces.has(burnNonce)) {
2060
2320
  throw new PTRedeemError(
2061
2321
  "NONCE_IN_FLIGHT",
2062
- `A burn request for nonce ${burnNonce} is already in progress for ${request.userAddress}. Retry after the current request completes.`
2322
+ `A burn request for nonce ${burnNonce} is already in progress for ${request.userAddress} on ${pointTokenAddress}. Retry after the current request completes.`
2063
2323
  );
2064
2324
  }
2065
2325
  userNonces.add(burnNonce);
2066
2326
  try {
2067
- return await this._handleAfterNonceLock(request, burnNonce);
2327
+ return await this._handleAfterNonceLock(request, burnNonce, pointTokenAddress);
2068
2328
  } finally {
2069
2329
  userNonces.delete(burnNonce);
2070
- if (userNonces.size === 0) this.inFlightNonces.delete(userKey);
2330
+ if (userNonces.size === 0) this.inFlightNonces.delete(nonceKey);
2071
2331
  }
2072
2332
  }
2073
- async _handleAfterNonceLock(request, burnNonce) {
2333
+ async _handleAfterNonceLock(request, burnNonce, pointTokenAddress) {
2334
+ const previewDeadline = BigInt(
2335
+ Math.floor(this.now() / 1e3) + this.signatureDeadlineSeconds
2336
+ );
2074
2337
  let fee;
2075
2338
  if (request.feeAmount !== void 0) {
2076
2339
  fee = request.feeAmount > 0n ? request.feeAmount : 0n;
2077
2340
  } else if (this.feeService) {
2078
- fee = await this.feeService.estimateGasFee();
2341
+ const previewUserOp = this.relayService.previewBurnUserOp({
2342
+ userAddress: request.userAddress,
2343
+ aaNonce: burnNonce,
2344
+ pointTokenAddress,
2345
+ amount: request.amount,
2346
+ deadline: previewDeadline
2347
+ });
2348
+ fee = await this.feeService.estimateGasFee({
2349
+ scenario: "burn",
2350
+ contractAddress: pointTokenAddress,
2351
+ partialUserOp: {
2352
+ sender: previewUserOp.sender,
2353
+ nonce: previewUserOp.nonce,
2354
+ callData: previewUserOp.callData
2355
+ }
2356
+ });
2079
2357
  } else {
2080
2358
  fee = 0n;
2081
2359
  }
@@ -2088,7 +2366,7 @@ var PTRedeemHandler = class {
2088
2366
  }
2089
2367
  const onChainBalance = await (0, import_core7.getPointTokenBalance)(
2090
2368
  this.provider,
2091
- this.pointTokenAddress,
2369
+ pointTokenAddress,
2092
2370
  request.userAddress
2093
2371
  );
2094
2372
  if (onChainBalance < request.amount) {
@@ -2097,13 +2375,12 @@ var PTRedeemHandler = class {
2097
2375
  `insufficient on-chain PT balance: have ${onChainBalance}, need ${request.amount}`
2098
2376
  );
2099
2377
  }
2100
- const deadline = BigInt(
2101
- Math.floor(this.now() / 1e3) + this.signatureDeadlineSeconds
2102
- );
2378
+ const deadline = previewDeadline;
2379
+ const domainName = await this.domainResolver.resolve(pointTokenAddress);
2103
2380
  const domain = {
2104
- name: this.domain.name,
2381
+ name: domainName,
2105
2382
  chainId: this.chainId,
2106
- verifyingContract: this.domain.verifyingContract ?? this.pointTokenAddress
2383
+ verifyingContract: pointTokenAddress
2107
2384
  };
2108
2385
  const sponsoredBurnAmount = request.amount - fee;
2109
2386
  const sponsoredBurnRequest = {
@@ -2125,14 +2402,14 @@ var PTRedeemHandler = class {
2125
2402
  request.userAddress,
2126
2403
  sponsoredBurnAmount,
2127
2404
  this.redeemLockDurationMs,
2128
- this.pointTokenAddress
2405
+ pointTokenAddress
2129
2406
  );
2130
2407
  try {
2131
2408
  const sponsoredUserOp = await this.relayService.prepareBurn({
2132
2409
  mode: "burnWithSig",
2133
2410
  userAddress: request.userAddress,
2134
2411
  aaNonce: request.aaNonce,
2135
- pointTokenAddress: this.pointTokenAddress,
2412
+ pointTokenAddress,
2136
2413
  batchExecutorAddress: this.batchExecutorAddress,
2137
2414
  burnRequest: sponsoredBurnRequest,
2138
2415
  burnerSignature: sponsoredSig,
@@ -2160,7 +2437,7 @@ var PTRedeemHandler = class {
2160
2437
  request.userAddress,
2161
2438
  request.amount,
2162
2439
  this.redeemLockDurationMs,
2163
- this.pointTokenAddress
2440
+ pointTokenAddress
2164
2441
  );
2165
2442
  let fallbackUserOp;
2166
2443
  try {
@@ -2168,7 +2445,7 @@ var PTRedeemHandler = class {
2168
2445
  mode: "burnWithSig",
2169
2446
  userAddress: request.userAddress,
2170
2447
  aaNonce: request.aaNonce,
2171
- pointTokenAddress: this.pointTokenAddress,
2448
+ pointTokenAddress,
2172
2449
  batchExecutorAddress: this.batchExecutorAddress,
2173
2450
  burnRequest: fallbackBurnRequest,
2174
2451
  burnerSignature: fallbackSig,
@@ -2193,7 +2470,7 @@ var PTRedeemHandler = class {
2193
2470
  await this.redemptionService.recordSuccessfulInitiate({
2194
2471
  user: request.userAddress,
2195
2472
  amountPt: request.amount,
2196
- pointTokenAddress: this.pointTokenAddress,
2473
+ pointTokenAddress,
2197
2474
  reservationId: sponsoredLockId
2198
2475
  }).catch(() => {
2199
2476
  });
@@ -2316,7 +2593,7 @@ async function handleRedeemStatus(params) {
2316
2593
  }
2317
2594
 
2318
2595
  // src/api/mobileHandlers.ts
2319
- var import_viem8 = require("viem");
2596
+ var import_viem9 = require("viem");
2320
2597
  var import_core10 = require("@pafi-dev/core");
2321
2598
 
2322
2599
  // src/userop-store/serialize.ts
@@ -2662,7 +2939,7 @@ async function handleMobileSubmit(params) {
2662
2939
  if (!entry) {
2663
2940
  throw new PendingUserOpNotFoundError(params.lockId);
2664
2941
  }
2665
- if ((0, import_viem8.getAddress)(entry.sender) !== (0, import_viem8.getAddress)(params.authenticatedAddress)) {
2942
+ if ((0, import_viem9.getAddress)(entry.sender) !== (0, import_viem9.getAddress)(params.authenticatedAddress)) {
2666
2943
  throw new PendingUserOpForbiddenError(params.lockId);
2667
2944
  }
2668
2945
  const variant = params.variant ?? "sponsored";
@@ -2678,7 +2955,7 @@ async function handleMobileSubmit(params) {
2678
2955
  }
2679
2956
 
2680
2957
  // src/api/handlers/ptClaimHandler.ts
2681
- var import_viem9 = require("viem");
2958
+ var import_viem10 = require("viem");
2682
2959
  var import_core11 = require("@pafi-dev/core");
2683
2960
 
2684
2961
  // src/issuer-state/types.ts
@@ -2724,7 +3001,7 @@ var PTClaimHandler = class {
2724
3001
  };
2725
3002
  }
2726
3003
  async handle(request) {
2727
- if ((0, import_viem9.getAddress)(request.authenticatedAddress) !== (0, import_viem9.getAddress)(request.userAddress)) {
3004
+ if ((0, import_viem10.getAddress)(request.authenticatedAddress) !== (0, import_viem10.getAddress)(request.userAddress)) {
2728
3005
  throw new PTClaimError(
2729
3006
  "VALIDATION_FAILED",
2730
3007
  `userAddress (${request.userAddress}) does not match authenticated session (${request.authenticatedAddress})`
@@ -2762,9 +3039,28 @@ var PTClaimHandler = class {
2762
3039
  const signatureDeadline = BigInt(
2763
3040
  Math.floor(this.cfg.now() / 1e3) + this.cfg.signatureDeadlineSeconds
2764
3041
  );
2765
- const feeAmount = this.cfg.feeService ? await this.cfg.feeService.estimateGasFee() : 0n;
3042
+ const previewUserOp = this.cfg.relayService.previewMintUserOp({
3043
+ userAddress: request.userAddress,
3044
+ aaNonce: request.aaNonce,
3045
+ pointTokenAddress: request.pointTokenAddress,
3046
+ amount: request.amount,
3047
+ deadline: signatureDeadline,
3048
+ mintFeeWrapperAddress: resolvedWrapper
3049
+ });
3050
+ const feeAmount = this.cfg.feeService ? await this.cfg.feeService.estimateGasFee({
3051
+ scenario: resolvedWrapper ? "mint-wrapped" : "mint",
3052
+ contractAddress: request.pointTokenAddress,
3053
+ partialUserOp: {
3054
+ sender: previewUserOp.sender,
3055
+ nonce: previewUserOp.nonce,
3056
+ callData: previewUserOp.callData
3057
+ }
3058
+ }) : 0n;
3059
+ const domainName = await this.cfg.domainResolver.resolve(
3060
+ request.pointTokenAddress
3061
+ );
2766
3062
  const domain = {
2767
- name: this.cfg.pointTokenDomainName,
3063
+ name: domainName,
2768
3064
  chainId: request.chainId,
2769
3065
  verifyingContract: request.pointTokenAddress
2770
3066
  };
@@ -2962,7 +3258,7 @@ var PerpDepositHandler = class {
2962
3258
 
2963
3259
  // src/api/delegateHandler.ts
2964
3260
  var import_core13 = require("@pafi-dev/core");
2965
- var import_viem10 = require("viem");
3261
+ var import_viem11 = require("viem");
2966
3262
  var DEFAULT_DELEGATE_GAS = {
2967
3263
  callGasLimit: 100000n,
2968
3264
  verificationGasLimit: 150000n,
@@ -3049,7 +3345,7 @@ async function handleDelegateSubmit(params) {
3049
3345
  if (!entry) {
3050
3346
  throw new PendingUserOpNotFoundError(params.lockId);
3051
3347
  }
3052
- if ((0, import_viem10.getAddress)(entry.sender) !== (0, import_viem10.getAddress)(params.authenticatedAddress)) {
3348
+ if ((0, import_viem11.getAddress)(entry.sender) !== (0, import_viem11.getAddress)(params.authenticatedAddress)) {
3053
3349
  throw new PendingUserOpForbiddenError(params.lockId);
3054
3350
  }
3055
3351
  if (!entry.eip7702Auth) {
@@ -3070,7 +3366,7 @@ async function handleDelegateSubmit(params) {
3070
3366
 
3071
3367
  // src/api/issuerApiAdapter.ts
3072
3368
  var import_node_crypto3 = require("crypto");
3073
- var import_viem11 = require("viem");
3369
+ var import_viem12 = require("viem");
3074
3370
  var import_core14 = require("@pafi-dev/core");
3075
3371
  var AdapterMisconfiguredError = class extends Error {
3076
3372
  code = "ADAPTER_MISCONFIGURED";
@@ -3128,7 +3424,7 @@ var IssuerApiAdapter = class {
3128
3424
  async pools(authenticatedAddress, chainId, pointTokenAddress) {
3129
3425
  const result = await this.cfg.issuerService.api.handlePools(
3130
3426
  authenticatedAddress,
3131
- { chainId, pointTokenAddress: (0, import_viem11.getAddress)(pointTokenAddress) }
3427
+ { chainId, pointTokenAddress: (0, import_viem12.getAddress)(pointTokenAddress) }
3132
3428
  );
3133
3429
  return { pools: result.pools };
3134
3430
  }
@@ -3137,8 +3433,8 @@ var IssuerApiAdapter = class {
3137
3433
  authenticatedAddress,
3138
3434
  {
3139
3435
  chainId,
3140
- userAddress: (0, import_viem11.getAddress)(userAddress),
3141
- pointTokenAddress: (0, import_viem11.getAddress)(pointTokenAddress)
3436
+ userAddress: (0, import_viem12.getAddress)(userAddress),
3437
+ pointTokenAddress: (0, import_viem12.getAddress)(pointTokenAddress)
3142
3438
  }
3143
3439
  );
3144
3440
  return {
@@ -3159,7 +3455,7 @@ var IssuerApiAdapter = class {
3159
3455
  "ptClaimHandler",
3160
3456
  "claim"
3161
3457
  );
3162
- const pointTokenAddress = (0, import_viem11.getAddress)(input.pointTokenAddress);
3458
+ const pointTokenAddress = (0, import_viem12.getAddress)(input.pointTokenAddress);
3163
3459
  const result = await ptClaimHandler.handle({
3164
3460
  authenticatedAddress: input.authenticatedAddress,
3165
3461
  userAddress: input.authenticatedAddress,
@@ -3186,9 +3482,11 @@ var IssuerApiAdapter = class {
3186
3482
  }
3187
3483
  async redeem(input) {
3188
3484
  this.assertRedeemHandler();
3485
+ const pointTokenAddress = (0, import_viem12.getAddress)(input.pointTokenAddress);
3189
3486
  const response = await this.cfg.ptRedeemHandler.handle({
3190
3487
  userAddress: input.authenticatedAddress,
3191
3488
  authenticatedAddress: input.authenticatedAddress,
3489
+ pointTokenAddress,
3192
3490
  amount: input.amount,
3193
3491
  aaNonce: input.aaNonce,
3194
3492
  chainId: input.chainId
@@ -3254,7 +3552,7 @@ var IssuerApiAdapter = class {
3254
3552
  "ptClaimHandler",
3255
3553
  "claimPrepare"
3256
3554
  );
3257
- const pointTokenAddress = (0, import_viem11.getAddress)(input.pointTokenAddress);
3555
+ const pointTokenAddress = (0, import_viem12.getAddress)(input.pointTokenAddress);
3258
3556
  const claimResult = await ptClaimHandler.handle({
3259
3557
  authenticatedAddress: input.authenticatedAddress,
3260
3558
  userAddress: input.authenticatedAddress,
@@ -3300,10 +3598,11 @@ var IssuerApiAdapter = class {
3300
3598
  }
3301
3599
  async redeemPrepare(input) {
3302
3600
  this.assertRedeemHandler();
3303
- const pointTokenAddress = (0, import_viem11.getAddress)(input.pointTokenAddress);
3601
+ const pointTokenAddress = (0, import_viem12.getAddress)(input.pointTokenAddress);
3304
3602
  const redeemResponse = await this.cfg.ptRedeemHandler.handle({
3305
3603
  userAddress: input.authenticatedAddress,
3306
3604
  authenticatedAddress: input.authenticatedAddress,
3605
+ pointTokenAddress,
3307
3606
  amount: input.amount,
3308
3607
  aaNonce: input.aaNonce,
3309
3608
  chainId: input.chainId
@@ -3490,7 +3789,7 @@ var IssuerApiAdapter = class {
3490
3789
  };
3491
3790
 
3492
3791
  // src/pools/subgraphPoolsProvider.ts
3493
- var import_viem12 = require("viem");
3792
+ var import_viem13 = require("viem");
3494
3793
  var import_core15 = require("@pafi-dev/core");
3495
3794
  var DEFAULT_CACHE_TTL_MS = 3e4;
3496
3795
  var MAX_REASONABLE_FEE_TIER = 1e6;
@@ -3613,7 +3912,7 @@ async function fetchPoolsFromSubgraph(fetchImpl, subgraphUrl, pointTokenAddress,
3613
3912
  return [];
3614
3913
  }
3615
3914
  const { pool } = token;
3616
- if (!(0, import_viem12.isAddress)(pool.token0.id) || !(0, import_viem12.isAddress)(pool.token1.id)) {
3915
+ if (!(0, import_viem13.isAddress)(pool.token0.id) || !(0, import_viem13.isAddress)(pool.token1.id)) {
3617
3916
  const error = new Error(
3618
3917
  "[PAFI] SubgraphPoolsProvider: invalid token address in response"
3619
3918
  );
@@ -3766,8 +4065,8 @@ function toUsdtPerNative(priceFloat, usdtDecimals) {
3766
4065
  }
3767
4066
 
3768
4067
  // src/pools/nativePtQuoter.ts
3769
- var import_viem13 = require("viem");
3770
- var CHAINLINK_ABI = (0, import_viem13.parseAbi)([
4068
+ var import_viem14 = require("viem");
4069
+ var CHAINLINK_ABI = (0, import_viem14.parseAbi)([
3771
4070
  "function latestRoundData() external view returns (uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound)"
3772
4071
  ]);
3773
4072
  var CHAINLINK_MAX_AGE_S = 3600n;
@@ -4051,7 +4350,7 @@ var PafiBackendClient = class {
4051
4350
  };
4052
4351
 
4053
4352
  // src/config.ts
4054
- var import_viem14 = require("viem");
4353
+ var import_viem15 = require("viem");
4055
4354
  var import_core18 = require("@pafi-dev/core");
4056
4355
 
4057
4356
  // src/redemption/evaluator.ts
@@ -4378,7 +4677,7 @@ function createIssuerService(config) {
4378
4677
  "createIssuerService: at least one of pointTokenAddress / pointTokenAddresses is required"
4379
4678
  );
4380
4679
  }
4381
- const tokenAddresses = rawAddresses.map((a) => (0, import_viem14.getAddress)(a));
4680
+ const tokenAddresses = rawAddresses.map((a) => (0, import_viem15.getAddress)(a));
4382
4681
  const ledger = config.ledger;
4383
4682
  const sessionStore = config.sessionStore ?? new MemorySessionStore();
4384
4683
  const policy = config.policy ?? new DefaultPolicyEngine({ ledger });
@@ -4497,7 +4796,7 @@ function createIssuerService(config) {
4497
4796
  }
4498
4797
 
4499
4798
  // src/issuer-state/validator.ts
4500
- var import_viem15 = require("viem");
4799
+ var import_viem16 = require("viem");
4501
4800
  var import_core19 = require("@pafi-dev/core");
4502
4801
  var ISSUER_RECORD_TTL_MS = 3e4;
4503
4802
  var IssuerStateValidator = class _IssuerStateValidator {
@@ -4524,7 +4823,7 @@ var IssuerStateValidator = class _IssuerStateValidator {
4524
4823
  */
4525
4824
  invalidate(pointToken) {
4526
4825
  if (pointToken) {
4527
- const key = (0, import_viem15.getAddress)(pointToken);
4826
+ const key = (0, import_viem16.getAddress)(pointToken);
4528
4827
  this.pointTokenIssuerCache.delete(key);
4529
4828
  this.stateCache.delete(key);
4530
4829
  this.inflight.delete(key);
@@ -4539,7 +4838,7 @@ var IssuerStateValidator = class _IssuerStateValidator {
4539
4838
  * The issuer field is set at `initialize()` and never changes.
4540
4839
  */
4541
4840
  async getIssuerAddressForPointToken(pointToken) {
4542
- const key = (0, import_viem15.getAddress)(pointToken);
4841
+ const key = (0, import_viem16.getAddress)(pointToken);
4543
4842
  const cached = this.pointTokenIssuerCache.get(key);
4544
4843
  if (cached) return cached;
4545
4844
  const issuer = await this.provider.readContract({
@@ -4547,15 +4846,15 @@ var IssuerStateValidator = class _IssuerStateValidator {
4547
4846
  abi: import_core19.POINT_TOKEN_ABI,
4548
4847
  functionName: "issuer"
4549
4848
  });
4550
- this.pointTokenIssuerCache.set(key, (0, import_viem15.getAddress)(issuer));
4551
- return (0, import_viem15.getAddress)(issuer);
4849
+ this.pointTokenIssuerCache.set(key, (0, import_viem16.getAddress)(issuer));
4850
+ return (0, import_viem16.getAddress)(issuer);
4552
4851
  }
4553
4852
  /**
4554
4853
  * Read registry record + totalSupply, with 30s cache and in-flight
4555
4854
  * deduplication. Does NOT throw on inactive/missing — returns raw state.
4556
4855
  */
4557
4856
  async getIssuerState(pointToken) {
4558
- const tokenAddr = (0, import_viem15.getAddress)(pointToken);
4857
+ const tokenAddr = (0, import_viem16.getAddress)(pointToken);
4559
4858
  const now = Date.now();
4560
4859
  const cached = this.stateCache.get(tokenAddr);
4561
4860
  if (cached && cached.expiresAt > now) return cached.value;
@@ -4698,7 +4997,7 @@ var MemoryRedemptionHistoryStore = class {
4698
4997
  };
4699
4998
 
4700
4999
  // src/index.ts
4701
- var PAFI_ISSUER_SDK_VERSION = true ? "0.19.0" : "dev";
5000
+ var PAFI_ISSUER_SDK_VERSION = true ? "0.21.0" : "dev";
4702
5001
  // Annotate the CommonJS export names for ESM import in node:
4703
5002
  0 && (module.exports = {
4704
5003
  AdapterMisconfiguredError,
@@ -4731,12 +5030,14 @@ var PAFI_ISSUER_SDK_VERSION = true ? "0.19.0" : "dev";
4731
5030
  PTRedeemHandler,
4732
5031
  PafiBackendClient,
4733
5032
  PafiBackendError,
5033
+ PafiEstimatorHttpError,
4734
5034
  PafiSdkError,
4735
5035
  PendingUserOpForbiddenError,
4736
5036
  PendingUserOpNotFoundError,
4737
5037
  PerpDepositError,
4738
5038
  PerpDepositHandler,
4739
5039
  PointIndexer,
5040
+ PointTokenDomainResolver,
4740
5041
  PolicyProvider,
4741
5042
  REDEMPTION_HISTORY_WINDOW_SEC,
4742
5043
  RedemptionService,
@@ -4751,6 +5052,7 @@ var PAFI_ISSUER_SDK_VERSION = true ? "0.19.0" : "dev";
4751
5052
  buildSdkErrorBody,
4752
5053
  createIssuerService,
4753
5054
  createNativePtQuoter,
5055
+ createPafiEstimatorClient,
4754
5056
  createSdkErrorMapper,
4755
5057
  createSubgraphNativeUsdtQuoter,
4756
5058
  createSubgraphPoolsProvider,