| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758 |
- import 'dotenv/config';
- import axios from "axios";
- import { HttpsProxyAgent } from "https-proxy-agent";
- import { Chain, ClobClient } from "@polymarket/clob-client-v2";
- import { createWalletClient, http } from "viem";
- import { privateKeyToAccount } from "viem/accounts";
- import { polygon } from "viem/chains";
- const NODE_HTTP_PROXY = process.env.NODE_HTTP_PROXY;
- if (NODE_HTTP_PROXY) {
- axios.defaults.proxy = false;
- axios.defaults.httpsAgent = new HttpsProxyAgent(NODE_HTTP_PROXY);
- }
- const getRequiredEnv = (key) => {
- const value = process.env[key];
- if (!value) {
- throw new Error(`${key} is required`);
- }
- return value;
- }
- const normalizePrivateKey = (privateKey) => {
- return privateKey.startsWith("0x") ? privateKey : `0x${privateKey}`;
- }
- const HOST = "https://clob.polymarket.com";
- const account = privateKeyToAccount(normalizePrivateKey(getRequiredEnv("POLYMARKET_PRIVATE_KEY")));
- const signer = createWalletClient({ account, chain: polygon, transport: http() });
- const client = new ClobClient({
- host: HOST,
- chain: Chain.POLYGON,
- signer,
- throwOnError: true,
- });
- const nonce = process.env.POLYMARKET_API_KEY_NONCE
- ? Number(process.env.POLYMARKET_API_KEY_NONCE)
- : undefined;
- if (nonce !== undefined && !Number.isInteger(nonce)) {
- throw new Error(`POLYMARKET_API_KEY_NONCE is invalid: ${process.env.POLYMARKET_API_KEY_NONCE}`);
- }
- const apiKey = await client.createApiKey(nonce).catch(error => {
- if (error?.status === 400) {
- return client.deriveApiKey(nonce);
- }
- throw error;
- });
- if (!apiKey?.key || !apiKey?.secret || !apiKey?.passphrase) {
- throw new Error(`failed to create or derive api key: ${JSON.stringify(apiKey)}`);
- }
- console.log(JSON.stringify(apiKey, null, 2));
|