apikey.js 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. import 'dotenv/config';
  2. import axios from "axios";
  3. import { HttpsProxyAgent } from "https-proxy-agent";
  4. import { Chain, ClobClient } from "@polymarket/clob-client-v2";
  5. import { createWalletClient, http } from "viem";
  6. import { privateKeyToAccount } from "viem/accounts";
  7. import { polygon } from "viem/chains";
  8. const NODE_HTTP_PROXY = process.env.NODE_HTTP_PROXY;
  9. if (NODE_HTTP_PROXY) {
  10. axios.defaults.proxy = false;
  11. axios.defaults.httpsAgent = new HttpsProxyAgent(NODE_HTTP_PROXY);
  12. }
  13. const getRequiredEnv = (key) => {
  14. const value = process.env[key];
  15. if (!value) {
  16. throw new Error(`${key} is required`);
  17. }
  18. return value;
  19. }
  20. const normalizePrivateKey = (privateKey) => {
  21. return privateKey.startsWith("0x") ? privateKey : `0x${privateKey}`;
  22. }
  23. const HOST = "https://clob.polymarket.com";
  24. const account = privateKeyToAccount(normalizePrivateKey(getRequiredEnv("POLYMARKET_PRIVATE_KEY")));
  25. const signer = createWalletClient({ account, chain: polygon, transport: http() });
  26. const client = new ClobClient({
  27. host: HOST,
  28. chain: Chain.POLYGON,
  29. signer,
  30. throwOnError: true,
  31. });
  32. const nonce = process.env.POLYMARKET_API_KEY_NONCE
  33. ? Number(process.env.POLYMARKET_API_KEY_NONCE)
  34. : undefined;
  35. if (nonce !== undefined && !Number.isInteger(nonce)) {
  36. throw new Error(`POLYMARKET_API_KEY_NONCE is invalid: ${process.env.POLYMARKET_API_KEY_NONCE}`);
  37. }
  38. const apiKey = await client.createApiKey(nonce).catch(error => {
  39. if (error?.status === 400) {
  40. return client.deriveApiKey(nonce);
  41. }
  42. throw error;
  43. });
  44. if (!apiKey?.key || !apiKey?.secret || !apiKey?.passphrase) {
  45. throw new Error(`failed to create or derive api key: ${JSON.stringify(apiKey)}`);
  46. }
  47. console.log(JSON.stringify(apiKey, null, 2));