polymarketClient.js 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824
  1. import axios from "axios";
  2. import qs from "qs";
  3. import { HttpsProxyAgent } from "https-proxy-agent";
  4. import { AssetType, Chain, ClobClient, OrderType, Side, SignatureTypeV2 } from "@polymarket/clob-client-v2";
  5. import { BuilderConfig } from "@polymarket/builder-signing-sdk";
  6. import { deriveProxyWallet, RelayerTxType, RelayClient } from "@polymarket/builder-relayer-client";
  7. import {
  8. createPublicClient,
  9. createWalletClient,
  10. encodeFunctionData,
  11. erc20Abi,
  12. formatUnits,
  13. http,
  14. parseUnits,
  15. } from "viem";
  16. import { privateKeyToAccount } from "viem/accounts";
  17. import { polygon } from "viem/chains";
  18. import WebSocketClient from "./webSocketClient.js";
  19. import Logs from "./logs.js";
  20. const NODE_HTTP_PROXY = process.env.NODE_HTTP_PROXY;
  21. const proxyAgent = NODE_HTTP_PROXY ? new HttpsProxyAgent(NODE_HTTP_PROXY) : undefined;
  22. if (NODE_HTTP_PROXY) {
  23. axios.defaults.proxy = false;
  24. axios.defaults.httpAgent = proxyAgent;
  25. axios.defaults.httpsAgent = proxyAgent;
  26. }
  27. const CHAIN_ID = 137;
  28. const GAMMA_HOST = "https://gamma-api.polymarket.com";
  29. const CLOB_HOST = "https://clob.polymarket.com";
  30. const PUSD_ADDRESS = "0xC011a7E12a19f7B1f670d46F03B03f3342E82DFB";
  31. const PUSD_DECIMALS = 6;
  32. const PROXY_FACTORY_ADDRESS = "0xaB45c5A4B0c941a2F231C04C3f49182e1A254052";
  33. /**
  34. * axios 默认配置
  35. */
  36. const axiosDefaultOptions = {
  37. baseURL: "",
  38. url: "",
  39. method: "GET",
  40. headers: {},
  41. params: {},
  42. data: {},
  43. timeout: 10000,
  44. };
  45. /**
  46. * 通用请求
  47. * @param {*} options
  48. * @param {*} baseURL
  49. * @returns
  50. */
  51. const clientRequest = async (options, baseURL) => {
  52. const { url } = options;
  53. if (!url || !baseURL) {
  54. throw new Error("url and baseURL are required");
  55. }
  56. const mergedOptions = {
  57. ...axiosDefaultOptions,
  58. ...options,
  59. baseURL,
  60. paramsSerializer: params => qs.stringify(params, { arrayFormat: 'repeat' })
  61. };
  62. return axios(mergedOptions).then(res => res.data);
  63. }
  64. /**
  65. * 请求市场数据
  66. * @param {*} options
  67. * @returns
  68. */
  69. const requestMarketData = async (options) => {
  70. return clientRequest(options, GAMMA_HOST);
  71. }
  72. /**
  73. * 请求订单簿数据
  74. */
  75. const requestClobData = async (options) => {
  76. return clientRequest(options, CLOB_HOST);
  77. }
  78. const getRequiredEnv = (key) => {
  79. const value = process.env[key];
  80. if (!value) {
  81. throw new Error(`${key} is required`);
  82. }
  83. return value;
  84. }
  85. const normalizePrivateKey = (privateKey) => {
  86. return privateKey.startsWith("0x") ? privateKey : `0x${privateKey}`;
  87. }
  88. const getOptionalEnv = (key) => {
  89. const value = process.env[key];
  90. return value && value.trim() ? value.trim() : undefined;
  91. }
  92. const getPolymarketFunderAddress = (accountAddress) => {
  93. return getOptionalEnv("POLYMARKET_DEPOSIT_WALLET_ADDRESS")
  94. || getOptionalEnv("POLYMARKET_FUNDER_ADDRESS")
  95. || accountAddress;
  96. }
  97. const getPolymarketSignatureType = (funderAddress, accountAddress) => {
  98. const configuredType = getOptionalEnv("POLYMARKET_SIGNATURE_TYPE");
  99. if (configuredType) {
  100. const signatureType = SignatureTypeV2[configuredType] ?? Number(configuredType);
  101. if (!Number.isInteger(signatureType) || !SignatureTypeV2[signatureType]) {
  102. throw new Error(`POLYMARKET_SIGNATURE_TYPE is invalid: ${configuredType}`);
  103. }
  104. return signatureType;
  105. }
  106. return funderAddress.toLowerCase() === accountAddress.toLowerCase()
  107. ? SignatureTypeV2.POLY_PROXY
  108. : SignatureTypeV2.POLY_1271;
  109. }
  110. /**
  111. * 创建 viem HTTP transport
  112. * NODE_HTTP_PROXY 存在时通过 axios 代理请求 Polygon RPC
  113. * @param {string} rpcUrl
  114. * @returns {import("viem").HttpTransport}
  115. */
  116. const createViemHttpTransport = (rpcUrl) => {
  117. if (!NODE_HTTP_PROXY) {
  118. return rpcUrl ? http(rpcUrl) : http();
  119. }
  120. const fetchFn = async (url, init = {}) => {
  121. const headers = Object.fromEntries(new Headers(init.headers ?? {}).entries());
  122. const response = await axios({
  123. url,
  124. method: init.method || "POST",
  125. headers,
  126. data: init.body,
  127. transformResponse: [data => data],
  128. responseType: "text",
  129. validateStatus: () => true,
  130. });
  131. return new Response(response.data, {
  132. status: response.status,
  133. statusText: response.statusText,
  134. headers: response.headers,
  135. });
  136. };
  137. return http(rpcUrl, { fetchFn });
  138. }
  139. export const createClobClient = () => {
  140. const account = privateKeyToAccount(normalizePrivateKey(getRequiredEnv("POLYMARKET_PRIVATE_KEY")));
  141. const signer = createWalletClient({
  142. account,
  143. chain: polygon,
  144. transport: createViemHttpTransport(getOptionalEnv("POLYGON_RPC_URL")),
  145. });
  146. const funderAddress = getPolymarketFunderAddress(account.address);
  147. const userApiCreds = {
  148. key: getRequiredEnv("POLYMARKET_API_KEY"),
  149. secret: getRequiredEnv("POLYMARKET_API_SECRET"),
  150. passphrase: getRequiredEnv("POLYMARKET_API_PASSPHRASE"),
  151. };
  152. return new ClobClient({
  153. host: CLOB_HOST,
  154. chain: Chain.POLYGON,
  155. signer,
  156. creds: userApiCreds,
  157. signatureType: getPolymarketSignatureType(funderAddress, account.address),
  158. funderAddress,
  159. throwOnError: true,
  160. });
  161. }
  162. const createPolymarketContext = () => {
  163. const rpcUrl = getOptionalEnv("POLYGON_RPC_URL");
  164. const transport = createViemHttpTransport(rpcUrl);
  165. const account = privateKeyToAccount(normalizePrivateKey(getRequiredEnv("POLYMARKET_PRIVATE_KEY")));
  166. const signer = createWalletClient({ account, chain: polygon, transport });
  167. const publicClient = createPublicClient({ chain: polygon, transport });
  168. const creds = {
  169. key: getRequiredEnv("POLYMARKET_API_KEY"),
  170. secret: getRequiredEnv("POLYMARKET_API_SECRET"),
  171. passphrase: getRequiredEnv("POLYMARKET_API_PASSPHRASE"),
  172. };
  173. return { account, signer, publicClient, creds };
  174. }
  175. const normalizeWalletMode = (wallet = "both") => {
  176. const value = wallet.toLowerCase();
  177. if (!["deposit", "proxy", "both"].includes(value)) {
  178. throw new Error("wallet must be deposit, proxy, or both", { cause: 400 });
  179. }
  180. return value;
  181. }
  182. const createBalanceClobClient = ({ signer, creds, funderAddress, signatureType }) => {
  183. return new ClobClient({
  184. host: CLOB_HOST,
  185. chain: Chain.POLYGON,
  186. signer,
  187. creds,
  188. signatureType,
  189. funderAddress,
  190. throwOnError: true,
  191. });
  192. }
  193. const getChainPusdBalance = async ({ publicClient, address }) => {
  194. const balance = await publicClient.readContract({
  195. address: PUSD_ADDRESS,
  196. abi: erc20Abi,
  197. functionName: "balanceOf",
  198. args: [address],
  199. });
  200. return formatUnits(balance, PUSD_DECIMALS);
  201. }
  202. const getClobBalanceAllowance = async ({ signer, creds, funderAddress, signatureType }) => {
  203. const client = createBalanceClobClient({ signer, creds, funderAddress, signatureType });
  204. return client.getBalanceAllowance({ asset_type: AssetType.COLLATERAL });
  205. }
  206. const createBuilderConfig = () => {
  207. return new BuilderConfig({
  208. localBuilderCreds: {
  209. key: getRequiredEnv("POLYMARKET_BUILDER_API_KEY"),
  210. secret: getRequiredEnv("POLYMARKET_BUILDER_SECRET"),
  211. passphrase: getRequiredEnv("POLYMARKET_BUILDER_PASS_PHRASE"),
  212. },
  213. });
  214. }
  215. /**
  216. * 创建 Polymarket builder relayer 客户端
  217. * @param {Object} options
  218. * @param {Object} options.signer viem wallet client
  219. * @param {number} options.relayTxType relayer 交易类型
  220. * @returns {RelayClient}
  221. */
  222. const createRelayer = ({ signer, relayTxType = RelayerTxType.PROXY } = {}) => {
  223. const relayerUrl = getOptionalEnv("POLYMARKET_RELAYER_URL") || "https://relayer-v2.polymarket.com";
  224. const relayer = new RelayClient(relayerUrl, CHAIN_ID, signer, createBuilderConfig(), relayTxType);
  225. if (proxyAgent) {
  226. relayer.httpClient.instance.defaults.proxy = false;
  227. relayer.httpClient.instance.defaults.httpAgent = proxyAgent;
  228. relayer.httpClient.instance.defaults.httpsAgent = proxyAgent;
  229. }
  230. return relayer;
  231. }
  232. /**
  233. * 获取 Polymarket proxy wallet 地址
  234. * @param {Object} options
  235. * @param {string} options.ownerAddress owner 钱包地址
  236. * @returns {string}
  237. */
  238. const getProxyWalletAddress = ({ ownerAddress }) => {
  239. return getOptionalEnv("POLYMARKET_PROXY_WALLET_ADDRESS")
  240. || deriveProxyWallet(ownerAddress, PROXY_FACTORY_ADDRESS);
  241. }
  242. /**
  243. * 获取 Polymarket deposit wallet 地址
  244. * @param {Object} options
  245. * @param {Object} options.signer viem wallet client
  246. * @returns {Promise<string>}
  247. */
  248. const getDepositWalletAddress = async ({ signer }) => {
  249. const configuredAddress = getOptionalEnv("POLYMARKET_DEPOSIT_WALLET_ADDRESS");
  250. if (configuredAddress) {
  251. return configuredAddress;
  252. }
  253. const relayer = createRelayer({ signer });
  254. return relayer.deriveDepositWalletAddress();
  255. }
  256. /**
  257. * 获取 pUSD 转账所需的钱包上下文
  258. * @returns {Promise<Object>} owner、signer、publicClient、relayer 和 proxy/deposit 钱包地址
  259. */
  260. const getTransferWalletContext = async () => {
  261. const { account, signer, publicClient } = createPolymarketContext();
  262. const proxyRelayer = createRelayer({ signer, relayTxType: RelayerTxType.PROXY });
  263. const proxyWalletAddress = getProxyWalletAddress({ ownerAddress: account.address });
  264. const depositWalletAddress = await getDepositWalletAddress({ signer });
  265. return {
  266. account,
  267. signer,
  268. publicClient,
  269. proxyRelayer,
  270. proxyWalletAddress,
  271. depositWalletAddress,
  272. };
  273. }
  274. /**
  275. * 获取钱包原始 pUSD 余额
  276. * @param {Object} options
  277. * @param {Object} options.publicClient viem public client
  278. * @param {string} options.address 钱包地址
  279. * @returns {Promise<bigint>}
  280. */
  281. const getRawPusdBalance = ({ publicClient, address }) => {
  282. return publicClient.readContract({
  283. address: PUSD_ADDRESS,
  284. abi: erc20Abi,
  285. functionName: "balanceOf",
  286. args: [address],
  287. });
  288. }
  289. /**
  290. * 校验并转换转账金额为 pUSD 最小单位
  291. * @param {string|number} amount 转账数量
  292. * @returns {bigint}
  293. */
  294. const normalizeTransferAmount = (amount) => {
  295. if (!amount || !Number.isFinite(Number(amount)) || Number(amount) <= 0) {
  296. throw new Error("amount must be greater than 0", { cause: 400 });
  297. }
  298. return parseUnits(String(amount), PUSD_DECIMALS);
  299. }
  300. /**
  301. * 校验并标准化钱包转账方向
  302. * @param {Object} options
  303. * @param {string} options.from 来源钱包类型
  304. * @param {string} options.to 目标钱包类型
  305. * @returns {{from: "proxy"|"deposit", to: "proxy"|"deposit"}}
  306. */
  307. const normalizeTransferDirection = ({ from, to } = {}) => {
  308. const normalizedFrom = String(from || "").toLowerCase();
  309. const normalizedTo = String(to || "").toLowerCase();
  310. if (
  311. !["proxy", "deposit"].includes(normalizedFrom)
  312. || !["proxy", "deposit"].includes(normalizedTo)
  313. || normalizedFrom === normalizedTo
  314. ) {
  315. throw new Error("Transfer direction must be proxy -> deposit or deposit -> proxy", { cause: 400 });
  316. }
  317. return { from: normalizedFrom, to: normalizedTo };
  318. }
  319. /**
  320. * 生成 pUSD ERC20 transfer 调用数据
  321. * @param {Object} options
  322. * @param {string} options.to 收款钱包地址
  323. * @param {bigint} options.amount pUSD 最小单位金额
  324. * @returns {string}
  325. */
  326. const createPusdTransferData = ({ to, amount }) => {
  327. return encodeFunctionData({
  328. abi: erc20Abi,
  329. functionName: "transfer",
  330. args: [to, amount],
  331. });
  332. }
  333. /**
  334. * 统一格式化钱包转账返回结果
  335. * @param {Object} options
  336. * @returns {Object}
  337. */
  338. const buildTransferResult = ({
  339. owner,
  340. from,
  341. to,
  342. sourceAddress,
  343. destinationAddress,
  344. amount,
  345. sourceBalance,
  346. transactionID,
  347. transactionHash,
  348. confirmed,
  349. }) => {
  350. return {
  351. owner,
  352. pUSD: PUSD_ADDRESS,
  353. from,
  354. to,
  355. sourceAddress,
  356. destinationAddress,
  357. amount: String(amount),
  358. sourceBalance: formatUnits(sourceBalance, PUSD_DECIMALS),
  359. transactionID,
  360. transactionHash,
  361. confirmed,
  362. };
  363. }
  364. /**
  365. * 校验来源钱包 pUSD 余额是否足够
  366. * @param {Object} options
  367. * @param {string} options.wallet 钱包类型
  368. * @param {bigint} options.balance 当前余额
  369. * @param {bigint} options.amount 转账金额
  370. */
  371. const ensureSufficientPusdBalance = ({ wallet, balance, amount }) => {
  372. if (balance < amount) {
  373. throw new Error(`Insufficient ${wallet} wallet pUSD balance: ${formatUnits(balance, PUSD_DECIMALS)}`, { cause: 400 });
  374. }
  375. }
  376. /**
  377. * 根据转账方向提交 relayer 交易
  378. * @param {Object} options
  379. * @param {"proxy"|"deposit"} options.from 来源钱包类型
  380. * @param {"proxy"|"deposit"} options.to 目标钱包类型
  381. * @param {Object} options.context 转账钱包上下文
  382. * @param {string} options.data pUSD transfer 调用数据
  383. * @param {string|number} options.amount 展示用转账数量
  384. * @returns {Promise<Object>}
  385. */
  386. const executePusdTransfer = ({
  387. from,
  388. to,
  389. context,
  390. data,
  391. amount,
  392. }) => {
  393. if (from === "proxy" && to === "deposit") {
  394. return context.proxyRelayer.execute(
  395. [{
  396. to: PUSD_ADDRESS,
  397. data,
  398. value: "0",
  399. }],
  400. `transfer ${amount} pUSD from proxy to deposit wallet`,
  401. );
  402. }
  403. const depositRelayer = createRelayer({ signer: context.signer });
  404. return depositRelayer.executeDepositWalletBatch(
  405. [{
  406. target: PUSD_ADDRESS,
  407. data,
  408. value: "0",
  409. }],
  410. context.depositWalletAddress,
  411. String(Math.floor(Date.now() / 1000) + 600),
  412. );
  413. }
  414. /**
  415. * 执行 pUSD 钱包间转账的公共流程
  416. * @param {Object} options
  417. * @param {string|number} options.amount 转账数量
  418. * @param {"proxy"|"deposit"} options.from 来源钱包类型
  419. * @param {"proxy"|"deposit"} options.to 目标钱包类型
  420. * @returns {Promise<Object>}
  421. */
  422. const transferPusdBetweenWallets = async ({
  423. amount,
  424. from,
  425. to,
  426. } = {}) => {
  427. const transferAmount = normalizeTransferAmount(amount);
  428. const context = await getTransferWalletContext();
  429. const sourceAddress = from === "proxy"
  430. ? context.proxyWalletAddress
  431. : context.depositWalletAddress;
  432. const destinationAddress = to === "proxy"
  433. ? context.proxyWalletAddress
  434. : context.depositWalletAddress;
  435. const sourceBalance = await getRawPusdBalance({
  436. publicClient: context.publicClient,
  437. address: sourceAddress,
  438. });
  439. ensureSufficientPusdBalance({
  440. wallet: from,
  441. balance: sourceBalance,
  442. amount: transferAmount,
  443. });
  444. const data = createPusdTransferData({
  445. to: destinationAddress,
  446. amount: transferAmount,
  447. });
  448. const response = await executePusdTransfer({
  449. from,
  450. to,
  451. context,
  452. data,
  453. amount,
  454. });
  455. const confirmed = await response.wait();
  456. return buildTransferResult({
  457. owner: context.account.address,
  458. from,
  459. to,
  460. sourceAddress,
  461. destinationAddress,
  462. amount,
  463. sourceBalance,
  464. transactionID: response.transactionID,
  465. transactionHash: response.transactionHash || response.hash,
  466. confirmed,
  467. });
  468. }
  469. /**
  470. * 获取足球联赛
  471. * @returns {Promise}
  472. */
  473. export const getSoccerSports = async () => {
  474. return requestMarketData({ url: "/sports" })
  475. .then(sportsData => {
  476. return sportsData.filter(item => {
  477. const { tags } = item;
  478. const tagIds = tags.split(",").map(item => +item);
  479. return tagIds.includes(100350);
  480. });
  481. });
  482. }
  483. /**
  484. * 获取赛事数据
  485. * @param {Object} options
  486. * @param {number} options.limit
  487. * @param {number} options.tag_id
  488. * @param {boolean} options.active
  489. * @param {boolean} options.closed
  490. * @param {string} options.endDateMin
  491. * @param {string} options.endDateMax
  492. * @returns {Promise}
  493. */
  494. export const getEvents = async ({
  495. limit = 500, tag_id = 100350, active = true,
  496. closed = false, endDateMin = "", endDateMax = "",
  497. } = {}) => {
  498. return requestMarketData({
  499. url: "/events",
  500. params: {
  501. limit, tag_id, active, closed,
  502. end_date_min: endDateMin,
  503. end_date_max: endDateMax,
  504. }
  505. }).then(events => events.filter(item => !!item.series));
  506. }
  507. /**
  508. * 获取订单簿数据
  509. */
  510. export const getOrderBook = async (tokenId) => {
  511. return requestClobData({
  512. url: "/book",
  513. params: {
  514. token_id: tokenId,
  515. }
  516. });
  517. }
  518. /**
  519. * 批量获取订单簿数据
  520. * @param {Array} tokenIds
  521. * @returns {Promise}
  522. */
  523. export const getMultipleOrderBooks = async (tokenIds) => {
  524. return requestClobData({
  525. url: "/books",
  526. method: 'POST',
  527. headers: {
  528. 'Content-Type': 'application/json',
  529. },
  530. data: tokenIds.map(tokenId => ({ token_id: tokenId })),
  531. });
  532. }
  533. /**
  534. * 获取 USDC collateral 余额和授权信息
  535. */
  536. export const getBalanceAllowance = async ({ wallet = "both" } = {}) => {
  537. const walletMode = normalizeWalletMode(wallet);
  538. const { account, signer, publicClient, creds } = createPolymarketContext();
  539. const wallets = [];
  540. if (walletMode === "proxy" || walletMode === "both") {
  541. wallets.push({
  542. type: "proxy",
  543. address: getProxyWalletAddress({ ownerAddress: account.address }),
  544. signatureType: SignatureTypeV2.POLY_PROXY,
  545. });
  546. }
  547. if (walletMode === "deposit" || walletMode === "both") {
  548. wallets.push({
  549. type: "deposit",
  550. address: await getDepositWalletAddress({ signer }),
  551. signatureType: SignatureTypeV2.POLY_1271,
  552. });
  553. }
  554. const results = [];
  555. for (const item of wallets) {
  556. const [chainPusdBalance, clobBalanceAllowance] = await Promise.all([
  557. getChainPusdBalance({ publicClient, address: item.address }),
  558. getClobBalanceAllowance({
  559. signer,
  560. creds,
  561. funderAddress: item.address,
  562. signatureType: item.signatureType,
  563. }),
  564. ]);
  565. results.push({
  566. type: item.type,
  567. owner: account.address,
  568. address: item.address,
  569. signatureType: SignatureTypeV2[item.signatureType],
  570. chainPusdBalance,
  571. clobBalanceAllowance,
  572. });
  573. }
  574. return results;
  575. }
  576. /**
  577. * 在 Proxy wallet 和 Deposit wallet 之间转 pUSD
  578. * @param {Object} options
  579. * @param {string|number} options.amount 转账数量
  580. * @param {"proxy"|"deposit"} options.from 来源钱包类型
  581. * @param {"proxy"|"deposit"} options.to 目标钱包类型
  582. * @returns {Promise<Object>}
  583. */
  584. export const transferWallet = async ({ amount, from, to } = {}) => {
  585. const direction = normalizeTransferDirection({ from, to });
  586. return transferPusdBetweenWallets({
  587. amount,
  588. from: direction.from,
  589. to: direction.to,
  590. });
  591. }
  592. /**
  593. * 创建 Polymarket 限价挂单
  594. */
  595. export const createLimitOrder = async ({
  596. tokenID,
  597. price,
  598. size,
  599. side = Side.BUY,
  600. tickSize = "0.01",
  601. negRisk = false,
  602. orderType = OrderType.GTC,
  603. postOnly = true,
  604. expiration,
  605. deferExec = false,
  606. } = {}) => {
  607. if (!tokenID) {
  608. throw new Error("tokenID is required", { cause: 400 });
  609. }
  610. if (!Number.isFinite(Number(price))) {
  611. throw new Error("price is required", { cause: 400 });
  612. }
  613. if (!Number.isFinite(Number(size))) {
  614. throw new Error("size is required", { cause: 400 });
  615. }
  616. if (orderType !== OrderType.GTC && orderType !== OrderType.GTD) {
  617. throw new Error(`orderType must be ${OrderType.GTC} or ${OrderType.GTD}`, { cause: 400 });
  618. }
  619. const client = createClobClient();
  620. const orderData = {
  621. tokenID,
  622. price: Number(price),
  623. size: Number(size),
  624. side,
  625. ...(expiration ? { expiration: Number(expiration) } : {}),
  626. };
  627. const orderOptions = { tickSize, negRisk };
  628. Logs.outDev('polymarket create limit order data', orderData, orderOptions, orderType, postOnly, deferExec);
  629. return client.createAndPostOrder(orderData, orderOptions, orderType, postOnly, deferExec);
  630. }
  631. /**
  632. * 查询单个 Polymarket 订单
  633. * @param {string} orderID 订单 ID
  634. * @returns {Promise<Object>}
  635. */
  636. export const getOrder = async (orderID) => {
  637. if (!orderID) {
  638. throw new Error("orderID is required", { cause: 400 });
  639. }
  640. const client = createClobClient();
  641. return client.getOrder(orderID);
  642. }
  643. /**
  644. * 查询 Polymarket 开放订单
  645. * @param {Object} options
  646. * @param {string} options.id 订单 ID
  647. * @param {string} options.market 市场 ID
  648. * @param {string} options.asset_id token/asset ID
  649. * @param {boolean} options.only_first_page 是否只查第一页
  650. * @param {string} options.next_cursor 分页 cursor
  651. * @returns {Promise<Array>}
  652. */
  653. export const getOpenOrders = async ({
  654. id,
  655. market,
  656. asset_id,
  657. only_first_page = false,
  658. next_cursor,
  659. } = {}) => {
  660. const client = createClobClient();
  661. const params = {
  662. ...(id ? { id } : {}),
  663. ...(market ? { market } : {}),
  664. ...(asset_id ? { asset_id } : {}),
  665. };
  666. return client.getOpenOrders(params, Boolean(only_first_page), next_cursor);
  667. }
  668. /**
  669. * 请求平台数据
  670. * @param {*} options
  671. * @returns {Promise}
  672. */
  673. export const platformRequest = async (options) => {
  674. const { url } = options;
  675. if (!url) {
  676. throw new Error("url is required");
  677. }
  678. const internalToken = process.env.PPAI_INTERNAL_API_TOKEN;
  679. const mergedOptions = {
  680. ...axiosDefaultOptions,
  681. ...options,
  682. baseURL: "http://127.0.0.1:9020",
  683. headers: {
  684. ...axiosDefaultOptions.headers,
  685. ...options.headers,
  686. ...(internalToken ? { Authorization: `Bearer ${internalToken}` } : {}),
  687. },
  688. httpAgent: null,
  689. httpsAgent: null,
  690. proxy: false,
  691. };
  692. return axios(mergedOptions).then(res => res.data);
  693. }
  694. /**
  695. * 请求平台 POST 数据
  696. * @param {string} url
  697. * @param {Object} data
  698. * @returns {Promise}
  699. */
  700. export const platformPost = async (url, data) => {
  701. return platformRequest({
  702. url,
  703. method: 'POST',
  704. headers: {
  705. 'Content-Type': 'application/json',
  706. },
  707. data,
  708. });
  709. }
  710. /**
  711. * 请求平台 GET 数据
  712. * @param {string} url
  713. * @param {Object} params
  714. * @returns {Promise}
  715. */
  716. export const platformGet = async (url, params) => {
  717. return platformRequest({ url, method: 'GET', params });
  718. }
  719. /**
  720. * 市场 WebSocket 客户端
  721. */
  722. export class MarketWsClient extends WebSocketClient {
  723. #assetIds = [];
  724. constructor() {
  725. let agent;
  726. const proxy = process.env.NODE_HTTP_PROXY;
  727. if (proxy) {
  728. agent = new HttpsProxyAgent(proxy);
  729. }
  730. super("wss://ws-subscriptions-clob.polymarket.com/ws/market", { agent });
  731. }
  732. connect() {
  733. super.connect();
  734. this.on('open', () => {
  735. if (this.#assetIds.length > 0) {
  736. this.subscribeToTokensIds(this.#assetIds);
  737. }
  738. });
  739. }
  740. subscribeToTokensIds(assetIds) {
  741. this.#assetIds = [...new Set([...this.#assetIds, ...assetIds])];
  742. this.send({
  743. operation: "subscribe",
  744. assets_ids: assetIds,
  745. });
  746. }
  747. unsubscribeToTokensIds(assetIds) {
  748. const assetIdsSet = new Set(assetIds);
  749. this.#assetIds = this.#assetIds.filter(id => !assetIdsSet.has(id));
  750. this.send({
  751. operation: "unsubscribe",
  752. assets_ids: assetIds,
  753. });
  754. }
  755. }