"use client";
import {
  logger
} from "./chunk-UUHGOBKZ.js";

// src/clients/polymarket.tsx
import {
  POLYMARKET_API_KEY,
  initializeCheckoutTokenTransferAddress
} from "@funkit/api-base";
import {
  encodeFunctionData,
  erc20Abi,
  getAddress as getAddress2
} from "viem";
import { polygon } from "viem/chains";

// src/consts/polymarket.ts
import { getAddress } from "viem";
var POLYMARKET_PUSD_ADDRESS = getAddress(
  "0xC011a7E12a19f7B1f670d46F03B03f3342E82DFB"
);

// src/domains/paymentMethods.ts
import { PaymentMethod } from "@funkit/connect-core";
import { exhaustiveCheck, formatAddress } from "@funkit/utils";

// src/consts/bluvo.tsx
import {
  ETHEREAL_API_KEY,
  FormOfPaymentType
} from "@funkit/api-base";
import React7 from "react";

// src/components/Icons/BinanceIcon.tsx
import React from "react";
var BinanceIcon = ({ size = 24 }) => {
  return /* @__PURE__ */ React.createElement(
    "svg",
    {
      width: size,
      height: size,
      viewBox: "0 0 20 20",
      fill: "none",
      xmlns: "http://www.w3.org/2000/svg"
    },
    /* @__PURE__ */ React.createElement("rect", { width: "20", height: "20", rx: "4", fill: "#F3BA2F" }),
    /* @__PURE__ */ React.createElement(
      "path",
      {
        d: "M7.67 9.04 10 6.71l2.33 2.34 1.36-1.36L10 4 6.31 7.69zM4 10l1.36-1.36L6.7 10l-1.35 1.36zm3.67.96L10 13.29l2.33-2.33 1.36 1.35-3.69 3.7-3.69-3.7zm5.62-.96 1.35-1.35L16 10l-1.36 1.36z",
        fill: "#fff"
      }
    ),
    /* @__PURE__ */ React.createElement(
      "path",
      {
        d: "M11.38 10 10 8.62 8.98 9.64l-.11.12-.25.24L10 11.38z",
        fill: "#fff"
      }
    )
  );
};

// src/components/Icons/BybitIcon.tsx
import React2 from "react";
var BybitIcon = ({ size = 24 }) => {
  return /* @__PURE__ */ React2.createElement(
    "svg",
    {
      width: size,
      height: size,
      viewBox: "0 0 20 20",
      fill: "none",
      xmlns: "http://www.w3.org/2000/svg"
    },
    /* @__PURE__ */ React2.createElement("rect", { width: "20", height: "20", rx: "4", fill: "#0B0E11" }),
    /* @__PURE__ */ React2.createElement("g", { transform: "translate(2 6.78) scale(0.184)" }, /* @__PURE__ */ React2.createElement("path", { d: "M62.0083 25.3572V3H66.5022V25.3572H62.0083Z", fill: "#F7A600" }), /* @__PURE__ */ React2.createElement(
      "path",
      {
        d: "M9.63407 31.9983H0V9.64111H9.24666C13.7406 9.64111 16.3591 12.0903 16.3591 15.9214C16.3591 18.4013 14.6774 20.0039 13.5134 20.5375C14.9028 21.1652 16.6813 22.5779 16.6813 25.5624C16.6813 29.7373 13.7406 31.9983 9.63407 31.9983ZM8.89096 13.5355H4.4939V18.6852H8.89096C10.7981 18.6852 11.8652 17.6488 11.8652 16.1095C11.8652 14.5719 10.7981 13.5355 8.89096 13.5355ZM9.18151 22.6104H4.4939V28.1056H9.18151C11.2189 28.1056 12.1874 26.8503 12.1874 25.3418C12.1874 23.835 11.2171 22.6104 9.18151 22.6104Z",
        fill: "white"
      }
    ), /* @__PURE__ */ React2.createElement(
      "path",
      {
        d: "M30.3882 22.8293V31.9983H25.926V22.8293L19.0073 9.64111H23.8886L28.1888 18.6527L32.4239 9.64111H37.3052L30.3882 22.8293Z",
        fill: "white"
      }
    ), /* @__PURE__ */ React2.createElement(
      "path",
      {
        d: "M50.0457 31.9983H40.4116V9.64111H49.6583C54.1522 9.64111 56.7707 12.0903 56.7707 15.9214C56.7707 18.4013 55.089 20.0039 53.925 20.5375C55.3144 21.1652 57.093 22.5779 57.093 25.5624C57.093 29.7373 54.1522 31.9983 50.0457 31.9983ZM49.3026 13.5355H44.9055V18.6852H49.3026C51.2097 18.6852 52.2768 17.6488 52.2768 16.1095C52.2768 14.5719 51.2097 13.5355 49.3026 13.5355ZM49.5931 22.6104H44.9055V28.1056H49.5931C51.6305 28.1056 52.599 26.8503 52.599 25.3418C52.599 23.835 51.6305 22.6104 49.5931 22.6104Z",
        fill: "white"
      }
    ), /* @__PURE__ */ React2.createElement(
      "path",
      {
        d: "M80.986 13.5355V32H76.4921V13.5355H70.4785V9.64111H86.9996V13.5355H80.986Z",
        fill: "white"
      }
    ))
  );
};

// src/components/Icons/CoinbaseIcon.tsx
import React3 from "react";
var CoinbaseIcon = ({ size = 24 }) => {
  return /* @__PURE__ */ React3.createElement(
    "svg",
    {
      xmlns: "http://www.w3.org/2000/svg",
      width: size,
      height: size,
      viewBox: "0 0 20 20",
      fill: "none"
    },
    /* @__PURE__ */ React3.createElement("rect", { width: "20", height: "20", rx: "4", fill: "#2C5FF6" }),
    /* @__PURE__ */ React3.createElement(
      "path",
      {
        d: "M9.99 13.5c-1.93 0-3.5-1.57-3.5-3.5s1.57-3.5 3.5-3.5c1.76 0 3.22 1.305 3.46 3h3.52A7.005 7.005 0 0 0 9.99 3c-3.86 0-7 3.14-7 7s3.14 7 7 7c3.69 0 6.725-2.87 6.98-6.5h-3.52c-.24 1.695-1.7 3-3.46 3Z",
        fill: "#fff"
      }
    )
  );
};

// src/components/Icons/GateIoIcon.tsx
import React4 from "react";
var GateIoIcon = ({ size = 24 }) => {
  return /* @__PURE__ */ React4.createElement(
    "svg",
    {
      width: size,
      height: size,
      viewBox: "0 0 25 25",
      fill: "none",
      xmlns: "http://www.w3.org/2000/svg"
    },
    /* @__PURE__ */ React4.createElement("rect", { width: "25", height: "25", rx: "5.357", fill: "#fff" }),
    /* @__PURE__ */ React4.createElement("g", { clipPath: "url(#a)" }, /* @__PURE__ */ React4.createElement(
      "mask",
      {
        id: "b",
        maskUnits: "userSpaceOnUse",
        x: "5",
        y: "5",
        width: "15",
        height: "15",
        style: { maskType: "luminance" }
      },
      /* @__PURE__ */ React4.createElement("path", { d: "M5 5h15v15H5V5Z", fill: "#fff" })
    ), /* @__PURE__ */ React4.createElement("g", { mask: "url(#b)" }, /* @__PURE__ */ React4.createElement(
      "path",
      {
        fillRule: "evenodd",
        clipRule: "evenodd",
        d: "M12.5 16.625a4.125 4.125 0 0 1 0-8.25V5a7.5 7.5 0 1 0 7.5 7.5h-3.375a4.125 4.125 0 0 1-4.125 4.125Z",
        fill: "#2354E6"
      }
    )), /* @__PURE__ */ React4.createElement(
      "path",
      {
        fillRule: "evenodd",
        clipRule: "evenodd",
        d: "M12.5 12.5h4.125V8.375H12.5V12.5Z",
        fill: "#17E6A1"
      }
    )),
    /* @__PURE__ */ React4.createElement("defs", null, /* @__PURE__ */ React4.createElement("clipPath", { id: "a" }, /* @__PURE__ */ React4.createElement("path", { fill: "#fff", transform: "translate(5 5)", d: "M0 0h15v15H0z" })))
  );
};

// src/components/Icons/GeminiIcon.tsx
import React5 from "react";
var GeminiIcon = ({ size = 24 }) => {
  return /* @__PURE__ */ React5.createElement(
    "svg",
    {
      width: size,
      height: size,
      viewBox: "0 0 20 20",
      fill: "none",
      xmlns: "http://www.w3.org/2000/svg"
    },
    /* @__PURE__ */ React5.createElement(
      "path",
      {
        d: "M16 0H4a4 4 0 0 0-4 4v12a4 4 0 0 0 4 4h12a4 4 0 0 0 4-4V4a4 4 0 0 0-4-4",
        fill: "#58C8E6"
      }
    ),
    /* @__PURE__ */ React5.createElement(
      "path",
      {
        d: "M15.025 7.686H8.661a3.21 3.21 0 0 1 3.182-2.746 3.21 3.21 0 0 1 3.182 2.746m-3.653.94v2.746H8.626V8.626zm-.035 3.686a3.21 3.21 0 0 1-3.182 2.746 3.21 3.21 0 0 1-3.183-2.746zm-6.365-.94A3.23 3.23 0 0 1 7.686 8.66v2.71zm10.053-2.746a3.23 3.23 0 0 1-2.711 2.71v-2.71zM11.843 4C9.734 4 7.937 5.624 7.712 7.712A4.18 4.18 0 0 0 4 11.843 4.16 4.16 0 0 0 8.157 16c2.109 0 3.909-1.624 4.131-3.712C14.376 12.063 16 10.266 16 8.157A4.16 4.16 0 0 0 11.843 4",
        fill: "#fff"
      }
    )
  );
};

// src/components/Icons/KrakenIcon.tsx
import React6 from "react";
var KrakenIcon = ({ size = 24 }) => {
  return /* @__PURE__ */ React6.createElement(
    "svg",
    {
      width: size,
      height: size,
      viewBox: "0 0 20 20",
      fill: "none",
      xmlns: "http://www.w3.org/2000/svg"
    },
    /* @__PURE__ */ React6.createElement(
      "path",
      {
        d: "M16 0H4a4 4 0 0 0-4 4v12a4 4 0 0 0 4 4h12a4 4 0 0 0 4-4V4a4 4 0 0 0-4-4",
        fill: "#5741D9"
      }
    ),
    /* @__PURE__ */ React6.createElement(
      "path",
      {
        d: "M4 11.78v-.67a6.4 6.4 0 0 1 .83-3.26 6 6 0 0 1 2.64-2.3A6 6 0 0 1 9.89 5q1.84-.02 3.4.96a5.6 5.6 0 0 1 2.64 4.18q.1.9.07 1.82l-.01.98q0 .22-.05.43c-.15.54-.8.8-1.27.49a.8.8 0 0 1-.35-.57l-.04-.48v-1.98q0-.4-.26-.68a.83.83 0 0 0-1.17-.04 1 1 0 0 0-.32.65v.28l-.01 2.19c0 .41-.33.73-.76.76a1 1 0 0 1-.56-.17.8.8 0 0 1-.3-.48l-.03-.33v-2.2a1 1 0 0 0-.26-.65.84.84 0 0 0-1.25.02 1 1 0 0 0-.24.64V13q0 .28-.1.54a1 1 0 0 1-.32.34.8.8 0 0 1-1.17-.4 1 1 0 0 1-.07-.38V11q.01-.24-.05-.47a.9.9 0 0 0-.72-.62c-.37-.06-.65.11-.85.4q-.14.22-.14.46v2q.02.3-.04.59a.84.84 0 0 1-.87.63.9.9 0 0 1-.74-.63A1 1 0 0 1 4 13z",
        fill: "#fff"
      }
    )
  );
};

// src/consts/bluvo.tsx
var BLUVO_MIN_DEPOSIT_BY_CUSTOMER = {
  [ETHEREAL_API_KEY]: 15
};
var BLUVO_EXCHANGES = {
  coinbase: {
    icon: (size) => /* @__PURE__ */ React7.createElement(CoinbaseIcon, { size }),
    name: "Coinbase"
  },
  binance: {
    icon: (size) => /* @__PURE__ */ React7.createElement(BinanceIcon, { size }),
    name: "Binance"
  },
  gemini: {
    icon: (size) => /* @__PURE__ */ React7.createElement(GeminiIcon, { size }),
    name: "Gemini"
  },
  kraken: {
    icon: (size) => /* @__PURE__ */ React7.createElement(KrakenIcon, { size }),
    name: "Kraken"
  },
  gate: {
    icon: (size) => /* @__PURE__ */ React7.createElement(GateIoIcon, { size }),
    name: "Gate"
  }
};
function getExchangeName(brokerType) {
  return BLUVO_EXCHANGES[brokerType].name;
}
var FOP_COMPONENT_ICONS = {
  [FormOfPaymentType.BYBIT]: (size) => /* @__PURE__ */ React7.createElement(BybitIcon, { size })
};

// src/domains/paymentMethods.ts
function createPaymentMethodInfo(params) {
  switch (params.paymentMethod) {
    case PaymentMethod.CARD:
      return {
        paymentMethod: PaymentMethod.CARD,
        title: params.titleCustomization,
        description: ""
      };
    case PaymentMethod.ACCOUNT_BALANCE:
      return {
        paymentMethod: PaymentMethod.ACCOUNT_BALANCE,
        title: "Your Wallet",
        description: formatAddress(params.walletAddress || "")
      };
    case PaymentMethod.BROKERAGE:
      return {
        paymentMethod: PaymentMethod.BROKERAGE,
        title: getExchangeName(params.exchange),
        description: "",
        deviceId: params.deviceId,
        exchange: params.exchange
      };
    case PaymentMethod.TOKEN_TRANSFER:
      return {
        // this is an arbitrary value for Polymarket.
        paymentMethod: PaymentMethod.TOKEN_TRANSFER,
        title: "QR Code Transfer",
        description: ""
      };
    case PaymentMethod.BITCOIN_LIGHTNING:
      return {
        paymentMethod: PaymentMethod.BITCOIN_LIGHTNING,
        title: "Bitcoin on Cash App",
        description: ""
      };
    case PaymentMethod.VIRTUAL_BANK:
      return {
        paymentMethod: PaymentMethod.VIRTUAL_BANK,
        title: "Fiat Account",
        description: "",
        matchingFiatAccount: params.matchingFiatAccount,
        bridgeCustomer: params.bridgeCustomer
      };
    default:
      exhaustiveCheck(params);
      return {};
  }
}

// src/domains/clientMetadata.ts
function generateClientMetadataForTokenTransfer() {
  return {
    id: "",
    startTimestampMs: 0,
    finalDollarValue: 0,
    latestQuote: null,
    depositAddress: null,
    initSettings: {
      config: {
        targetAsset: "0x",
        targetChain: "",
        targetAssetTicker: "",
        checkoutItemTitle: ""
      }
    },
    selectedSourceAssetInfo: {
      address: "0x",
      symbol: "",
      chainId: "",
      iconSrc: null
    },
    selectedPaymentMethodInfo: createPaymentMethodInfo({
      paymentMethod: PaymentMethod.TOKEN_TRANSFER
    })
  };
}

// src/utils/statsig/checkFeatureGate.ts
import { defaultFeatureGates as fallbackFeatureGates } from "@funkit/connect-core";
import { StatsigClient } from "@statsig/react-bindings";

// src/providers/FunkitStatsigProvider.tsx
import { datadogLogs } from "@datadog/browser-logs";
import {
  LogEventCompressionMode,
  LogLevel,
  StatsigProvider,
  useClientAsyncInit
} from "@statsig/react-bindings";
import React8, { useEffect } from "react";
var STATSIG_CLIENT_KEY = "client-UmFd8WIJljA7cLmZuDqs3X25M8sKd5WIQP4BSC2bRbM";

// src/utils/statsig/checkFeatureGate.ts
function checkFeatureGate(name) {
  try {
    return StatsigClient.instance(STATSIG_CLIENT_KEY).checkGate(name);
  } catch (err) {
    logger.warn("checkFeatureGate:error", { name, err });
    return fallbackFeatureGates[name];
  }
}

// src/clients/polymarket.tsx
var PMCT_WITHDRAW_ACTION_TYPE = "PMCT_WITHDRAW";
var POLYGON_USDCE = "0x2791Bca1f2de4661ED88A30C99A7a9449Aa84174";
var PUSD_TOKEN = {
  address: POLYMARKET_PUSD_ADDRESS,
  symbol: "pUSD",
  iconSrc: "https://sdk-cdn.fun.xyz/images/pusd.svg"
};
var PUSD_OFFRAMP_ADDRESS = "0x2957922Eb93258b93368531d39fAcCA3B4dC5854";
var PUSD_OFFRAMP_ABI = [
  {
    name: "unwrap",
    type: "function",
    inputs: [
      { name: "_asset", type: "address" },
      { name: "_to", type: "address" },
      { name: "_amount", type: "uint256" }
    ],
    outputs: [],
    stateMutability: "nonpayable"
  }
];
function createPolymarketWithdrawalCallback(config) {
  const { userId, sendPmctTransfer } = config;
  return async (param) => {
    const { targetAssetAddress, targetChainId, destinationAddress, funQuote } = param;
    logger.info("polymarket:withdrawal:start", {
      targetChainId,
      targetAssetAddress,
      destinationAddress,
      quoteId: param.quoteId
    });
    const transferInit = await initializeCheckoutTokenTransferAddress({
      apiKey: POLYMARKET_API_KEY,
      userId,
      recipientAddr: destinationAddress,
      toChainId: targetChainId.toString(),
      toTokenAddress: targetAssetAddress,
      logger,
      clientMetadata: {
        ...generateClientMetadataForTokenTransfer(),
        isWithdrawal: true
      },
      actionType: PMCT_WITHDRAW_ACTION_TYPE
    });
    const udaAddress = transferInit.depositAddr;
    logger.info("polymarket:withdrawal:udaGenerated", { udaAddress });
    const amountBaseUnit = extractWithdrawalAmount(funQuote);
    await sendPmctTransfer({
      udaAddress,
      amountBaseUnit
    });
    logger.info("polymarket:withdrawal:transferSubmitted", {
      udaAddress,
      amountBaseUnit: amountBaseUnit.toString()
    });
    return void 0;
  };
}
function buildUdaWithdrawalConfig(config) {
  logger.info("polymarket:withdrawal:flow", { flow: "uda" });
  return {
    modalTitle: config.modalTitle ?? "Withdraw",
    disableConnectedWallet: config.disableConnectedWallet,
    withdrawCallback: createPolymarketWithdrawalCallback(config),
    sourceChainId: polygon.id.toString(),
    sourceTokenSymbol: config.sourceTokenSymbol ?? "USDC",
    defaultReceiveToken: config.defaultReceiveToken ?? "USDC",
    sourceTokenAddress: config.sourceTokenAddress ?? POLYGON_USDCE,
    iconSrc: config.iconSrc ?? "https://sdk-cdn.fun.xyz/images/usdc.svg",
    getMinWithdrawalUSD: () => 3
  };
}
function buildWalletUnwrapWithdrawalConfig(config) {
  logger.info("polymarket:withdrawal:flow", { flow: "wallet-unwrap" });
  const {
    proxyAddress,
    publicClient,
    sendTransactions: callerSendTransactions,
    confirmTransaction
  } = config;
  const wallet = {
    address: () => proxyAddress,
    getChainId: async () => polygon.id,
    switchChain: async (chainId) => {
      if (chainId !== polygon.id) {
        throw new Error(
          `Cannot switch chain: Polymarket withdrawal is fixed to ${polygon.id}, requested ${chainId}`
        );
      }
    },
    sendTransaction: async (_chainId, transaction) => callerSendTransactions([transaction]),
    sendTransactions: async (_chainId, txs) => callerSendTransactions(txs),
    confirmTransaction: confirmTransaction ?? (async (txHash) => publicClient.waitForTransactionReceipt({ hash: txHash }))
  };
  const preWithdrawalAction = async ({
    funQuote
  }) => {
    logger.info("polymarket:withdrawal:wallet:start", { proxyAddress });
    try {
      const amountBaseUnit = extractWithdrawalAmount(funQuote);
      const currentAllowance = await publicClient.readContract({
        address: PUSD_TOKEN.address,
        abi: erc20Abi,
        functionName: "allowance",
        args: [proxyAddress, PUSD_OFFRAMP_ADDRESS]
      });
      const needsApprovalTx = currentAllowance < amountBaseUnit;
      logger.info("polymarket:withdrawal:wallet:allowanceChecked", {
        proxyAddress,
        amountBaseUnit: amountBaseUnit.toString(),
        currentAllowance: currentAllowance.toString(),
        needsApprovalTx
      });
      const txs = [];
      if (needsApprovalTx) {
        txs.push({
          to: PUSD_TOKEN.address,
          data: encodeFunctionData({
            abi: erc20Abi,
            functionName: "approve",
            args: [PUSD_OFFRAMP_ADDRESS, amountBaseUnit]
          }),
          value: "0"
        });
      }
      txs.push({
        to: PUSD_OFFRAMP_ADDRESS,
        data: encodeFunctionData({
          abi: PUSD_OFFRAMP_ABI,
          functionName: "unwrap",
          args: [POLYGON_USDCE, proxyAddress, amountBaseUnit]
        }),
        value: "0"
      });
      logger.info("polymarket:withdrawal:wallet:txsStaged", {
        proxyAddress,
        txCount: txs.length,
        needsApprovalTx
      });
      return txs;
    } catch (err) {
      logger.error("polymarket:withdrawal:wallet:error", err, {
        phase: "preWithdrawal",
        proxyAddress
      });
      throw err;
    }
  };
  return {
    modalTitle: config.modalTitle ?? "Withdraw",
    disableConnectedWallet: config.disableConnectedWallet,
    sourceChainId: polygon.id.toString(),
    sourceTokenSymbol: config.sourceTokenSymbol ?? PUSD_TOKEN.symbol,
    sourceTokenAddress: config.sourceTokenAddress ?? POLYGON_USDCE,
    defaultReceiveToken: config.defaultReceiveToken ?? "USDC",
    iconSrc: config.iconSrc ?? PUSD_TOKEN.iconSrc,
    getMinWithdrawalUSD: () => 0,
    wallet,
    preWithdrawalAction
  };
}
function extractWithdrawalAmount(funQuote) {
  const quote = funQuote;
  const amountStr = quote?.baseQuote?.estTotalFromAmountBaseUnit;
  if (!amountStr) {
    logger.error("polymarket:withdrawal:missingAmountInQuote", { quote });
    throw new Error("Missing withdrawal amount in quote");
  }
  return BigInt(amountStr);
}
function createPolymarketWithdrawalConfig(config) {
  if ("sendPmctTransfer" in config && "sendTransactions" in config) {
    const walletUnwrapEnabled = checkFeatureGate(
      "enable-polymarket-wallet-withdrawal"
    );
    logger.info("polymarket:withdrawal:gate", { walletUnwrapEnabled });
    return walletUnwrapEnabled ? buildWalletUnwrapWithdrawalConfig(config) : buildUdaWithdrawalConfig(config);
  }
  return "sendPmctTransfer" in config ? buildUdaWithdrawalConfig(config) : buildWalletUnwrapWithdrawalConfig(config);
}
var COLLATERAL_ONRAMP_ADDRESS = "0x93070a847efEf7F70739046A929D47a521F5B8ee";
var COLLATERAL_ONRAMP_ABI = [
  {
    name: "wrap",
    type: "function",
    inputs: [
      { name: "_asset", type: "address" },
      { name: "_to", type: "address" },
      { name: "_amount", type: "uint256" }
    ],
    outputs: [],
    stateMutability: "nonpayable"
  }
];
var POLYMARKET_PERPS_ADDRESS = "0xdca4af75705dbb50f62437045aff9921947917d2";
var POLYMARKET_PERPS_ABI = [
  {
    name: "deposit",
    type: "function",
    stateMutability: "nonpayable",
    inputs: [
      { internalType: "address", name: "token", type: "address" },
      { internalType: "uint256", name: "amount", type: "uint256" },
      { internalType: "address", name: "to", type: "address" }
    ],
    outputs: []
  }
];
var VAULT_DEPOSITOR_POLYGON = getAddress2(
  "0xC8A6871D4eC4DaE64f605db0f8a0B3D9ef928D64"
);
var VAULT_DEPOSITOR_ABI = [
  {
    name: "deposit",
    type: "function",
    stateMutability: "nonpayable",
    inputs: [
      { name: "token", type: "address" },
      { name: "vault", type: "address" },
      { name: "callData", type: "bytes" },
      { name: "minAmountOut", type: "uint256" }
    ],
    outputs: [{ name: "returnData", type: "bytes" }]
  }
];
var RELAY_ROUTER_V3_ADDRESS = getAddress2(
  "0xb92fe925DC43a0ECdE6c8b1a2709c170Ec4fFf4f"
);
var RELAY_ROUTER_V3_ABI = [
  {
    inputs: [
      { internalType: "address[]", name: "tokens", type: "address[]" },
      { internalType: "address[]", name: "tos", type: "address[]" },
      { internalType: "bytes[]", name: "datas", type: "bytes[]" },
      { internalType: "uint256[]", name: "amounts", type: "uint256[]" }
    ],
    name: "cleanupErc20sViaCall",
    outputs: [],
    stateMutability: "nonpayable",
    type: "function"
  }
];
var AMOUNT_PLACEHOLDER = 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffdeadbeefn;
function createPerpsGenerateActionParams(config) {
  const { recipientAddress } = config;
  return async () => {
    const wrapUsdceToPusd = encodeFunctionData({
      abi: COLLATERAL_ONRAMP_ABI,
      functionName: "wrap",
      args: [POLYGON_USDCE, RELAY_ROUTER_V3_ADDRESS, AMOUNT_PLACEHOLDER]
    });
    const wrapUsdceToPusdViaVaultDepositor = encodeFunctionData({
      abi: VAULT_DEPOSITOR_ABI,
      functionName: "deposit",
      args: [POLYGON_USDCE, COLLATERAL_ONRAMP_ADDRESS, wrapUsdceToPusd, 0n]
    });
    const depositPusdToPerps = encodeFunctionData({
      abi: POLYMARKET_PERPS_ABI,
      functionName: "deposit",
      args: [PUSD_TOKEN.address, AMOUNT_PLACEHOLDER, recipientAddress]
    });
    const depositPusdToPerpsViaVaultDepositor = encodeFunctionData({
      abi: VAULT_DEPOSITOR_ABI,
      functionName: "deposit",
      args: [
        PUSD_TOKEN.address,
        POLYMARKET_PERPS_ADDRESS,
        depositPusdToPerps,
        0n
      ]
    });
    const legs = [
      // Leg 1 — sweep the bridged USDC.e and wrap it into pUSD.
      {
        token: POLYGON_USDCE,
        to: VAULT_DEPOSITOR_POLYGON,
        data: wrapUsdceToPusdViaVaultDepositor,
        // relay replaces this with the actual amount of tokens available at execution time https://github.com/relayprotocol/relay-periphery/blob/0e4aabb750efb1f807d7f12b83b090b51b9ee736/src/v3/RelayRouterV3.sol#L177-L180
        amount: 0n
      },
      // Leg 2 — sweep the resulting pUSD and deposit it into Polymarket Perps
      // for the recipient.
      {
        token: PUSD_TOKEN.address,
        to: VAULT_DEPOSITOR_POLYGON,
        data: depositPusdToPerpsViaVaultDepositor,
        // relay replaces this with the actual amount of tokens available at execution time https://github.com/relayprotocol/relay-periphery/blob/0e4aabb750efb1f807d7f12b83b090b51b9ee736/src/v3/RelayRouterV3.sol#L177-L180
        amount: 0n
      }
    ];
    return [
      // RelayRouterV3 calls its function `cleanupErc20sViaCall`
      // that iterates over the legs and does the following for each leg:
      // 1. Substitutes 0n with the actual amount of tokens available at execution time (https://github.com/relayprotocol/relay-periphery/blob/0e4aabb750efb1f807d7f12b83b090b51b9ee736/src/v3/RelayRouterV3.sol#L177-L180):
      // `IERC20(token).balanceOf(address(this))`
      // 2. Approves the token to the target address (https://github.com/relayprotocol/relay-periphery/blob/0e4aabb750efb1f807d7f12b83b090b51b9ee736/src/v3/RelayRouterV3.sol#L183-L184):
      // `IERC20(token).approve(to, amount)`
      // 3. Makes the call to the target address and bubles up the revert if it fails (https://github.com/relayprotocol/relay-periphery/blob/0e4aabb750efb1f807d7f12b83b090b51b9ee736/src/v3/RelayRouterV3.sol#L186-L190):
      // `(bool success, ) = to.call(data);
      // `if (!success) { revert CallFailed(); }`
      {
        contractAbi: RELAY_ROUTER_V3_ABI,
        contractAddress: RELAY_ROUTER_V3_ADDRESS,
        functionName: "cleanupErc20sViaCall",
        // cleanupErc20sViaCall takes parallel arrays — transpose the per-leg rows.
        functionArgs: [
          legs.map((leg) => leg.token),
          legs.map((leg) => leg.to),
          legs.map((leg) => leg.data),
          legs.map((leg) => leg.amount)
        ]
      }
    ];
  };
}
export {
  createPerpsGenerateActionParams,
  createPolymarketWithdrawalConfig
};
