← Back
/** Cancel all open CLOB orders for the deposit wallet + show pUSD balance.
 *  Run on Malaysia (CLOB geoblocked elsewhere). Cleanup after a test. */
import fs from 'node:fs';
import { PrivyClient } from '@privy-io/server-auth';
import { createWalletClient, createPublicClient, http, erc20Abi, formatUnits } from 'viem';
import { toAccount } from 'viem/accounts';
import { polygon } from 'viem/chains';
import { ClobClient, SignatureTypeV2 } from '@polymarket/clob-client-v2';

const DW = '0x50A8061e9448EB1e5d5e7aF07BE4E4F63C6F24Ff';
const PUSD = '0xC011a7E12a19f7B1f670d46F03B03f3342E82DFB';
const fix = (v) => typeof v === 'bigint' ? v.toString() : Array.isArray(v) ? v.map(fix) : (v && typeof v === 'object' ? Object.fromEntries(Object.entries(v).map(([k, x]) => [k, fix(x)])) : v);
const env = {};
for (const l of fs.readFileSync(new URL('./.env.privy', import.meta.url), 'utf8').split('\n')) { const t = l.trim(); if (!t || t.startsWith('#')) continue; const i = t.indexOf('='); if (i > 0) env[t.slice(0, i).trim()] = t.slice(i + 1).trim(); }
const privy = new PrivyClient(env.PRIVY_APP_ID, env.PRIVY_APP_SECRET, { walletApi: { authorizationPrivateKey: env.PRIVY_AUTHORIZATION_KEY } });
const users = await privy.getUsers();
let EOA = null;
for (const u of users) for (const a of u.linkedAccounts || []) if (a.type === 'wallet' && a.walletClientType === 'privy') EOA = a.address;
const account = toAccount({
  address: EOA,
  async signMessage({ message }) { const m = typeof message === 'string' ? message : (message.raw ?? message); return (await privy.walletApi.ethereum.signMessage({ address: EOA, chainType: 'ethereum', message: m })).signature; },
  async signTypedData(td) { return (await privy.walletApi.ethereum.signTypedData({ address: EOA, chainType: 'ethereum', typedData: { ...td, message: fix(td.message) } })).signature; },
  async signTransaction() { throw new Error('n/a'); },
});
const walletClient = createWalletClient({ account, chain: polygon, transport: http('https://polygon.drpc.org') });
const clob = new ClobClient({ host: 'https://clob.polymarket.com', chain: 137, signer: walletClient, signatureType: SignatureTypeV2.POLY_1271, funderAddress: DW });
const creds = await clob.createOrDeriveApiKey();
clob.setApiCreds ? clob.setApiCreds(creds) : (clob.creds = creds);

const open = await clob.getOpenOrders();
const orders = Array.isArray(open) ? open : (open?.data || []);
console.log('open orders:', orders.length);
for (const o of orders) console.log(' ', o.id || o.orderID, o.side, o.size || o.original_size, '@', o.price, o.market?.slice?.(0, 12) || '');
if (orders.length) {
  const ids = orders.map((o) => o.id || o.orderID).filter(Boolean);
  try { const r = await clob.cancelOrders(ids); console.log('cancel result:', JSON.stringify(fix(r)).slice(0, 200)); }
  catch (e) { console.log('cancel err:', e?.message || e); }
}
const pub = createPublicClient({ chain: polygon, transport: http('https://polygon.drpc.org') });
console.log('DW pUSD:', formatUnits(await pub.readContract({ address: PUSD, abi: erc20Abi, functionName: 'balanceOf', args: [DW] }), 6));