@pafi-dev/core 0.5.18 → 0.5.20

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.d.ts CHANGED
@@ -8,7 +8,7 @@ export { buildAllPaths, combineRoutes, findBestQuote, quoteBestRoute, quoteExact
8
8
  import { P as PartialUserOperation, O as Operation, U as UserOperation, S as SwapSimulationResult } from './index-DKtVEoRC.js';
9
9
  export { B as BuildSwapWithGasDeductionParams, a as PaymasterFields, b as SETTLE_ALL, c as SWAP_EXACT_IN, T as TAKE_ALL, d as UserOpReceipt, V as V4_SWAP, Z as ZERO_VALUE, e as buildErc20ApprovalCalldata, f as buildPermit2ApprovalCalldata, g as buildSwapFromQuote, h as buildSwapWithGasDeduction, i as buildUniversalRouterExecuteArgs, j as buildV4SwapInput, k as checkAllowance, s as simulateSwap } from './index-DKtVEoRC.js';
10
10
  import { LoginMessageParams } from './auth/index.js';
11
- export { SPONSOR_AUTH_DOMAIN_NAME, SPONSOR_AUTH_TYPES, SponsorAuthPayload, SponsorAuthVerifyResult, VerifyLoginResult, buildSponsorAuthDomain, buildSponsorAuthTypedData, computeCallDataHash, createLoginMessage, parseLoginMessage, signSponsorAuth, verifyLoginMessage, verifySponsorAuth } from './auth/index.js';
11
+ export { BuildSponsorAuthParams, BuiltSponsorAuth, SPONSOR_AUTH_DOMAIN_NAME, SPONSOR_AUTH_TYPES, SponsorAuthPayload, SponsorAuthVerifyResult, VerifyLoginResult, buildAndSignSponsorAuth, buildSponsorAuthDomain, buildSponsorAuthTypedData, computeCallDataHash, createLoginMessage, parseLoginMessage, signSponsorAuth, verifyLoginMessage, verifySponsorAuth } from './auth/index.js';
12
12
 
13
13
  declare const mintRequestTypes: {
14
14
  readonly MintRequest: readonly [{
@@ -1112,6 +1112,37 @@ interface SendWithPaymasterFallbackParams {
1112
1112
  */
1113
1113
  declare function sendWithPaymasterFallback(params: SendWithPaymasterFallbackParams): Promise<Hex>;
1114
1114
 
1115
+ interface QuoteOperatorFeePtConfig {
1116
+ provider: PublicClient;
1117
+ chainId: number;
1118
+ pointTokenAddress: Address;
1119
+ /**
1120
+ * ERC-4337 gas units the UserOp will consume on chain. Default
1121
+ * 500_000n covers the common scenarios (mint, swap, perp deposit
1122
+ * via Relay) with margin. Pass a tighter number when you have a
1123
+ * Pimlico estimate to feed in.
1124
+ */
1125
+ gasUnits?: bigint;
1126
+ /**
1127
+ * Premium applied on top of raw gas cost in basis points. Default
1128
+ * 12_000 (= 1.2×, 20% buffer to cover oracle drift + paymaster
1129
+ * overhead). Same default the issuer SDK's `FeeManager` uses.
1130
+ */
1131
+ premiumBps?: number;
1132
+ /** Chainlink ETH/USD feed override. Defaults to chain's address. */
1133
+ chainlinkFeedAddress?: Address;
1134
+ /** Subgraph URL override. Defaults to `PAFI_SUBGRAPH_URL`. */
1135
+ subgraphUrl?: string;
1136
+ /** USDT token decimals. Default 6 (USDC/USDT on Base/Ethereum). */
1137
+ usdtDecimals?: number;
1138
+ /** Fallback ETH price (USD) when Chainlink is unreachable. Default 3000. */
1139
+ fallbackEthPriceUsd?: number;
1140
+ /** Fallback PT price (USDT per 1 PT) when subgraph is unreachable. Default 0.1. */
1141
+ fallbackPtPriceUsdt?: number;
1142
+ fetchImpl?: typeof fetch;
1143
+ }
1144
+ declare function quoteOperatorFeePt(config: QuoteOperatorFeePtConfig): Promise<bigint>;
1145
+
1115
1146
  declare const BATCH_EXECUTOR_ADDRESS_BASE_MAINNET: `0x${string}`;
1116
1147
  declare const BATCH_EXECUTOR_ADDRESS_BASE_SEPOLIA: `0x${string}`;
1117
1148
 
@@ -1566,4 +1597,4 @@ declare class PafiSDK {
1566
1597
  signLoginMessage(message: string): Promise<Hex>;
1567
1598
  }
1568
1599
 
1569
- export { ApiError, BATCH_EXECUTOR_7702_IMPL, BATCH_EXECUTOR_ABI, BATCH_EXECUTOR_ADDRESS_BASE_MAINNET, BATCH_EXECUTOR_ADDRESS_BASE_SEPOLIA, BROKER_HASHES, BestQuote, type BuildDelegationUserOpParams, type BuildPartialUserOpParams, type BuildPerpDepositViaRelayParams, type BuildPerpDepositWithGasDeductionParams, COMMON_POOLS, COMMON_TOKENS, CONTRACT_ADDRESSES, ChainConfig, type CheckEthAndBranchParams, ConfigurationError, type ContractAddresses, DUMMY_SIGNATURE_V07, type DelegateImpl, EIP712Signature, ENTRY_POINT_V07, ENTRY_POINT_V08, LoginMessageParams, MintRequest, type ModalOpenOptions, ORDERLY_RELAY_ABI, ORDERLY_VAULT_ABI, ORDERLY_VAULT_ADDRESSES, ORDERLY_VAULT_BASE_MAINNET, Operation, type OrderlyRelayDepositRequest, PAFI_SUBGRAPH_URL, PERMIT2_ADDRESS, POINT_TOKEN_FACTORY_ADDRESSES, POINT_TOKEN_IMPL_ADDRESSES, POINT_TOKEN_POOLS, type PackedUserOperationMessage, type PafiProxyTransportParams, PafiSDK, PafiSDKConfig, PafiSDKError, type PafiWebModalAdapter, type PafiWebModalHandle, PartialUserOperation, type PaymasterConfig, PointTokenDomainConfig, PoolKey, QuoteResult, ReceiverConsent, SIMPLE_7702_IMPL_BASE_MAINNET, SUPPORTED_CHAINS, type SendWithPaymasterFallbackParams, type SignatureStruct, SignatureVerification, SigningError, SimulationError, type SmartAccountSender, type SponsorshipScenario, type SubmissionPath, SwapSimulationResult, TOKEN_HASHES, UNIVERSAL_ROUTER_ADDRESSES, type UserOpTypedData, UserOperation, V4_QUOTER_ADDRESSES, type VaultDepositFE, _resetPaymasterConfigForTests, assembleUserOperation, buildDelegationUserOp, buildPartialUserOperation, buildPerpDepositViaRelay, buildPerpDepositWithGasDeduction, buildUserOpTypedData, burnRequestTypes, checkDelegation, checkEthAndBranch, computeAccountId, computeAuthorizationHash, computeUserOpHash, createPafiProxyTransport, decodeBatchExecuteCalls, detectDelegateImpl, encodeBatchExecute, erc20ApproveOp, erc20BurnOp, erc20TransferOp, fetchPafiPools, getAaNonce, getContractAddresses, getDummySignatureFor7702, getPafiWebModalAdapter, getPaymasterConfig, isDelegatedTo, isDelegatedToTarget, isPaymasterConfigured, isPaymasterError, mintRequestTypes, openPafiWebModal, openWebPopup, parseEip7702DelegatedAddress, rawCallOp, receiverConsentTypes, sendWithPaymasterFallback, serializeUserOpToJsonRpc, setPafiWebModalAdapter, setPaymasterConfig, webPopupAdapter };
1600
+ export { ApiError, BATCH_EXECUTOR_7702_IMPL, BATCH_EXECUTOR_ABI, BATCH_EXECUTOR_ADDRESS_BASE_MAINNET, BATCH_EXECUTOR_ADDRESS_BASE_SEPOLIA, BROKER_HASHES, BestQuote, type BuildDelegationUserOpParams, type BuildPartialUserOpParams, type BuildPerpDepositViaRelayParams, type BuildPerpDepositWithGasDeductionParams, COMMON_POOLS, COMMON_TOKENS, CONTRACT_ADDRESSES, ChainConfig, type CheckEthAndBranchParams, ConfigurationError, type ContractAddresses, DUMMY_SIGNATURE_V07, type DelegateImpl, EIP712Signature, ENTRY_POINT_V07, ENTRY_POINT_V08, LoginMessageParams, MintRequest, type ModalOpenOptions, ORDERLY_RELAY_ABI, ORDERLY_VAULT_ABI, ORDERLY_VAULT_ADDRESSES, ORDERLY_VAULT_BASE_MAINNET, Operation, type OrderlyRelayDepositRequest, PAFI_SUBGRAPH_URL, PERMIT2_ADDRESS, POINT_TOKEN_FACTORY_ADDRESSES, POINT_TOKEN_IMPL_ADDRESSES, POINT_TOKEN_POOLS, type PackedUserOperationMessage, type PafiProxyTransportParams, PafiSDK, PafiSDKConfig, PafiSDKError, type PafiWebModalAdapter, type PafiWebModalHandle, PartialUserOperation, type PaymasterConfig, PointTokenDomainConfig, PoolKey, type QuoteOperatorFeePtConfig, QuoteResult, ReceiverConsent, SIMPLE_7702_IMPL_BASE_MAINNET, SUPPORTED_CHAINS, type SendWithPaymasterFallbackParams, type SignatureStruct, SignatureVerification, SigningError, SimulationError, type SmartAccountSender, type SponsorshipScenario, type SubmissionPath, SwapSimulationResult, TOKEN_HASHES, UNIVERSAL_ROUTER_ADDRESSES, type UserOpTypedData, UserOperation, V4_QUOTER_ADDRESSES, type VaultDepositFE, _resetPaymasterConfigForTests, assembleUserOperation, buildDelegationUserOp, buildPartialUserOperation, buildPerpDepositViaRelay, buildPerpDepositWithGasDeduction, buildUserOpTypedData, burnRequestTypes, checkDelegation, checkEthAndBranch, computeAccountId, computeAuthorizationHash, computeUserOpHash, createPafiProxyTransport, decodeBatchExecuteCalls, detectDelegateImpl, encodeBatchExecute, erc20ApproveOp, erc20BurnOp, erc20TransferOp, fetchPafiPools, getAaNonce, getContractAddresses, getDummySignatureFor7702, getPafiWebModalAdapter, getPaymasterConfig, isDelegatedTo, isDelegatedToTarget, isPaymasterConfigured, isPaymasterError, mintRequestTypes, openPafiWebModal, openWebPopup, parseEip7702DelegatedAddress, quoteOperatorFeePt, rawCallOp, receiverConsentTypes, sendWithPaymasterFallback, serializeUserOpToJsonRpc, setPafiWebModalAdapter, setPaymasterConfig, webPopupAdapter };
package/dist/index.js CHANGED
@@ -1,6 +1,10 @@
1
+ import {
2
+ pointTokenFactoryAbi
3
+ } from "./chunk-Y2MZ7MKJ.js";
1
4
  import {
2
5
  SPONSOR_AUTH_DOMAIN_NAME,
3
6
  SPONSOR_AUTH_TYPES,
7
+ buildAndSignSponsorAuth,
4
8
  buildSponsorAuthDomain,
5
9
  buildSponsorAuthTypedData,
6
10
  computeCallDataHash,
@@ -9,10 +13,7 @@ import {
9
13
  signSponsorAuth,
10
14
  verifyLoginMessage,
11
15
  verifySponsorAuth
12
- } from "./chunk-W6VULMCO.js";
13
- import {
14
- pointTokenFactoryAbi
15
- } from "./chunk-Y2MZ7MKJ.js";
16
+ } from "./chunk-QGXJLLKF.js";
16
17
  import {
17
18
  getBurnRequestNonce,
18
19
  getIssuer,
@@ -624,6 +625,76 @@ async function sendWithPaymasterFallback(params) {
624
625
  }
625
626
  }
626
627
 
628
+ // src/fee/operatorFeeQuoter.ts
629
+ import { parseAbi } from "viem";
630
+
631
+ // src/subgraph/pools.ts
632
+ import { isAddress } from "viem";
633
+ var PAFI_SUBGRAPH_URL = "https://graph-base-mainnet.pacificfinance.org/subgraphs/name/pafi-subgraph-v2";
634
+ var POOL_QUERY = `
635
+ query GetPoolForPointToken($id: ID!) {
636
+ pafiToken(id: $id) {
637
+ id
638
+ pool {
639
+ id
640
+ feeTier
641
+ tickSpacing
642
+ hooks
643
+ token0 { id }
644
+ token1 { id }
645
+ }
646
+ }
647
+ }
648
+ `;
649
+ function sortCurrencies(a, b) {
650
+ return a.toLowerCase() < b.toLowerCase() ? [a, b] : [b, a];
651
+ }
652
+ async function fetchPafiPools(_chainId, pointTokenAddress, subgraphUrl = PAFI_SUBGRAPH_URL) {
653
+ let response;
654
+ try {
655
+ response = await fetch(subgraphUrl, {
656
+ method: "POST",
657
+ headers: { "Content-Type": "application/json" },
658
+ body: JSON.stringify({
659
+ query: POOL_QUERY,
660
+ variables: { id: pointTokenAddress.toLowerCase() }
661
+ })
662
+ });
663
+ } catch (err) {
664
+ console.warn("[fetchPafiPools] subgraph unreachable:", err.message);
665
+ return [];
666
+ }
667
+ if (!response.ok) {
668
+ console.warn(`[fetchPafiPools] subgraph returned ${response.status}`);
669
+ return [];
670
+ }
671
+ const json = await response.json();
672
+ if (json.errors && json.errors.length > 0) {
673
+ console.warn(
674
+ "[fetchPafiPools] subgraph errors:",
675
+ json.errors.map((e) => e.message).join("; ")
676
+ );
677
+ return [];
678
+ }
679
+ const pool = json.data?.pafiToken?.pool;
680
+ if (!pool) return [];
681
+ if (!isAddress(pool.hooks) || !isAddress(pool.token0.id) || !isAddress(pool.token1.id) || !Number.isFinite(Number(pool.feeTier)) || !Number.isFinite(Number(pool.tickSpacing))) {
682
+ console.error("[fetchPafiPools] invalid pool data in subgraph response \u2014 skipping");
683
+ return [];
684
+ }
685
+ const [currency0, currency1] = sortCurrencies(
686
+ pool.token0.id,
687
+ pool.token1.id
688
+ );
689
+ return [{
690
+ currency0,
691
+ currency1,
692
+ fee: Number(pool.feeTier),
693
+ tickSpacing: Number(pool.tickSpacing),
694
+ hooks: pool.hooks
695
+ }];
696
+ }
697
+
627
698
  // src/contracts/real/addresses.ts
628
699
  var PLACEHOLDER_DEAD = (suffix) => `0x000000000000000000000000000000000000${suffix.toLowerCase().padStart(4, "0")}`;
629
700
  var CONTRACT_ADDRESSES = {
@@ -679,6 +750,120 @@ function getContractAddresses(chainId) {
679
750
  return addrs;
680
751
  }
681
752
 
753
+ // src/fee/operatorFeeQuoter.ts
754
+ var CHAINLINK_ABI = parseAbi([
755
+ "function latestRoundData() external view returns (uint80, int256, uint256, uint256, uint80)"
756
+ ]);
757
+ var CHAINLINK_MAX_AGE_S = 3600n;
758
+ var POOL_PRICE_QUERY = `
759
+ query GetPoolPrice($id: ID!) {
760
+ pafiToken(id: $id) {
761
+ pool {
762
+ token0 { id }
763
+ token1 { id }
764
+ token0Price
765
+ token1Price
766
+ }
767
+ }
768
+ }
769
+ `;
770
+ var DEFAULT_GAS_UNITS = 500000n;
771
+ var DEFAULT_PREMIUM_BPS = 12e3;
772
+ var DEFAULT_USDT_DECIMALS = 6;
773
+ async function quoteOperatorFeePt(config) {
774
+ const {
775
+ provider,
776
+ chainId,
777
+ pointTokenAddress,
778
+ gasUnits = DEFAULT_GAS_UNITS,
779
+ premiumBps = DEFAULT_PREMIUM_BPS,
780
+ subgraphUrl = PAFI_SUBGRAPH_URL,
781
+ usdtDecimals = DEFAULT_USDT_DECIMALS,
782
+ fallbackEthPriceUsd = 3e3,
783
+ fallbackPtPriceUsdt = 0.1,
784
+ fetchImpl = globalThis.fetch
785
+ } = config;
786
+ const chainlinkFeedAddress = config.chainlinkFeedAddress ?? getContractAddresses(chainId).chainlinkEthUsd;
787
+ const gasPrice = await provider.getGasPrice();
788
+ const nativeCost = gasPrice * gasUnits;
789
+ const withPremium = nativeCost * BigInt(premiumBps) / 10000n;
790
+ const [ethPrice8dec, ptPerUsdt18dec] = await Promise.all([
791
+ getEthPrice8dec(provider, chainlinkFeedAddress, fallbackEthPriceUsd),
792
+ getPtPerUsdt18dec(
793
+ fetchImpl,
794
+ subgraphUrl,
795
+ pointTokenAddress,
796
+ fallbackPtPriceUsdt
797
+ )
798
+ ]);
799
+ return withPremium * ethPrice8dec * ptPerUsdt18dec / 10n ** 26n;
800
+ }
801
+ async function getEthPrice8dec(provider, feed, fallback) {
802
+ try {
803
+ const result = await provider.readContract({
804
+ address: feed,
805
+ abi: CHAINLINK_ABI,
806
+ functionName: "latestRoundData"
807
+ });
808
+ const answer = result[1];
809
+ const updatedAt = result[3];
810
+ if (answer <= 0n) throw new Error("Chainlink: non-positive price");
811
+ const ageS = BigInt(Math.floor(Date.now() / 1e3)) - updatedAt;
812
+ if (ageS > CHAINLINK_MAX_AGE_S) {
813
+ throw new Error(`Chainlink: price stale by ${ageS}s`);
814
+ }
815
+ return answer;
816
+ } catch (err) {
817
+ console.warn(
818
+ "[quoteOperatorFeePt] Chainlink unavailable, using fallback:",
819
+ err.message
820
+ );
821
+ return BigInt(Math.round(fallback * 1e8));
822
+ }
823
+ }
824
+ async function getPtPerUsdt18dec(fetchImpl, subgraphUrl, pointTokenAddress, fallbackPtPriceUsdt) {
825
+ try {
826
+ const response = await fetchImpl(subgraphUrl, {
827
+ method: "POST",
828
+ headers: { "Content-Type": "application/json" },
829
+ body: JSON.stringify({
830
+ query: POOL_PRICE_QUERY,
831
+ variables: { id: pointTokenAddress.toLowerCase() }
832
+ })
833
+ });
834
+ if (!response.ok) throw new Error(`subgraph HTTP ${response.status}`);
835
+ const json = await response.json();
836
+ if (json.errors?.length) {
837
+ throw new Error(json.errors.map((e) => e.message).join("; "));
838
+ }
839
+ const pool = json.data?.pafiToken?.pool;
840
+ if (!pool) throw new Error("pafiToken or pool not found");
841
+ const isPtToken0 = pool.token0.id.toLowerCase() === pointTokenAddress.toLowerCase();
842
+ const priceStr = isPtToken0 ? pool.token0Price : pool.token1Price;
843
+ if (!priceStr || Number(priceStr) <= 0) {
844
+ throw new Error(`invalid pool price from subgraph: ${priceStr}`);
845
+ }
846
+ const raw = parseBigDecimalTo18(priceStr);
847
+ if (raw === 0n) {
848
+ throw new Error(`pool price parsed to zero: ${priceStr}`);
849
+ }
850
+ return 10n ** 24n / raw;
851
+ } catch (err) {
852
+ console.warn(
853
+ "[quoteOperatorFeePt] subgraph unavailable, using fallback:",
854
+ err.message
855
+ );
856
+ const ptPerUsdtHuman = 1 / fallbackPtPriceUsdt;
857
+ return parseBigDecimalTo18(ptPerUsdtHuman.toFixed(18));
858
+ }
859
+ }
860
+ function parseBigDecimalTo18(s) {
861
+ const SCALE = 18;
862
+ const [whole = "0", frac = ""] = s.split(".");
863
+ const padded = (frac + "0".repeat(SCALE)).slice(0, SCALE);
864
+ return BigInt(whole + padded);
865
+ }
866
+
682
867
  // src/contracts/real/batchExecutor.ts
683
868
  var BATCH_EXECUTOR_ADDRESS_BASE_MAINNET = getContractAddresses(8453).batchExecutor;
684
869
  var BATCH_EXECUTOR_ADDRESS_BASE_SEPOLIA = getContractAddresses(84532).batchExecutor;
@@ -804,73 +989,6 @@ async function openPafiWebModal(url, options = {}) {
804
989
  );
805
990
  }
806
991
 
807
- // src/subgraph/pools.ts
808
- import { isAddress } from "viem";
809
- var PAFI_SUBGRAPH_URL = "https://graph-base-mainnet.pacificfinance.org/subgraphs/name/pafi-subgraph-v2";
810
- var POOL_QUERY = `
811
- query GetPoolForPointToken($id: ID!) {
812
- pafiToken(id: $id) {
813
- id
814
- pool {
815
- id
816
- feeTier
817
- tickSpacing
818
- hooks
819
- token0 { id }
820
- token1 { id }
821
- }
822
- }
823
- }
824
- `;
825
- function sortCurrencies(a, b) {
826
- return a.toLowerCase() < b.toLowerCase() ? [a, b] : [b, a];
827
- }
828
- async function fetchPafiPools(_chainId, pointTokenAddress, subgraphUrl = PAFI_SUBGRAPH_URL) {
829
- let response;
830
- try {
831
- response = await fetch(subgraphUrl, {
832
- method: "POST",
833
- headers: { "Content-Type": "application/json" },
834
- body: JSON.stringify({
835
- query: POOL_QUERY,
836
- variables: { id: pointTokenAddress.toLowerCase() }
837
- })
838
- });
839
- } catch (err) {
840
- console.warn("[fetchPafiPools] subgraph unreachable:", err.message);
841
- return [];
842
- }
843
- if (!response.ok) {
844
- console.warn(`[fetchPafiPools] subgraph returned ${response.status}`);
845
- return [];
846
- }
847
- const json = await response.json();
848
- if (json.errors && json.errors.length > 0) {
849
- console.warn(
850
- "[fetchPafiPools] subgraph errors:",
851
- json.errors.map((e) => e.message).join("; ")
852
- );
853
- return [];
854
- }
855
- const pool = json.data?.pafiToken?.pool;
856
- if (!pool) return [];
857
- if (!isAddress(pool.hooks) || !isAddress(pool.token0.id) || !isAddress(pool.token1.id) || !Number.isFinite(Number(pool.feeTier)) || !Number.isFinite(Number(pool.tickSpacing))) {
858
- console.error("[fetchPafiPools] invalid pool data in subgraph response \u2014 skipping");
859
- return [];
860
- }
861
- const [currency0, currency1] = sortCurrencies(
862
- pool.token0.id,
863
- pool.token1.id
864
- );
865
- return [{
866
- currency0,
867
- currency1,
868
- fee: Number(pool.feeTier),
869
- tickSpacing: Number(pool.tickSpacing),
870
- hooks: pool.hooks
871
- }];
872
- }
873
-
874
992
  // src/index.ts
875
993
  var PafiSDK = class {
876
994
  _pointTokenAddress;
@@ -1133,6 +1251,7 @@ export {
1133
1251
  _resetPaymasterConfigForTests,
1134
1252
  assembleUserOperation,
1135
1253
  buildAllPaths,
1254
+ buildAndSignSponsorAuth,
1136
1255
  buildBurnRequestTypedData,
1137
1256
  buildDelegationUserOp,
1138
1257
  buildDomain,
@@ -1203,6 +1322,7 @@ export {
1203
1322
  quoteBestRoute,
1204
1323
  quoteExactInput,
1205
1324
  quoteExactInputSingle,
1325
+ quoteOperatorFeePt,
1206
1326
  rawCallOp,
1207
1327
  receiverConsentTypes,
1208
1328
  sendWithPaymasterFallback,