@pafi-dev/core 0.3.0-beta.3 → 0.3.0-beta.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (85) hide show
  1. package/dist/abi/index.cjs +2 -6
  2. package/dist/abi/index.cjs.map +1 -1
  3. package/dist/abi/index.d.cts +1 -286
  4. package/dist/abi/index.d.ts +1 -286
  5. package/dist/abi/index.js +1 -5
  6. package/dist/{chunk-R4L66ZR5.js → chunk-73CQTNLB.js} +10 -1
  7. package/dist/chunk-73CQTNLB.js.map +1 -0
  8. package/dist/{chunk-5YH4D7QF.js → chunk-7UBO7DY5.js} +1 -1
  9. package/dist/{chunk-FGKLDKJK.cjs → chunk-ALCWYDVG.cjs} +1 -1
  10. package/dist/{chunk-FGKLDKJK.cjs.map → chunk-ALCWYDVG.cjs.map} +1 -1
  11. package/dist/{chunk-X3I5XWAR.cjs → chunk-CQCSQPWG.cjs} +2 -15
  12. package/dist/chunk-CQCSQPWG.cjs.map +1 -0
  13. package/dist/{chunk-CWP4PFOP.cjs → chunk-DMW67WBU.cjs} +11 -2
  14. package/dist/chunk-DMW67WBU.cjs.map +1 -0
  15. package/dist/{chunk-C4ZDYG4D.js → chunk-DUY7Z2AI.js} +48 -6
  16. package/dist/chunk-DUY7Z2AI.js.map +1 -0
  17. package/dist/{chunk-CXFUP2YK.cjs → chunk-EDR5SFJN.cjs} +46 -6
  18. package/dist/chunk-EDR5SFJN.cjs.map +1 -0
  19. package/dist/{chunk-FIKTQR7H.js → chunk-I2P3TIP7.js} +2 -2
  20. package/dist/{chunk-BNTVOKYT.cjs → chunk-KJKDLD7N.cjs} +51 -9
  21. package/dist/chunk-KJKDLD7N.cjs.map +1 -0
  22. package/dist/{chunk-VQSRCMMK.js → chunk-QGO6X6LG.js} +2 -15
  23. package/dist/chunk-QGO6X6LG.js.map +1 -0
  24. package/dist/{chunk-IK4UK7KT.js → chunk-W23EJNYG.js} +44 -4
  25. package/dist/chunk-W23EJNYG.js.map +1 -0
  26. package/dist/{chunk-CAE2BVKI.cjs → chunk-Z2V525IS.cjs} +6 -6
  27. package/dist/{chunk-CAE2BVKI.cjs.map → chunk-Z2V525IS.cjs.map} +1 -1
  28. package/dist/contract/index.cjs +2 -5
  29. package/dist/contract/index.cjs.map +1 -1
  30. package/dist/contract/index.d.cts +2 -4
  31. package/dist/contract/index.d.ts +2 -4
  32. package/dist/contract/index.js +1 -4
  33. package/dist/eip712/index.cjs +9 -3
  34. package/dist/eip712/index.cjs.map +1 -1
  35. package/dist/eip712/index.d.cts +44 -2
  36. package/dist/eip712/index.d.ts +44 -2
  37. package/dist/eip712/index.js +8 -2
  38. package/dist/{index-CNALKsH1.d.ts → index-B06IJlHe.d.ts} +1 -1
  39. package/dist/{index-BpUYHGu3.d.cts → index-B7pGBych.d.cts} +1 -1
  40. package/dist/index.cjs +106 -200
  41. package/dist/index.cjs.map +1 -1
  42. package/dist/index.d.cts +370 -258
  43. package/dist/index.d.ts +370 -258
  44. package/dist/index.js +104 -198
  45. package/dist/index.js.map +1 -1
  46. package/dist/quoting/index.cjs +3 -3
  47. package/dist/quoting/index.d.cts +1 -1
  48. package/dist/quoting/index.d.ts +1 -1
  49. package/dist/quoting/index.js +2 -2
  50. package/dist/swap/index.cjs +2 -3
  51. package/dist/swap/index.cjs.map +1 -1
  52. package/dist/swap/index.d.cts +2 -2
  53. package/dist/swap/index.d.ts +2 -2
  54. package/dist/swap/index.js +1 -2
  55. package/dist/{types-BDOnH5Le.d.cts → types-b5_Tokjl.d.cts} +8 -17
  56. package/dist/{types-BDOnH5Le.d.ts → types-b5_Tokjl.d.ts} +8 -17
  57. package/package.json +1 -1
  58. package/dist/chunk-27V32VNM.cjs +0 -370
  59. package/dist/chunk-27V32VNM.cjs.map +0 -1
  60. package/dist/chunk-4RYBJLF3.js +0 -370
  61. package/dist/chunk-4RYBJLF3.js.map +0 -1
  62. package/dist/chunk-5QJZT7VB.cjs +0 -46
  63. package/dist/chunk-5QJZT7VB.cjs.map +0 -1
  64. package/dist/chunk-BNTVOKYT.cjs.map +0 -1
  65. package/dist/chunk-C4ZDYG4D.js.map +0 -1
  66. package/dist/chunk-CWP4PFOP.cjs.map +0 -1
  67. package/dist/chunk-CXFUP2YK.cjs.map +0 -1
  68. package/dist/chunk-IK4UK7KT.js.map +0 -1
  69. package/dist/chunk-L74CZAVQ.cjs +0 -99
  70. package/dist/chunk-L74CZAVQ.cjs.map +0 -1
  71. package/dist/chunk-P56TUGTS.js +0 -46
  72. package/dist/chunk-P56TUGTS.js.map +0 -1
  73. package/dist/chunk-R4L66ZR5.js.map +0 -1
  74. package/dist/chunk-VQSRCMMK.js.map +0 -1
  75. package/dist/chunk-X3I5XWAR.cjs.map +0 -1
  76. package/dist/chunk-X4IXUTTD.js +0 -99
  77. package/dist/chunk-X4IXUTTD.js.map +0 -1
  78. package/dist/relay/index.cjs +0 -19
  79. package/dist/relay/index.cjs.map +0 -1
  80. package/dist/relay/index.d.cts +0 -75
  81. package/dist/relay/index.d.ts +0 -75
  82. package/dist/relay/index.js +0 -19
  83. package/dist/relay/index.js.map +0 -1
  84. /package/dist/{chunk-5YH4D7QF.js.map → chunk-7UBO7DY5.js.map} +0 -0
  85. /package/dist/{chunk-FIKTQR7H.js.map → chunk-I2P3TIP7.js.map} +0 -0
@@ -1 +1 @@
1
- {"version":3,"sources":["/Users/phitran/Pacific-Finance/pafi-backend/pafi-sdk/packages/core/dist/index.cjs","../src/index.ts","../src/userop/types.ts","../src/paymaster/config.ts","../src/utils/checkEthAndBranch.ts","../src/contracts/mocks/pointTokenV2.mock.ts","../src/contracts/mocks/batchExecutor.mock.ts","../src/contracts/mocks/addresses.mock.ts","../src/contracts/mocks/eip712/burnConsent.mock.ts","../src/web-handoff/webPopup.ts","../src/web-handoff/index.ts"],"names":[],"mappings":"AAAA;AACE;AACF,wDAA6B;AAC7B;AACE;AACA;AACA;AACF,wDAA6B;AAC7B;AACE;AACA;AACA;AACA;AACA;AACA;AACA;AACA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;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA","file":"/Users/phitran/Pacific-Finance/pafi-backend/pafi-sdk/packages/core/dist/index.cjs","sourcesContent":[null,"import { createPublicClient, http } from \"viem\";\nimport type { Address, Hex, PublicClient, WalletClient } from \"viem\";\n\n// -------------------------------------------------------------------------\n// Re-export all sub-modules\n// -------------------------------------------------------------------------\nexport * from \"./types\";\nexport * from \"./constants\";\nexport * from \"./errors\";\nexport * from \"./abi/index\";\nexport * from \"./eip712/index\";\nexport * from \"./relay/index\";\nexport * from \"./contract/index\";\nexport * from \"./quoting/index\";\nexport * from \"./swap/index\";\nexport * from \"./auth/index\";\n\n// v1.4 — Account Abstraction primitives (EIP-7702 + ERC-4337 v0.7)\nexport * from \"./userop/index\";\nexport * from \"./paymaster/index\";\nexport * from \"./utils/index\";\n\n// v1.4 — Contract ABIs + addresses + EIP-712 v2 types.\n// MOCKED until SC team ships real ABIs. See `src/contracts/mocks/README.md`.\n// Consumers: `import { RELAYER_V2_ABI, buildBurnConsentTypedData, ... } from '@pafi-dev/core'`\n// The re-export swaps mock → real in one file when SC delivers.\nexport * from \"./contracts/index\";\n\n// v1.5 — PAFI Web handoff (mobile + desktop modal helper).\n// `openPafiWebModal()` + adapter registry for platform-specific UX.\nexport * from \"./web-handoff/index\";\n\n// -------------------------------------------------------------------------\n// Internal imports for PafiSDK class\n// -------------------------------------------------------------------------\nimport { buildMintRequestTypedData, signMintRequest, verifyMintRequest } from \"./eip712/mintRequest\";\nimport {\n buildReceiverConsentTypedData,\n signReceiverConsent,\n verifyReceiverConsent,\n} from \"./eip712/receiverConsent\";\nimport {\n getMintRequestNonce,\n getReceiverConsentNonce,\n getTokenName,\n} from \"./contract/pointToken\";\nimport {\n encodeMintAndSwap,\n decodeMintAndSwap,\n encodeExtData,\n buildRelaySwapParams,\n} from \"./relay/calldata\";\nimport { findBestQuote } from \"./quoting/quote\";\nimport {\n buildSwapFromQuote,\n buildUniversalRouterExecuteArgs,\n} from \"./swap/universalRouter\";\nimport { simulateMintAndSwap } from \"./relay/simulate\";\nimport { simulateSwap } from \"./swap/simulate\";\nimport type { SimulationResult } from \"./relay/simulate\";\nimport type { SwapSimulationResult } from \"./swap/simulate\";\nimport { createLoginMessage } from \"./auth/loginMessage\";\nimport type { LoginMessageParams } from \"./auth/types\";\nimport { ConfigurationError } from \"./errors\";\nimport type {\n BestQuote,\n EIP712Signature,\n MintParams,\n MintRequest,\n PafiSDKConfig,\n PathKey,\n PointTokenDomainConfig,\n PoolKey,\n QuoteResult,\n ReceiverConsent,\n SignatureVerification,\n SwapParams,\n} from \"./types\";\n\n// -------------------------------------------------------------------------\n// PafiSDK — convenience class wrapping all contract + crypto primitives.\n//\n// This class is HTTP-client-free on purpose. It covers signing, verifying,\n// contract reads, and calldata encoding — the things that need a signer\n// or a provider but no HTTP layer. The issuer backend defines its own HTTP\n// contract via `@pafi/issuer`; frontends build `fetch()` calls against\n// those types directly.\n// -------------------------------------------------------------------------\n\nexport class PafiSDK {\n private _pointTokenAddress?: Address;\n private _relayContractAddress?: Address;\n private _signer?: WalletClient;\n private _provider?: PublicClient;\n private _chainId?: number;\n\n constructor(config: PafiSDKConfig) {\n this._pointTokenAddress = config.pointTokenAddress;\n this._relayContractAddress = config.relayContractAddress;\n this._signer = config.signer;\n this._chainId = config.chainId;\n\n if (config.provider) {\n this._provider = config.provider;\n } else if (config.rpcUrl) {\n this._provider = createPublicClient({\n transport: http(config.rpcUrl),\n });\n }\n }\n\n // -------------------------------------------------------------------------\n // Setters\n // -------------------------------------------------------------------------\n\n setPointTokenAddress(address: Address): void {\n this._pointTokenAddress = address;\n }\n\n setRelayContractAddress(address: Address): void {\n this._relayContractAddress = address;\n }\n\n setSigner(signer: WalletClient): void {\n this._signer = signer;\n }\n\n setProvider(provider: PublicClient): void {\n this._provider = provider;\n }\n\n // -------------------------------------------------------------------------\n // Private guards\n // -------------------------------------------------------------------------\n\n private requirePointToken(): Address {\n if (!this._pointTokenAddress) {\n throw new ConfigurationError(\"pointTokenAddress not set\");\n }\n return this._pointTokenAddress;\n }\n\n private requireProvider(): PublicClient {\n if (!this._provider) {\n throw new ConfigurationError(\"provider not set\");\n }\n return this._provider;\n }\n\n private requireSigner(): WalletClient {\n if (!this._signer) {\n throw new ConfigurationError(\"signer not set\");\n }\n return this._signer;\n }\n\n private requireChainId(): number {\n if (this._chainId === undefined) {\n throw new ConfigurationError(\"chainId not set\");\n }\n return this._chainId;\n }\n\n // -------------------------------------------------------------------------\n // Domain\n // -------------------------------------------------------------------------\n\n async getDomain(): Promise<PointTokenDomainConfig> {\n const provider = this.requireProvider();\n const pointToken = this.requirePointToken();\n const chainId = this.requireChainId();\n const name = await getTokenName(provider, pointToken);\n return { name, verifyingContract: pointToken, chainId };\n }\n\n // -------------------------------------------------------------------------\n // EIP-712 — delegates to pure functions\n // -------------------------------------------------------------------------\n\n /**\n * Build the EIP-712 typed data for a MintRequest.\n * Pass the result to any external signer (Privy, WalletConnect, etc.).\n */\n async buildMintRequestTypedData(message: MintRequest) {\n const domain = await this.getDomain();\n return buildMintRequestTypedData(domain, message);\n }\n\n /**\n * Build the EIP-712 typed data for a ReceiverConsent.\n * Pass the result to any external signer (Privy, WalletConnect, etc.).\n */\n async buildReceiverConsentTypedData(message: ReceiverConsent) {\n const domain = await this.getDomain();\n return buildReceiverConsentTypedData(domain, message);\n }\n\n async signMintRequest(message: MintRequest): Promise<EIP712Signature> {\n const domain = await this.getDomain();\n return signMintRequest(this.requireSigner(), domain, message);\n }\n\n async verifyMintRequest(\n message: MintRequest,\n signature: Hex,\n expectedMinter: Address,\n ): Promise<SignatureVerification> {\n const domain = await this.getDomain();\n return verifyMintRequest(domain, message, signature, expectedMinter);\n }\n\n async signReceiverConsent(\n message: ReceiverConsent,\n ): Promise<EIP712Signature> {\n const domain = await this.getDomain();\n return signReceiverConsent(this.requireSigner(), domain, message);\n }\n\n async verifyReceiverConsent(\n message: ReceiverConsent,\n signature: Hex,\n expectedReceiver: Address,\n ): Promise<SignatureVerification> {\n const domain = await this.getDomain();\n return verifyReceiverConsent(domain, message, signature, expectedReceiver);\n }\n\n // -------------------------------------------------------------------------\n // Contract reads\n // -------------------------------------------------------------------------\n\n async getMintRequestNonce(receiver: Address): Promise<bigint> {\n return getMintRequestNonce(\n this.requireProvider(),\n this.requirePointToken(),\n receiver,\n );\n }\n\n async getReceiverConsentNonce(receiver: Address): Promise<bigint> {\n return getReceiverConsentNonce(\n this.requireProvider(),\n this.requirePointToken(),\n receiver,\n );\n }\n\n // -------------------------------------------------------------------------\n // Relay calldata — delegates to pure functions\n // -------------------------------------------------------------------------\n\n encodeMintAndSwap(mint: MintParams, swap: SwapParams): Hex {\n return encodeMintAndSwap(mint, swap);\n }\n\n decodeMintAndSwap(calldata: Hex): { mint: MintParams; swap: SwapParams } {\n return decodeMintAndSwap(calldata);\n }\n\n // -------------------------------------------------------------------------\n // Quoting — delegates to pure functions\n // -------------------------------------------------------------------------\n\n /**\n * Find the best swap route from `tokenIn` to `tokenOut`.\n * Merges `pools` with COMMON_POOLS for the configured chain, builds all\n * paths, and quotes via a single multicall RPC call.\n */\n async findBestQuote(\n tokenIn: Address,\n tokenOut: Address,\n exactAmount: bigint,\n pools: PoolKey[] = [],\n quoterAddress?: Address,\n maxHops?: number,\n ): Promise<BestQuote> {\n return findBestQuote(\n this.requireProvider(),\n this.requireChainId(),\n tokenIn,\n tokenOut,\n exactAmount,\n pools,\n quoterAddress,\n maxHops,\n );\n }\n\n // -------------------------------------------------------------------------\n // Swap building — delegates to pure functions\n // -------------------------------------------------------------------------\n\n /**\n * Build UniversalRouter execute args from a quote result.\n * The caller provides `minAmountOut` after applying their own slippage.\n */\n buildSwapFromQuote(params: {\n quote: QuoteResult;\n currencyIn: Address;\n currencyOut: Address;\n amountIn: bigint;\n minAmountOut: bigint;\n }): { commands: Hex; inputs: Hex[] } {\n return buildSwapFromQuote(params);\n }\n\n /**\n * Build Relay SwapParams + extData from a quote result.\n * Returns ready-to-use args for `Relay.mintAndSwap`.\n */\n buildRelaySwapParams(params: {\n quote: { path: PathKey[] };\n minAmountOut: bigint;\n feeInUsdt: bigint;\n deadline: bigint;\n }): { swapParams: SwapParams; extData: Hex } {\n return buildRelaySwapParams(params);\n }\n\n /**\n * Encode extData for ReceiverConsent and MintParams.\n * extData = abi.encode(minAmountOut, feeInUsdt)\n */\n encodeExtData(minAmountOut: bigint, feeInUsdt: bigint): Hex {\n return encodeExtData(minAmountOut, feeInUsdt);\n }\n\n // -------------------------------------------------------------------------\n // Simulation — dry-run via eth_call (no gas spent)\n // -------------------------------------------------------------------------\n\n /**\n * Simulate a Relay.mintAndSwap call. Catches reverts (bad signatures,\n * expired deadlines, insufficient mint cap, pool errors) before submitting.\n *\n * @param relayAddress - Relay contract address\n * @param mint - MintParams with real signatures\n * @param swap - SwapParams (path + deadline)\n * @param from - Relayer address that will submit the tx\n */\n async simulateMintAndSwap(\n relayAddress: Address,\n mint: MintParams,\n swap: SwapParams,\n from: Address,\n ): Promise<SimulationResult> {\n return simulateMintAndSwap(\n this.requireProvider(),\n relayAddress,\n mint,\n swap,\n from,\n );\n }\n\n /**\n * Simulate a UniversalRouter.execute swap call. Catches reverts (bad\n * approvals, insufficient balance, pool errors) before submitting.\n *\n * @param routerAddress - UniversalRouter contract address\n * @param commands - Packed command bytes (from buildSwapFromQuote)\n * @param inputs - Encoded inputs (from buildSwapFromQuote)\n * @param deadline - Unix timestamp\n * @param from - Address that will execute the swap\n */\n async simulateSwap(\n routerAddress: Address,\n commands: Hex,\n inputs: Hex[],\n deadline: bigint,\n from: Address,\n ): Promise<SwapSimulationResult> {\n return simulateSwap(\n this.requireProvider(),\n routerAddress,\n commands,\n inputs,\n deadline,\n from,\n );\n }\n\n // -------------------------------------------------------------------------\n // Auth — EIP-4361 login helpers (offline, stateless)\n //\n // These are convenience wrappers around the pure functions in\n // `./auth/loginMessage.ts`. They do NOT hit the network — the caller is\n // responsible for fetching the nonce, POSTing the signed message, and\n // storing the JWT returned by the issuer backend.\n // -------------------------------------------------------------------------\n\n /**\n * Build an EIP-4361 login message for the current signer + chain. The\n * caller supplies the issuer-specific fields (domain, nonce, uri); the SDK\n * fills in the wallet address and chain id from its own config.\n */\n async createLoginMessage(\n params: Omit<LoginMessageParams, \"address\" | \"chainId\">,\n ): Promise<string> {\n const signer = this.requireSigner();\n const chainId = this.requireChainId();\n const account = signer.account;\n if (!account) {\n throw new ConfigurationError(\"signer has no account attached\");\n }\n return createLoginMessage({ ...params, address: account.address, chainId });\n }\n\n /** Sign a login message string with the current signer (personal_sign) */\n async signLoginMessage(message: string): Promise<Hex> {\n const signer = this.requireSigner();\n const account = signer.account;\n if (!account) {\n throw new ConfigurationError(\"signer has no account attached\");\n }\n return signer.signMessage({ account, message });\n }\n}\n","import type { Address, Hex } from \"viem\";\n\n/**\n * ERC-4337 v0.7 EntryPoint standard address (deployed deterministically\n * at the same address across chains).\n * https://eips.ethereum.org/EIPS/eip-4337\n */\nexport const ENTRY_POINT_V07: Address =\n \"0x0000000071727De22E5E9d8BAf0edAc6f37da032\";\n\n/**\n * A single call inside a batch. `BatchExecutor.execute(Call[])` iterates\n * and invokes each one. When the batch runs via EIP-7702 delegation,\n * `msg.sender` for each call is the user's EOA.\n */\nexport interface Operation {\n target: Address;\n value: bigint;\n data: Hex;\n}\n\n/**\n * Paymaster fields attached to a UserOperation. Populated by the\n * Coinbase Paymaster (via PAFI Backend proxy) before the user signs.\n */\nexport interface PaymasterFields {\n paymaster: Address;\n paymasterData: Hex;\n paymasterVerificationGasLimit: bigint;\n paymasterPostOpGasLimit: bigint;\n}\n\n/**\n * Partial UserOp used during preparation — before paymaster fields are\n * attached or the user signs.\n */\nexport interface PartialUserOperation {\n sender: Address;\n nonce: bigint;\n callData: Hex;\n callGasLimit: bigint;\n verificationGasLimit: bigint;\n preVerificationGas: bigint;\n maxFeePerGas: bigint;\n maxPriorityFeePerGas: bigint;\n}\n\n/**\n * Full ERC-4337 v0.7 UserOperation, ready for bundler submission.\n */\nexport interface UserOperation extends PartialUserOperation {\n paymaster: Address;\n paymasterData: Hex;\n paymasterVerificationGasLimit: bigint;\n paymasterPostOpGasLimit: bigint;\n signature: Hex;\n}\n\n/**\n * Receipt returned by a bundler after a UserOp lands on-chain.\n */\nexport interface UserOpReceipt {\n userOpHash: Hex;\n success: boolean;\n txHash: Hex;\n blockNumber: bigint;\n gasUsed: bigint;\n /** Effective gas cost paid (wei). */\n actualGasCost: bigint;\n}\n\n/**\n * Sentinel operation value used in tests + docs when `Operation.value`\n * is irrelevant (ERC-20 transfers, for example).\n */\nexport const ZERO_VALUE = 0n;\n","import type { PaymasterConfig } from \"./types\";\n\n/**\n * Module-level paymaster config. Read by batch builders (via\n * `getPaymasterConfig()`) and by `@pafi/issuer` `RelayService` when\n * building UserOps.\n *\n * Consumers call `setPaymasterConfig()` once at application boot. All\n * subsequent helpers that need the feeRecipient / issuer identity /\n * backend URL pull from here.\n *\n * This is global state by design — making every batch builder take a\n * config param would clutter every call site. The alternative (a\n * context/service) has more ceremony than this flow justifies.\n */\nlet _config: PaymasterConfig | null = null;\n\n/**\n * Set the application-wide paymaster config. Safe to call multiple\n * times (later calls override earlier). Throws if required fields\n * are missing.\n */\nexport function setPaymasterConfig(config: PaymasterConfig): void {\n if (!config.pafiBackendUrl) {\n throw new Error(\"setPaymasterConfig: pafiBackendUrl is required\");\n }\n if (!config.issuerId) {\n throw new Error(\"setPaymasterConfig: issuerId is required\");\n }\n if (!config.apiKey) {\n throw new Error(\"setPaymasterConfig: apiKey is required\");\n }\n if (!config.feeRecipient) {\n throw new Error(\"setPaymasterConfig: feeRecipient is required\");\n }\n _config = { ...config };\n}\n\n/**\n * Get the current paymaster config. Throws if `setPaymasterConfig()`\n * has not been called yet — this surfaces boot-order bugs early\n * instead of failing with \"paymaster.feeRecipient is undefined\" at\n * the point of use.\n */\nexport function getPaymasterConfig(): PaymasterConfig {\n if (!_config) {\n throw new Error(\n \"PaymasterConfig not initialized — call setPaymasterConfig() at application boot before invoking any batch builder\",\n );\n }\n return _config;\n}\n\n/** Test helper — clear the singleton. */\nexport function _resetPaymasterConfigForTests(): void {\n _config = null;\n}\n\n/** Check whether paymaster config has been initialized. */\nexport function isPaymasterConfigured(): boolean {\n return _config !== null;\n}\n","import type { Address, PublicClient } from \"viem\";\n\n/**\n * Submission path chosen by `checkEthAndBranch`.\n * - `normal`: initiator has enough ETH; submit via `walletClient.writeContract`\n * or a plain `eth_sendRawTransaction`. No paymaster round-trip.\n * - `paymaster`: initiator doesn't have enough ETH; wrap the batch as a\n * UserOperation and route through PAFI Backend → Coinbase Paymaster\n * → Bundler.\n */\nexport type SubmissionPath = \"normal\" | \"paymaster\";\n\nexport interface CheckEthAndBranchParams {\n /** viem PublicClient bound to the target chain. */\n client: PublicClient;\n /** The address whose ETH balance we check. */\n initiator: Address;\n /** Estimated gas cost in wei for the upcoming tx. */\n estimatedGasWei: bigint;\n /**\n * Optional safety margin multiplier (basis points). Defaults to\n * 11_000 (110%) — the initiator needs 10% above the estimate to\n * qualify for the normal path. Prevents edge cases where gas price\n * spikes between estimation and submission cause a \"has enough\"\n * decision to fail at broadcast time.\n */\n marginBps?: number;\n}\n\nconst DEFAULT_MARGIN_BPS = 11_000;\n\n/**\n * Step 3 of the Generalized Flow ([SPONSORED_PATH_FLOW.md §2]):\n * choose between the normal path (initiator pays ETH directly) and the\n * paymaster path (bundler + Coinbase Paymaster).\n *\n * Intentionally synchronous in spirit — the only network call is\n * `getBalance`. Callers can parallelize it with other reads.\n */\nexport async function checkEthAndBranch(\n params: CheckEthAndBranchParams,\n): Promise<SubmissionPath> {\n const marginBps = params.marginBps ?? DEFAULT_MARGIN_BPS;\n const required =\n (params.estimatedGasWei * BigInt(marginBps)) / 10_000n;\n\n const balance = await params.client.getBalance({\n address: params.initiator,\n });\n\n return balance >= required ? \"normal\" : \"paymaster\";\n}\n","import { parseAbi } from \"viem\";\n\n/**\n * ⚠️ MOCK — `PointToken` v1.4 surface (mint + burn).\n *\n * ## Mint (NEW direct flow — no Relayer)\n *\n * In v1.4 the user calls `PointToken.mint()` directly via an EIP-7702\n * delegated UserOp — `msg.sender == user`. The contract checks the\n * caller is on its authorized minter allowlist. **No Relayer contract,\n * no MintRequest EIP-712 signature.** Backend (gg56) only validates\n * off-chain (balance, policy, KYC) before returning the unsigned UserOp.\n *\n * The mock signature `mint(uint256 amount)` mints to `msg.sender`.\n * SC team confirmation pending — they may pick `mint(address to,\n * uint256 amount)` instead. Either is a 1-line ABI change here.\n *\n * ## Burn — two variants mocked\n *\n * Variant A (simpler, most likely):\n * burn(uint256 amount)\n * - burns from `msg.sender` (user via EIP-7702)\n *\n * Variant B (signature-based, if SC prefers explicit on-chain consent):\n * burnWithSig(BurnConsent consent, Signature sig)\n * - verifies EIP-712 signature before burning\n *\n * Either way the ERC-20 emits `Transfer(from, address(0), amount)` so\n * `BurnIndexer` semantics don't change.\n */\nexport const MOCK_POINT_TOKEN_V2_ABI = parseAbi([\n // --- Mint (v1.4 direct flow, no Relayer) ---\n \"function mint(uint256 amount) external\",\n // SC may instead pick: \"function mint(address to, uint256 amount) external\"\n // Authorization check (off-chain reader for gg56 to verify BEFORE returning UserOp)\n \"function minters(address user) external view returns (bool)\",\n\n // --- Burn (v1.4 reverse flow, Scenario 2) ---\n \"function burn(uint256 amount) external\",\n \"function burnWithSig((address user, address pointToken, uint256 amount, uint256 nonce, uint256 deadline) consent, (uint8 v, bytes32 r, bytes32 s) sig) external\",\n\n // --- Standard reads ---\n \"function balanceOf(address user) external view returns (uint256)\",\n \"function burnNonce(address user) external view returns (uint256)\",\n\n // --- Events ---\n // PointIndexer filters Transfer(from=0x0) for mints\n // BurnIndexer filters Transfer(to=0x0) for burns\n \"event Transfer(address indexed from, address indexed to, uint256 value)\",\n] as const);\n","import { parseAbi } from \"viem\";\nimport type { Address } from \"viem\";\n\n/**\n * ⚠️ MOCK — placeholder BatchExecutor address.\n *\n * Real deployment:\n * - Coinbase may pre-deploy a canonical BatchExecutor that we target\n * via EIP-7702 delegation (see blocker B2 in V1.4_V1.5_READINESS.md)\n * - Otherwise PAFI deploys a minimal one and publishes the address\n *\n * The ABI itself (`execute(Call[])`) is stable and lives under\n * `../../userop/batchExecute.ts` — that's the real one, unchanged\n * by the mock swap. Only the **address** is mocked here.\n *\n * Pattern: checksum address with hex \"DEAD0001\" suffix per chain so\n * it's obvious in logs which chain is using a mock.\n */\n\n// Base Sepolia (testnet)\nexport const MOCK_BATCH_EXECUTOR_ADDRESS_BASE_SEPOLIA =\n \"0x000000000000000000000000000000000000DE01\" as Address;\n\n// Base mainnet\nexport const MOCK_BATCH_EXECUTOR_ADDRESS_BASE_MAINNET =\n \"0x000000000000000000000000000000000000DE02\" as Address;\n\n// Re-export the real ABI from userop module (not mocked — ABI is stable)\nexport { BATCH_EXECUTOR_ABI } from \"../../userop/batchExecute\";\n","import type { Address } from \"viem\";\n\n/**\n * ⚠️ MOCK — per-chain contract addresses for the v1.4 sponsored flow.\n *\n * Real addresses come from SC team once they deploy Relayer v2 and\n * pick a BatchExecutor. Until then we use placeholders so the SDK\n * code path compiles + tests execute end-to-end.\n *\n * **Intentionally not merge-safe to mainnet** — callers that resolve\n * a mainnet address here get a `0x...DEAD` placeholder which will\n * revert at contract-level. That's the point: prod refuses to run\n * on mocks.\n *\n * Chain id map:\n * - 8453 Base mainnet\n * - 84532 Base Sepolia\n *\n * Swap workflow when SC delivers:\n * 1. Rename this file → `addresses.ts` under `src/contracts/real/`\n * 2. Fill real addresses per chain\n * 3. Update `src/contracts/index.ts` re-export\n * 4. Delete MOCK_* named exports\n */\n\n/**\n * Per-chain contract addresses.\n *\n * v1.4 update: `relayerV2` field dropped — flow now calls\n * `PointToken.mint()` directly via EIP-7702 delegation. No Relayer\n * contract sits between user and PointToken.\n */\nexport interface ContractAddresses {\n pointToken: Address;\n batchExecutor: Address;\n usdt: Address;\n issuerRegistry: Address;\n mintingOracle: Address;\n}\n\nconst MOCK_PLACEHOLDER = (suffix: string): Address =>\n `0x000000000000000000000000000000000000${suffix.toLowerCase().padStart(4, \"0\")}` as Address;\n\nexport const MOCK_ADDRESSES: Record<number, ContractAddresses> = {\n // Base Sepolia — safe targets for integration tests (Hardhat fixtures\n // override at test time)\n 84532: {\n pointToken: MOCK_PLACEHOLDER(\"de11\"),\n batchExecutor: MOCK_PLACEHOLDER(\"de01\"),\n usdt: MOCK_PLACEHOLDER(\"de12\"),\n issuerRegistry: MOCK_PLACEHOLDER(\"de13\"),\n mintingOracle: MOCK_PLACEHOLDER(\"de14\"),\n },\n // Base mainnet — intentionally placeholder. Do NOT ship to prod\n // without swapping with real addresses.\n 8453: {\n pointToken: MOCK_PLACEHOLDER(\"dead\"),\n batchExecutor: MOCK_PLACEHOLDER(\"dead\"),\n usdt: MOCK_PLACEHOLDER(\"dead\"),\n issuerRegistry: MOCK_PLACEHOLDER(\"dead\"),\n mintingOracle: MOCK_PLACEHOLDER(\"dead\"),\n },\n};\n\n/**\n * Lookup helper — throws if the chain isn't in the map so callers fail\n * loudly on misconfiguration instead of silently using `undefined`.\n */\nexport function getMockAddresses(chainId: number): ContractAddresses {\n const addrs = MOCK_ADDRESSES[chainId];\n if (!addrs) {\n throw new Error(\n `getMockAddresses: no mock addresses for chainId ${chainId}. ` +\n `Supported: ${Object.keys(MOCK_ADDRESSES).join(\", \")}`,\n );\n }\n return addrs;\n}\n","import {\n parseSignature,\n recoverTypedDataAddress,\n type Address,\n type Hex,\n type WalletClient,\n} from \"viem\";\nimport { buildDomain } from \"../../../eip712/domain\";\nimport type {\n EIP712Signature,\n PointTokenDomainConfig,\n SignatureVerification,\n} from \"../../../types\";\n\n/**\n * ⚠️ MOCK — `BurnConsent` EIP-712 type for the v1.4 reverse flow.\n *\n * New type entirely — v0.2.x had no burn-for-credit flow.\n *\n * User signs `BurnConsent` to authorize burning `amount` PT from their\n * wallet in exchange for an off-chain credit of (amount - gasFee).\n * Signature is consumed either by:\n * - A relayer calling `PointToken.burnWithSig(...)` (Variant B)\n * - The paymaster-proxy-sponsored UserOp calling `PointToken.burn(...)`\n * with msg.sender = user via EIP-7702 (Variant A)\n *\n * Either way the tx emits `Transfer(user → 0x0)` which the issuer's\n * `BurnIndexer` watches for and uses to credit the off-chain ledger.\n *\n * Field list is a best-guess — SC team may add fields (e.g. `feeAmount`\n * explicit, `extData`). Update this mock when they freeze the spec.\n */\nexport interface MockBurnConsent {\n user: Address;\n pointToken: Address;\n amount: bigint;\n nonce: bigint;\n deadline: bigint;\n}\n\nexport const MOCK_BURN_CONSENT_TYPES = {\n BurnConsent: [\n { name: \"user\", type: \"address\" },\n { name: \"pointToken\", type: \"address\" },\n { name: \"amount\", type: \"uint256\" },\n { name: \"nonce\", type: \"uint256\" },\n { name: \"deadline\", type: \"uint256\" },\n ],\n} as const;\n\nexport function buildMockBurnConsentTypedData(\n domain: PointTokenDomainConfig,\n message: MockBurnConsent,\n) {\n return {\n domain: buildDomain(domain),\n types: MOCK_BURN_CONSENT_TYPES,\n primaryType: \"BurnConsent\" as const,\n message,\n };\n}\n\nexport async function signMockBurnConsent(\n walletClient: WalletClient,\n domain: PointTokenDomainConfig,\n message: MockBurnConsent,\n): Promise<EIP712Signature> {\n const serialized = await walletClient.signTypedData({\n account: walletClient.account!,\n domain: buildDomain(domain),\n types: MOCK_BURN_CONSENT_TYPES,\n primaryType: \"BurnConsent\",\n message,\n });\n\n const { v, r, s } = parseSignature(serialized);\n return {\n v: Number(v),\n r,\n s,\n serialized,\n };\n}\n\nexport async function verifyMockBurnConsent(\n domain: PointTokenDomainConfig,\n message: MockBurnConsent,\n signature: Hex,\n expectedUser: Address,\n): Promise<SignatureVerification> {\n const recoveredAddress = await recoverTypedDataAddress({\n domain: buildDomain(domain),\n types: MOCK_BURN_CONSENT_TYPES,\n primaryType: \"BurnConsent\",\n message,\n signature,\n });\n\n const isValid =\n recoveredAddress.toLowerCase() === expectedUser.toLowerCase();\n\n return {\n isValid,\n recoveredAddress,\n };\n}\n","import type {\n ModalOpenOptions,\n PafiWebModalAdapter,\n PafiWebModalHandle,\n} from \"./types\";\n\nconst DEFAULT_WIDTH = 900;\nconst DEFAULT_HEIGHT = 700;\nconst DEFAULT_NAME = \"pafi-web\";\n\n/**\n * Web browser popup adapter. Opens the given URL in a centered\n * `window.open()` popup, polls for close, and optionally forwards\n * `postMessage` events back to the caller.\n *\n * Runtime requirement: `window.open` must exist. Throws if called\n * under Node / SSR / React Native — use `setPafiWebModalAdapter()` to\n * provide a platform-specific adapter in those environments.\n *\n * ## Popup blocking\n *\n * Browsers block `window.open()` unless it happens inside a user\n * gesture (click handler). Callers MUST wire this into a direct click\n * handler — wrapping it in a `setTimeout` or async await before the\n * open call will trigger the blocker.\n */\nexport function openWebPopup(\n url: string,\n options: ModalOpenOptions = {},\n): PafiWebModalHandle {\n if (typeof window === \"undefined\" || typeof window.open !== \"function\") {\n throw new Error(\n \"openWebPopup: `window.open` is not available in this runtime. \" +\n \"Register a platform adapter via setPafiWebModalAdapter() instead.\",\n );\n }\n\n const width = options.width ?? DEFAULT_WIDTH;\n const height = options.height ?? DEFAULT_HEIGHT;\n const name = options.windowName ?? DEFAULT_NAME;\n\n // Center on the screen — works in all major browsers. Falls back\n // gracefully if `screen.availWidth`/`screenX` are unavailable.\n const screenW = window.screen?.availWidth ?? window.innerWidth;\n const screenH = window.screen?.availHeight ?? window.innerHeight;\n const left = Math.max(0, Math.floor((screenW - width) / 2));\n const top = Math.max(0, Math.floor((screenH - height) / 2));\n\n const features = [\n `width=${width}`,\n `height=${height}`,\n `left=${left}`,\n `top=${top}`,\n \"resizable=yes\",\n \"scrollbars=yes\",\n \"noopener=no\", // we need opener.postMessage to work\n ].join(\",\");\n\n const popup = window.open(url, name, features);\n if (!popup) {\n throw new Error(\n \"openWebPopup: popup was blocked. Ensure this call runs inside a user gesture (click handler).\",\n );\n }\n\n // Set up state + listeners --------------------------------------------\n\n let closed = false;\n let pollId: ReturnType<typeof setInterval> | null = null;\n let messageListener: ((e: MessageEvent) => void) | null = null;\n\n const dispose = (): void => {\n if (closed) return;\n closed = true;\n if (pollId !== null) {\n clearInterval(pollId);\n pollId = null;\n }\n if (messageListener) {\n window.removeEventListener(\"message\", messageListener);\n messageListener = null;\n }\n options.onClose?.();\n };\n\n // Poll every 500ms for popup close — there's no `close` event.\n // Stops when `popup.closed` flips to true OR our handle is closed.\n pollId = setInterval(() => {\n if (popup.closed) {\n dispose();\n }\n }, 500);\n\n // Wire postMessage filtering by origin — secure-by-default. An\n // empty or missing `allowedOrigins` rejects ALL messages; the\n // caller must explicitly whitelist PAFI Web's host(s) before any\n // payload is delivered. This prevents a compromised popup (via\n // opener leak or redirect) from impersonating PAFI Web.\n if (options.onMessage) {\n const allowed = options.allowedOrigins ?? [];\n const onMessage = options.onMessage;\n messageListener = (event: MessageEvent): void => {\n if (event.source !== popup) return;\n if (!allowed.includes(event.origin)) return;\n onMessage(event.data, event.origin);\n };\n window.addEventListener(\"message\", messageListener);\n }\n\n // Handle object -------------------------------------------------------\n\n return {\n get isOpen(): boolean {\n return !closed && !popup.closed;\n },\n close(): void {\n if (closed) return;\n try {\n popup.close();\n } catch {\n // Some browsers block close() unless the popup was opened by\n // the same document. Dispose our listeners anyway.\n }\n dispose();\n },\n focus(): void {\n if (closed || popup.closed) return;\n try {\n popup.focus();\n } catch {\n // No-op on failure — focus is best-effort.\n }\n },\n postMessage(data: unknown): void {\n if (closed || popup.closed) return;\n try {\n // targetOrigin '*' is fine here because the caller owns the\n // data being sent. For security on the receiving side, the\n // PAFI Web page should check event.origin itself.\n popup.postMessage(data, \"*\");\n } catch {\n // No-op.\n }\n },\n };\n}\n\n/**\n * The web popup packaged as a {@link PafiWebModalAdapter} so callers\n * can register it explicitly (e.g. in a test harness).\n */\nexport const webPopupAdapter: PafiWebModalAdapter = {\n open(url, options) {\n return openWebPopup(url, options);\n },\n};\n","import { openWebPopup } from \"./webPopup\";\nimport type {\n ModalOpenOptions,\n PafiWebModalAdapter,\n PafiWebModalHandle,\n} from \"./types\";\n\nexport type {\n ModalOpenOptions,\n PafiWebModalAdapter,\n PafiWebModalHandle,\n} from \"./types\";\nexport { openWebPopup, webPopupAdapter } from \"./webPopup\";\n\n/**\n * Module-level adapter registry — allows platform consumers (React\n * Native, Electron, Tauri, etc.) to plug in their own handoff\n * implementation without forking the SDK.\n *\n * Callers set this once at app boot; `openPafiWebModal()` below uses\n * whatever is registered, or falls back to the web popup adapter\n * when `window.open` is available.\n */\nlet registeredAdapter: PafiWebModalAdapter | null = null;\n\n/**\n * Register the adapter used by `openPafiWebModal()`. Typically called\n * once during app initialization — mobile apps register a\n * SFSafariViewController / Chrome Custom Tabs adapter, desktop apps\n * can leave it unset (web popup is the default).\n *\n * Pass `null` to unregister and fall back to the default.\n */\nexport function setPafiWebModalAdapter(\n adapter: PafiWebModalAdapter | null,\n): void {\n registeredAdapter = adapter;\n}\n\n/**\n * Return the currently registered adapter, or `null` when none is set.\n * Useful for tests that want to snapshot-and-restore the adapter.\n */\nexport function getPafiWebModalAdapter(): PafiWebModalAdapter | null {\n return registeredAdapter;\n}\n\n/**\n * Open PAFI Web in the host platform's appropriate UX:\n *\n * - Browser (window.open): centered popup, 900×700 by default\n * - React Native (with adapter registered): SFSafariViewController\n * / Chrome Custom Tabs via `react-native-inappbrowser-reborn` or\n * `expo-web-browser`\n * - Desktop (with adapter registered): custom BrowserWindow / new tab\n *\n * Resolution order:\n * 1. If an adapter was registered via `setPafiWebModalAdapter()`, use it.\n * 2. Else if `window.open` is available, use the built-in web popup.\n * 3. Else throw with a clear error pointing at the adapter registry.\n *\n * @example\n * ```ts\n * // User clicks \"Trade on PAFI\" button\n * button.addEventListener('click', async () => {\n * const modal = await openPafiWebModal('https://app.pacificfinance.org', {\n * allowedOrigins: ['https://app.pacificfinance.org'],\n * onMessage: (data, origin) => {\n * if (typeof data === 'object' && data && 'txHash' in data) {\n * console.log('Swap confirmed:', data.txHash);\n * modal.close();\n * }\n * },\n * onClose: () => {\n * console.log('User closed modal');\n * },\n * });\n * });\n * ```\n */\nexport async function openPafiWebModal(\n url: string,\n options: ModalOpenOptions = {},\n): Promise<PafiWebModalHandle> {\n if (!url || typeof url !== \"string\") {\n throw new Error(\"openPafiWebModal: `url` is required\");\n }\n\n if (registeredAdapter) {\n return Promise.resolve(registeredAdapter.open(url, options));\n }\n\n if (typeof window !== \"undefined\" && typeof window.open === \"function\") {\n return openWebPopup(url, options);\n }\n\n throw new Error(\n \"openPafiWebModal: no adapter registered and `window.open` is unavailable. \" +\n \"Call `setPafiWebModalAdapter()` with a platform-specific adapter (e.g. SFSafariViewController on iOS) during app boot.\",\n );\n}\n"]}
1
+ {"version":3,"sources":["/Users/phitran/Pacific-Finance/pafi-backend/pafi-sdk/packages/core/dist/index.cjs","../src/index.ts","../src/userop/types.ts","../src/paymaster/config.ts","../src/utils/checkEthAndBranch.ts","../src/contracts/real/pointToken.ts","../src/contracts/real/batchExecutor.ts","../src/contracts/real/addresses.ts","../src/web-handoff/webPopup.ts","../src/web-handoff/index.ts"],"names":[],"mappings":"AAAA;AACE;AACF,wDAA6B;AAC7B;AACE;AACA;AACA;AACF,wDAA6B;AAC7B;AACE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACF,wDAA6B;AAC7B;AACE;AACA;AACA;AACF,wDAA6B;AAC7B;AACE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACF,wDAA6B;AAC7B;AACE;AACA;AACA;AACA;AACA;AACA;AACF,wDAA6B;AAC7B;AACE;AACF,wDAA6B;AAC7B;AACE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACF,wDAA6B;AAC7B;AACE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACF,wDAA6B;AAC7B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A;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA","file":"/Users/phitran/Pacific-Finance/pafi-backend/pafi-sdk/packages/core/dist/index.cjs","sourcesContent":[null,"import { createPublicClient, http } from \"viem\";\nimport type { Address, Hex, PublicClient, WalletClient } from \"viem\";\n\n// -------------------------------------------------------------------------\n// Re-export all sub-modules\n// -------------------------------------------------------------------------\nexport * from \"./types\";\nexport * from \"./constants\";\nexport * from \"./errors\";\nexport * from \"./abi/index\";\nexport * from \"./eip712/index\";\nexport * from \"./contract/index\";\nexport * from \"./quoting/index\";\nexport * from \"./swap/index\";\nexport * from \"./auth/index\";\n\n// v1.4 — Account Abstraction primitives (EIP-7702 + ERC-4337 v0.7)\nexport * from \"./userop/index\";\nexport * from \"./paymaster/index\";\nexport * from \"./utils/index\";\n\n// v1.4 — Contract ABIs + addresses. ABI matches deployed PointToken on\n// Base mainnet; only `batchExecutor` address + Base Sepolia row remain\n// placeholder. EIP-712 helpers live under `./eip712/` and are already\n// exported above — not re-exported here.\n// Consumers: `import { POINT_TOKEN_V2_ABI, CONTRACT_ADDRESSES, ... } from '@pafi-dev/core'`\nexport * from \"./contracts/index\";\n\n// v1.5 — PAFI Web handoff (mobile + desktop modal helper).\n// `openPafiWebModal()` + adapter registry for platform-specific UX.\nexport * from \"./web-handoff/index\";\n\n// -------------------------------------------------------------------------\n// Internal imports for PafiSDK class\n// -------------------------------------------------------------------------\nimport { buildMintRequestTypedData, signMintRequest, verifyMintRequest } from \"./eip712/mintRequest\";\nimport {\n buildReceiverConsentTypedData,\n signReceiverConsent,\n verifyReceiverConsent,\n} from \"./eip712/receiverConsent\";\nimport {\n getMintRequestNonce,\n getReceiverConsentNonce,\n getTokenName,\n} from \"./contract/pointToken\";\nimport { findBestQuote } from \"./quoting/quote\";\nimport {\n buildSwapFromQuote,\n buildUniversalRouterExecuteArgs,\n} from \"./swap/universalRouter\";\nimport { simulateSwap } from \"./swap/simulate\";\nimport type { SwapSimulationResult } from \"./swap/simulate\";\nimport { createLoginMessage } from \"./auth/loginMessage\";\nimport type { LoginMessageParams } from \"./auth/types\";\nimport { ConfigurationError } from \"./errors\";\nimport type {\n BestQuote,\n EIP712Signature,\n MintRequest,\n PafiSDKConfig,\n PointTokenDomainConfig,\n PoolKey,\n QuoteResult,\n ReceiverConsent,\n SignatureVerification,\n} from \"./types\";\n\n// -------------------------------------------------------------------------\n// PafiSDK — convenience class wrapping all contract + crypto primitives.\n//\n// This class is HTTP-client-free on purpose. It covers signing, verifying,\n// contract reads, and calldata encoding — the things that need a signer\n// or a provider but no HTTP layer. The issuer backend defines its own HTTP\n// contract via `@pafi/issuer`; frontends build `fetch()` calls against\n// those types directly.\n// -------------------------------------------------------------------------\n\nexport class PafiSDK {\n private _pointTokenAddress?: Address;\n private _signer?: WalletClient;\n private _provider?: PublicClient;\n private _chainId?: number;\n\n constructor(config: PafiSDKConfig) {\n this._pointTokenAddress = config.pointTokenAddress;\n this._signer = config.signer;\n this._chainId = config.chainId;\n\n if (config.provider) {\n this._provider = config.provider;\n } else if (config.rpcUrl) {\n this._provider = createPublicClient({\n transport: http(config.rpcUrl),\n });\n }\n }\n\n // -------------------------------------------------------------------------\n // Setters\n // -------------------------------------------------------------------------\n\n setPointTokenAddress(address: Address): void {\n this._pointTokenAddress = address;\n }\n\n setSigner(signer: WalletClient): void {\n this._signer = signer;\n }\n\n setProvider(provider: PublicClient): void {\n this._provider = provider;\n }\n\n // -------------------------------------------------------------------------\n // Private guards\n // -------------------------------------------------------------------------\n\n private requirePointToken(): Address {\n if (!this._pointTokenAddress) {\n throw new ConfigurationError(\"pointTokenAddress not set\");\n }\n return this._pointTokenAddress;\n }\n\n private requireProvider(): PublicClient {\n if (!this._provider) {\n throw new ConfigurationError(\"provider not set\");\n }\n return this._provider;\n }\n\n private requireSigner(): WalletClient {\n if (!this._signer) {\n throw new ConfigurationError(\"signer not set\");\n }\n return this._signer;\n }\n\n private requireChainId(): number {\n if (this._chainId === undefined) {\n throw new ConfigurationError(\"chainId not set\");\n }\n return this._chainId;\n }\n\n // -------------------------------------------------------------------------\n // Domain\n // -------------------------------------------------------------------------\n\n async getDomain(): Promise<PointTokenDomainConfig> {\n const provider = this.requireProvider();\n const pointToken = this.requirePointToken();\n const chainId = this.requireChainId();\n const name = await getTokenName(provider, pointToken);\n return { name, verifyingContract: pointToken, chainId };\n }\n\n // -------------------------------------------------------------------------\n // EIP-712 — delegates to pure functions\n // -------------------------------------------------------------------------\n\n async buildMintRequestTypedData(message: MintRequest) {\n const domain = await this.getDomain();\n return buildMintRequestTypedData(domain, message);\n }\n\n async buildReceiverConsentTypedData(message: ReceiverConsent) {\n const domain = await this.getDomain();\n return buildReceiverConsentTypedData(domain, message);\n }\n\n async signMintRequest(message: MintRequest): Promise<EIP712Signature> {\n const domain = await this.getDomain();\n return signMintRequest(this.requireSigner(), domain, message);\n }\n\n async verifyMintRequest(\n message: MintRequest,\n signature: Hex,\n expectedMinter: Address,\n ): Promise<SignatureVerification> {\n const domain = await this.getDomain();\n return verifyMintRequest(domain, message, signature, expectedMinter);\n }\n\n async signReceiverConsent(\n message: ReceiverConsent,\n ): Promise<EIP712Signature> {\n const domain = await this.getDomain();\n return signReceiverConsent(this.requireSigner(), domain, message);\n }\n\n async verifyReceiverConsent(\n message: ReceiverConsent,\n signature: Hex,\n expectedReceiver: Address,\n ): Promise<SignatureVerification> {\n const domain = await this.getDomain();\n return verifyReceiverConsent(domain, message, signature, expectedReceiver);\n }\n\n // -------------------------------------------------------------------------\n // Contract reads\n // -------------------------------------------------------------------------\n\n async getMintRequestNonce(receiver: Address): Promise<bigint> {\n return getMintRequestNonce(\n this.requireProvider(),\n this.requirePointToken(),\n receiver,\n );\n }\n\n async getReceiverConsentNonce(receiver: Address): Promise<bigint> {\n return getReceiverConsentNonce(\n this.requireProvider(),\n this.requirePointToken(),\n receiver,\n );\n }\n\n // -------------------------------------------------------------------------\n // Quoting — delegates to pure functions\n // -------------------------------------------------------------------------\n\n /**\n * Find the best swap route from `tokenIn` to `tokenOut`.\n * Merges `pools` with COMMON_POOLS for the configured chain, builds all\n * paths, and quotes via a single multicall RPC call.\n */\n async findBestQuote(\n tokenIn: Address,\n tokenOut: Address,\n exactAmount: bigint,\n pools: PoolKey[] = [],\n quoterAddress?: Address,\n maxHops?: number,\n ): Promise<BestQuote> {\n return findBestQuote(\n this.requireProvider(),\n this.requireChainId(),\n tokenIn,\n tokenOut,\n exactAmount,\n pools,\n quoterAddress,\n maxHops,\n );\n }\n\n // -------------------------------------------------------------------------\n // Swap building — delegates to pure functions\n // -------------------------------------------------------------------------\n\n /**\n * Build UniversalRouter execute args from a quote result.\n * The caller provides `minAmountOut` after applying their own slippage.\n */\n buildSwapFromQuote(params: {\n quote: QuoteResult;\n currencyIn: Address;\n currencyOut: Address;\n amountIn: bigint;\n minAmountOut: bigint;\n }): { commands: Hex; inputs: Hex[] } {\n return buildSwapFromQuote(params);\n }\n\n // -------------------------------------------------------------------------\n // Simulation — dry-run via eth_call (no gas spent)\n // -------------------------------------------------------------------------\n\n /**\n * Simulate a UniversalRouter.execute swap call. Catches reverts (bad\n * approvals, insufficient balance, pool errors) before submitting.\n *\n * @param routerAddress - UniversalRouter contract address\n * @param commands - Packed command bytes (from buildSwapFromQuote)\n * @param inputs - Encoded inputs (from buildSwapFromQuote)\n * @param deadline - Unix timestamp\n * @param from - Address that will execute the swap\n */\n async simulateSwap(\n routerAddress: Address,\n commands: Hex,\n inputs: Hex[],\n deadline: bigint,\n from: Address,\n ): Promise<SwapSimulationResult> {\n return simulateSwap(\n this.requireProvider(),\n routerAddress,\n commands,\n inputs,\n deadline,\n from,\n );\n }\n\n // -------------------------------------------------------------------------\n // Auth — EIP-4361 login helpers (offline, stateless)\n // -------------------------------------------------------------------------\n\n async createLoginMessage(\n params: Omit<LoginMessageParams, \"address\" | \"chainId\">,\n ): Promise<string> {\n const signer = this.requireSigner();\n const chainId = this.requireChainId();\n const account = signer.account;\n if (!account) {\n throw new ConfigurationError(\"signer has no account attached\");\n }\n return createLoginMessage({ ...params, address: account.address, chainId });\n }\n\n /** Sign a login message string with the current signer (personal_sign) */\n async signLoginMessage(message: string): Promise<Hex> {\n const signer = this.requireSigner();\n const account = signer.account;\n if (!account) {\n throw new ConfigurationError(\"signer has no account attached\");\n }\n return signer.signMessage({ account, message });\n }\n}\n\n// Expose the `buildUniversalRouterExecuteArgs` helper for consumers that\n// build swap calldata directly (e.g. v1.5 sponsored swap flow).\nexport { buildUniversalRouterExecuteArgs };\n","import type { Address, Hex } from \"viem\";\n\n/**\n * ERC-4337 v0.7 EntryPoint standard address (deployed deterministically\n * at the same address across chains).\n * https://eips.ethereum.org/EIPS/eip-4337\n */\nexport const ENTRY_POINT_V07: Address =\n \"0x0000000071727De22E5E9d8BAf0edAc6f37da032\";\n\n/**\n * A single call inside a batch. `BatchExecutor.execute(Call[])` iterates\n * and invokes each one. When the batch runs via EIP-7702 delegation,\n * `msg.sender` for each call is the user's EOA.\n */\nexport interface Operation {\n target: Address;\n value: bigint;\n data: Hex;\n}\n\n/**\n * Paymaster fields attached to a UserOperation. Populated by the\n * Coinbase Paymaster (via PAFI Backend proxy) before the user signs.\n */\nexport interface PaymasterFields {\n paymaster: Address;\n paymasterData: Hex;\n paymasterVerificationGasLimit: bigint;\n paymasterPostOpGasLimit: bigint;\n}\n\n/**\n * Partial UserOp used during preparation — before paymaster fields are\n * attached or the user signs.\n */\nexport interface PartialUserOperation {\n sender: Address;\n nonce: bigint;\n callData: Hex;\n callGasLimit: bigint;\n verificationGasLimit: bigint;\n preVerificationGas: bigint;\n maxFeePerGas: bigint;\n maxPriorityFeePerGas: bigint;\n}\n\n/**\n * Full ERC-4337 v0.7 UserOperation, ready for bundler submission.\n */\nexport interface UserOperation extends PartialUserOperation {\n paymaster: Address;\n paymasterData: Hex;\n paymasterVerificationGasLimit: bigint;\n paymasterPostOpGasLimit: bigint;\n signature: Hex;\n}\n\n/**\n * Receipt returned by a bundler after a UserOp lands on-chain.\n */\nexport interface UserOpReceipt {\n userOpHash: Hex;\n success: boolean;\n txHash: Hex;\n blockNumber: bigint;\n gasUsed: bigint;\n /** Effective gas cost paid (wei). */\n actualGasCost: bigint;\n}\n\n/**\n * Sentinel operation value used in tests + docs when `Operation.value`\n * is irrelevant (ERC-20 transfers, for example).\n */\nexport const ZERO_VALUE = 0n;\n","import type { PaymasterConfig } from \"./types\";\n\n/**\n * Module-level paymaster config. Read by batch builders (via\n * `getPaymasterConfig()`) and by `@pafi/issuer` `RelayService` when\n * building UserOps.\n *\n * Consumers call `setPaymasterConfig()` once at application boot. All\n * subsequent helpers that need the feeRecipient / issuer identity /\n * backend URL pull from here.\n *\n * This is global state by design — making every batch builder take a\n * config param would clutter every call site. The alternative (a\n * context/service) has more ceremony than this flow justifies.\n */\nlet _config: PaymasterConfig | null = null;\n\n/**\n * Set the application-wide paymaster config. Safe to call multiple\n * times (later calls override earlier). Throws if required fields\n * are missing.\n */\nexport function setPaymasterConfig(config: PaymasterConfig): void {\n if (!config.pafiBackendUrl) {\n throw new Error(\"setPaymasterConfig: pafiBackendUrl is required\");\n }\n if (!config.issuerId) {\n throw new Error(\"setPaymasterConfig: issuerId is required\");\n }\n if (!config.apiKey) {\n throw new Error(\"setPaymasterConfig: apiKey is required\");\n }\n if (!config.feeRecipient) {\n throw new Error(\"setPaymasterConfig: feeRecipient is required\");\n }\n _config = { ...config };\n}\n\n/**\n * Get the current paymaster config. Throws if `setPaymasterConfig()`\n * has not been called yet — this surfaces boot-order bugs early\n * instead of failing with \"paymaster.feeRecipient is undefined\" at\n * the point of use.\n */\nexport function getPaymasterConfig(): PaymasterConfig {\n if (!_config) {\n throw new Error(\n \"PaymasterConfig not initialized — call setPaymasterConfig() at application boot before invoking any batch builder\",\n );\n }\n return _config;\n}\n\n/** Test helper — clear the singleton. */\nexport function _resetPaymasterConfigForTests(): void {\n _config = null;\n}\n\n/** Check whether paymaster config has been initialized. */\nexport function isPaymasterConfigured(): boolean {\n return _config !== null;\n}\n","import type { Address, PublicClient } from \"viem\";\n\n/**\n * Submission path chosen by `checkEthAndBranch`.\n * - `normal`: initiator has enough ETH; submit via `walletClient.writeContract`\n * or a plain `eth_sendRawTransaction`. No paymaster round-trip.\n * - `paymaster`: initiator doesn't have enough ETH; wrap the batch as a\n * UserOperation and route through PAFI Backend → Coinbase Paymaster\n * → Bundler.\n */\nexport type SubmissionPath = \"normal\" | \"paymaster\";\n\nexport interface CheckEthAndBranchParams {\n /** viem PublicClient bound to the target chain. */\n client: PublicClient;\n /** The address whose ETH balance we check. */\n initiator: Address;\n /** Estimated gas cost in wei for the upcoming tx. */\n estimatedGasWei: bigint;\n /**\n * Optional safety margin multiplier (basis points). Defaults to\n * 11_000 (110%) — the initiator needs 10% above the estimate to\n * qualify for the normal path. Prevents edge cases where gas price\n * spikes between estimation and submission cause a \"has enough\"\n * decision to fail at broadcast time.\n */\n marginBps?: number;\n}\n\nconst DEFAULT_MARGIN_BPS = 11_000;\n\n/**\n * Step 3 of the Generalized Flow ([SPONSORED_PATH_FLOW.md §2]):\n * choose between the normal path (initiator pays ETH directly) and the\n * paymaster path (bundler + Coinbase Paymaster).\n *\n * Intentionally synchronous in spirit — the only network call is\n * `getBalance`. Callers can parallelize it with other reads.\n */\nexport async function checkEthAndBranch(\n params: CheckEthAndBranchParams,\n): Promise<SubmissionPath> {\n const marginBps = params.marginBps ?? DEFAULT_MARGIN_BPS;\n const required =\n (params.estimatedGasWei * BigInt(marginBps)) / 10_000n;\n\n const balance = await params.client.getBalance({\n address: params.initiator,\n });\n\n return balance >= required ? \"normal\" : \"paymaster\";\n}\n","import { parseAbi } from \"viem\";\n\n/**\n * Real `PointToken` ABI — matches the contract deployed on Base mainnet\n * (POINT at `0x7d25E7156E51F865D522fd3ef257a6B5DD41b97e`). Sourced from\n * the Solidity contract shipped by the SC team 2026-04-21.\n *\n * ## Mint — two paths\n *\n * Path 1 — Direct (whitelisted minter):\n * mint(address to, uint256 amount)\n * - msg.sender must be in minters[]\n * - Used by off-chain services that hold a minter key\n *\n * Path 2 — Sig-gated (gasless, v1.4 sponsored flow):\n * mint(address to, uint256 amount, uint256 deadline, bytes minterSig)\n * - msg.sender MUST equal `to` (the receiver)\n * - minterSig is an EIP-712 MintRequest signature from a whitelisted minter\n * - Consumes `mintRequestNonces[to]`\n * - This is the path v1.4 uses: issuer backend signs, user submits\n * via EIP-7702 + Coinbase Paymaster\n *\n * ## Burn — mirror structure\n *\n * Path 1: burn(address from, uint256 amount) — whitelisted burner\n * Path 2: burn(address from, uint256 amount, uint256 deadline, bytes burnerSig)\n * — msg.sender must equal `from`, burnerSig from whitelisted burner,\n * consumes `burnRequestNonces[from]`\n *\n * Either burn path emits `Transfer(from → 0x0)` so BurnIndexer semantics\n * don't depend on which path was taken.\n *\n * ## EIP-712 type hashes (from contract source)\n *\n * MintRequest(address to,uint256 amount,uint256 nonce,uint256 deadline)\n * BurnRequest(address from,uint256 amount,uint256 nonce,uint256 deadline)\n *\n * Domain: EIP-712 standard — name = ERC-20 token name, version = \"1\",\n * chainId, verifyingContract = this PointToken address.\n */\nexport const POINT_TOKEN_ABI = parseAbi([\n // --- Mint paths ---\n \"function mint(address to, uint256 amount) external\",\n \"function mint(address to, uint256 amount, uint256 deadline, bytes minterSig) external\",\n\n // --- Burn paths ---\n \"function burn(address from, uint256 amount) external\",\n \"function burn(address from, uint256 amount, uint256 deadline, bytes burnerSig) external\",\n\n // --- Authorization reads ---\n \"function minters(address account) external view returns (bool)\",\n \"function burners(address account) external view returns (bool)\",\n\n // --- Authorization writes (owner-only; used by provisioning scripts) ---\n \"function addMinter(address minter) external\",\n \"function removeMinter(address minter) external\",\n \"function addBurner(address burner) external\",\n \"function removeBurner(address burner) external\",\n\n // --- Nonces (sig-gated paths) ---\n \"function mintRequestNonces(address receiver) external view returns (uint256)\",\n \"function burnRequestNonces(address from) external view returns (uint256)\",\n\n // --- Oracle ---\n \"function mintingOracle() external view returns (address)\",\n \"function setMintingOracle(address _mintingOracle) external\",\n\n // --- Issuer ---\n \"function issuer() external view returns (address)\",\n\n // --- Standard ERC-20 reads ---\n \"function balanceOf(address account) external view returns (uint256)\",\n \"function totalSupply() external view returns (uint256)\",\n \"function name() external view returns (string)\",\n \"function symbol() external view returns (string)\",\n \"function decimals() external view returns (uint8)\",\n\n // --- EIP-712 domain (for off-chain sig verification) ---\n \"function DOMAIN_SEPARATOR() external view returns (bytes32)\",\n \"function eip712Domain() external view returns (bytes1 fields, string name, string version, uint256 chainId, address verifyingContract, bytes32 salt, uint256[] extensions)\",\n\n // --- Events ---\n // PointIndexer filters Transfer(from=0x0) for mints\n // BurnIndexer filters Transfer(to=0x0) for burns\n \"event Transfer(address indexed from, address indexed to, uint256 value)\",\n \"event MinterAdded(address indexed minter)\",\n \"event MinterRemoved(address indexed minter)\",\n \"event BurnerAdded(address indexed burner)\",\n \"event BurnerRemoved(address indexed burner)\",\n \"event MintingOracleUpdated(address indexed mintingOracle)\",\n] as const);\n","import type { Address } from \"viem\";\n\n/**\n * BatchExecutor delegation target addresses.\n *\n * ## Status\n *\n * Per-chain addresses are **still placeholder** (`0x...DE01` / `DE02`)\n * pending the SC team's Phase B delivery. When Coinbase publishes a\n * canonical BatchExecutor, or PAFI deploys its own and publishes the\n * address, swap the constants below — callers already import from here\n * so no wiring changes.\n *\n * The ABI (`execute(Call[])`) itself is real and stable — it lives\n * under `../../userop/batchExecute.ts` and is re-exported below so\n * consumers can grab both ABI + address from one import path.\n *\n * ## Why checksum with DEAD0001 / DEAD0002 suffix\n *\n * The placeholder pattern makes the fact-of-mockness obvious in logs\n * and block explorers. A request targeting `0x...DE01` is impossible\n * to confuse with a production contract.\n */\n\n// Base Sepolia (testnet) — placeholder\nexport const BATCH_EXECUTOR_ADDRESS_BASE_SEPOLIA =\n \"0x000000000000000000000000000000000000DE01\" as Address;\n\n// Base mainnet — placeholder (pending SC delivery)\nexport const BATCH_EXECUTOR_ADDRESS_BASE_MAINNET =\n \"0x000000000000000000000000000000000000DE02\" as Address;\n\n// The ABI itself is fully real — re-exported from userop/ for\n// convenience so consumers don't need two imports.\nexport { BATCH_EXECUTOR_ABI } from \"../../userop/batchExecute\";\n","import type { Address } from \"viem\";\n\n/**\n * Per-chain deployed contract addresses — v1.4 flow.\n *\n * ## Status (2026-04-21)\n *\n * Base mainnet (8453): all SC-delivered and real, EXCEPT `batchExecutor`\n * which is still a `0x...DE02` placeholder pending the Phase B delivery.\n * Base Sepolia (84532): entire row is placeholder — not in active use.\n *\n * ## What lives where\n *\n * pointToken — live POINT instance (clone of PointToken impl)\n * batchExecutor — EIP-7702 delegation target (PLACEHOLDER)\n * usdt — MockERC20 used by Uniswap pools\n * issuerRegistry — registry of all issuers on this chain\n * mintingOracle — per-issuer mint cap enforcer\n *\n * PointTokenFactory + PointToken implementation addresses live in\n * separate exports below — they're only needed at provisioning /\n * observability time, not in the hot mint/burn path, so excluded from\n * the per-chain bundle.\n *\n * ## Swap workflow when BatchExecutor lands\n *\n * 1. Replace `batchExecutor` placeholder with real address\n * 2. Structure / imports don't change — callers are stable\n * 3. Bump core to next beta and update release notes\n */\nexport interface ContractAddresses {\n pointToken: Address;\n batchExecutor: Address;\n usdt: Address;\n issuerRegistry: Address;\n mintingOracle: Address;\n}\n\nconst PLACEHOLDER_DEAD = (suffix: string): Address =>\n `0x000000000000000000000000000000000000${suffix.toLowerCase().padStart(4, \"0\")}` as Address;\n\nexport const CONTRACT_ADDRESSES: Record<number, ContractAddresses> = {\n // Base mainnet — SC-delivered 2026-04-21\n // registry: IssuerRegistry 0xda2D3338CF70F462Ac175F5f2edfa45660CA4f31\n // factory: PointTokenFactory 0x36c0BAb2faBE45EfA6d13001143e43A266Af673B\n // oracle: MintingOracle 0xD85165939C700E51c8a45099316C6482634C2Ab9\n // tokenImpl: PointToken (impl) 0x2e6FB1B0C1A51abb83eC974890126a64eC02E995\n // mockUsdt: MockERC20 0x5d313485Ba59C3bb91e1A9C0C11782F0b83d5dcd\n // POINT: PointToken instance 0x7d25E7156E51F865D522fd3ef257a6B5DD41b97e\n 8453: {\n pointToken: \"0x7d25E7156E51F865D522fd3ef257a6B5DD41b97e\",\n batchExecutor: PLACEHOLDER_DEAD(\"de02\"), // ⏳ pending SC delivery\n usdt: \"0x5d313485Ba59C3bb91e1A9C0C11782F0b83d5dcd\",\n issuerRegistry: \"0xda2D3338CF70F462Ac175F5f2edfa45660CA4f31\",\n mintingOracle: \"0xD85165939C700E51c8a45099316C6482634C2Ab9\",\n },\n // Base Sepolia — not in active use; placeholders kept so the map\n // compiles for tooling that enumerates chains.\n 84532: {\n pointToken: PLACEHOLDER_DEAD(\"dead\"),\n batchExecutor: PLACEHOLDER_DEAD(\"de01\"),\n usdt: PLACEHOLDER_DEAD(\"dead\"),\n issuerRegistry: PLACEHOLDER_DEAD(\"dead\"),\n mintingOracle: PLACEHOLDER_DEAD(\"dead\"),\n },\n};\n\n/**\n * PointTokenFactory address — separate from `ContractAddresses` because\n * it's only used at provisioning time (issuer onboard + token creation),\n * not in the hot mint/burn path.\n */\nexport const POINT_TOKEN_FACTORY_ADDRESSES: Record<number, Address> = {\n 8453: \"0x36c0BAb2faBE45EfA6d13001143e43A266Af673B\",\n 84532: PLACEHOLDER_DEAD(\"dead\"),\n};\n\n/**\n * PointToken implementation address — the EIP-1167 clone target used\n * by PointTokenFactory. Exposed for observability / proxy verification;\n * consumers should never call this directly.\n */\nexport const POINT_TOKEN_IMPL_ADDRESSES: Record<number, Address> = {\n 8453: \"0x2e6FB1B0C1A51abb83eC974890126a64eC02E995\",\n 84532: PLACEHOLDER_DEAD(\"dead\"),\n};\n\n/**\n * Lookup helper — throws if the chain isn't in the map so callers fail\n * loudly on misconfiguration instead of silently using `undefined`.\n */\nexport function getContractAddresses(chainId: number): ContractAddresses {\n const addrs = CONTRACT_ADDRESSES[chainId];\n if (!addrs) {\n throw new Error(\n `getContractAddresses: no addresses for chainId ${chainId}. ` +\n `Supported: ${Object.keys(CONTRACT_ADDRESSES).join(\", \")}`,\n );\n }\n return addrs;\n}\n","import type {\n ModalOpenOptions,\n PafiWebModalAdapter,\n PafiWebModalHandle,\n} from \"./types\";\n\nconst DEFAULT_WIDTH = 900;\nconst DEFAULT_HEIGHT = 700;\nconst DEFAULT_NAME = \"pafi-web\";\n\n/**\n * Web browser popup adapter. Opens the given URL in a centered\n * `window.open()` popup, polls for close, and optionally forwards\n * `postMessage` events back to the caller.\n *\n * Runtime requirement: `window.open` must exist. Throws if called\n * under Node / SSR / React Native — use `setPafiWebModalAdapter()` to\n * provide a platform-specific adapter in those environments.\n *\n * ## Popup blocking\n *\n * Browsers block `window.open()` unless it happens inside a user\n * gesture (click handler). Callers MUST wire this into a direct click\n * handler — wrapping it in a `setTimeout` or async await before the\n * open call will trigger the blocker.\n */\nexport function openWebPopup(\n url: string,\n options: ModalOpenOptions = {},\n): PafiWebModalHandle {\n if (typeof window === \"undefined\" || typeof window.open !== \"function\") {\n throw new Error(\n \"openWebPopup: `window.open` is not available in this runtime. \" +\n \"Register a platform adapter via setPafiWebModalAdapter() instead.\",\n );\n }\n\n const width = options.width ?? DEFAULT_WIDTH;\n const height = options.height ?? DEFAULT_HEIGHT;\n const name = options.windowName ?? DEFAULT_NAME;\n\n // Center on the screen — works in all major browsers. Falls back\n // gracefully if `screen.availWidth`/`screenX` are unavailable.\n const screenW = window.screen?.availWidth ?? window.innerWidth;\n const screenH = window.screen?.availHeight ?? window.innerHeight;\n const left = Math.max(0, Math.floor((screenW - width) / 2));\n const top = Math.max(0, Math.floor((screenH - height) / 2));\n\n const features = [\n `width=${width}`,\n `height=${height}`,\n `left=${left}`,\n `top=${top}`,\n \"resizable=yes\",\n \"scrollbars=yes\",\n \"noopener=no\", // we need opener.postMessage to work\n ].join(\",\");\n\n const popup = window.open(url, name, features);\n if (!popup) {\n throw new Error(\n \"openWebPopup: popup was blocked. Ensure this call runs inside a user gesture (click handler).\",\n );\n }\n\n // Set up state + listeners --------------------------------------------\n\n let closed = false;\n let pollId: ReturnType<typeof setInterval> | null = null;\n let messageListener: ((e: MessageEvent) => void) | null = null;\n\n const dispose = (): void => {\n if (closed) return;\n closed = true;\n if (pollId !== null) {\n clearInterval(pollId);\n pollId = null;\n }\n if (messageListener) {\n window.removeEventListener(\"message\", messageListener);\n messageListener = null;\n }\n options.onClose?.();\n };\n\n // Poll every 500ms for popup close — there's no `close` event.\n // Stops when `popup.closed` flips to true OR our handle is closed.\n pollId = setInterval(() => {\n if (popup.closed) {\n dispose();\n }\n }, 500);\n\n // Wire postMessage filtering by origin — secure-by-default. An\n // empty or missing `allowedOrigins` rejects ALL messages; the\n // caller must explicitly whitelist PAFI Web's host(s) before any\n // payload is delivered. This prevents a compromised popup (via\n // opener leak or redirect) from impersonating PAFI Web.\n if (options.onMessage) {\n const allowed = options.allowedOrigins ?? [];\n const onMessage = options.onMessage;\n messageListener = (event: MessageEvent): void => {\n if (event.source !== popup) return;\n if (!allowed.includes(event.origin)) return;\n onMessage(event.data, event.origin);\n };\n window.addEventListener(\"message\", messageListener);\n }\n\n // Handle object -------------------------------------------------------\n\n return {\n get isOpen(): boolean {\n return !closed && !popup.closed;\n },\n close(): void {\n if (closed) return;\n try {\n popup.close();\n } catch {\n // Some browsers block close() unless the popup was opened by\n // the same document. Dispose our listeners anyway.\n }\n dispose();\n },\n focus(): void {\n if (closed || popup.closed) return;\n try {\n popup.focus();\n } catch {\n // No-op on failure — focus is best-effort.\n }\n },\n postMessage(data: unknown): void {\n if (closed || popup.closed) return;\n try {\n // targetOrigin '*' is fine here because the caller owns the\n // data being sent. For security on the receiving side, the\n // PAFI Web page should check event.origin itself.\n popup.postMessage(data, \"*\");\n } catch {\n // No-op.\n }\n },\n };\n}\n\n/**\n * The web popup packaged as a {@link PafiWebModalAdapter} so callers\n * can register it explicitly (e.g. in a test harness).\n */\nexport const webPopupAdapter: PafiWebModalAdapter = {\n open(url, options) {\n return openWebPopup(url, options);\n },\n};\n","import { openWebPopup } from \"./webPopup\";\nimport type {\n ModalOpenOptions,\n PafiWebModalAdapter,\n PafiWebModalHandle,\n} from \"./types\";\n\nexport type {\n ModalOpenOptions,\n PafiWebModalAdapter,\n PafiWebModalHandle,\n} from \"./types\";\nexport { openWebPopup, webPopupAdapter } from \"./webPopup\";\n\n/**\n * Module-level adapter registry — allows platform consumers (React\n * Native, Electron, Tauri, etc.) to plug in their own handoff\n * implementation without forking the SDK.\n *\n * Callers set this once at app boot; `openPafiWebModal()` below uses\n * whatever is registered, or falls back to the web popup adapter\n * when `window.open` is available.\n */\nlet registeredAdapter: PafiWebModalAdapter | null = null;\n\n/**\n * Register the adapter used by `openPafiWebModal()`. Typically called\n * once during app initialization — mobile apps register a\n * SFSafariViewController / Chrome Custom Tabs adapter, desktop apps\n * can leave it unset (web popup is the default).\n *\n * Pass `null` to unregister and fall back to the default.\n */\nexport function setPafiWebModalAdapter(\n adapter: PafiWebModalAdapter | null,\n): void {\n registeredAdapter = adapter;\n}\n\n/**\n * Return the currently registered adapter, or `null` when none is set.\n * Useful for tests that want to snapshot-and-restore the adapter.\n */\nexport function getPafiWebModalAdapter(): PafiWebModalAdapter | null {\n return registeredAdapter;\n}\n\n/**\n * Open PAFI Web in the host platform's appropriate UX:\n *\n * - Browser (window.open): centered popup, 900×700 by default\n * - React Native (with adapter registered): SFSafariViewController\n * / Chrome Custom Tabs via `react-native-inappbrowser-reborn` or\n * `expo-web-browser`\n * - Desktop (with adapter registered): custom BrowserWindow / new tab\n *\n * Resolution order:\n * 1. If an adapter was registered via `setPafiWebModalAdapter()`, use it.\n * 2. Else if `window.open` is available, use the built-in web popup.\n * 3. Else throw with a clear error pointing at the adapter registry.\n *\n * @example\n * ```ts\n * // User clicks \"Trade on PAFI\" button\n * button.addEventListener('click', async () => {\n * const modal = await openPafiWebModal('https://app.pacificfinance.org', {\n * allowedOrigins: ['https://app.pacificfinance.org'],\n * onMessage: (data, origin) => {\n * if (typeof data === 'object' && data && 'txHash' in data) {\n * console.log('Swap confirmed:', data.txHash);\n * modal.close();\n * }\n * },\n * onClose: () => {\n * console.log('User closed modal');\n * },\n * });\n * });\n * ```\n */\nexport async function openPafiWebModal(\n url: string,\n options: ModalOpenOptions = {},\n): Promise<PafiWebModalHandle> {\n if (!url || typeof url !== \"string\") {\n throw new Error(\"openPafiWebModal: `url` is required\");\n }\n\n if (registeredAdapter) {\n return Promise.resolve(registeredAdapter.open(url, options));\n }\n\n if (typeof window !== \"undefined\" && typeof window.open === \"function\") {\n return openWebPopup(url, options);\n }\n\n throw new Error(\n \"openPafiWebModal: no adapter registered and `window.open` is unavailable. \" +\n \"Call `setPafiWebModalAdapter()` with a platform-specific adapter (e.g. SFSafariViewController on iOS) during app boot.\",\n );\n}\n"]}