← Back
/** M3-final-b: build a sigType3 (POLY_1271) deposit-wallet order with ERC-7739
 *  wrapping via clob-client-v2, signed server-side. Offline build (tickSize/negRisk
 *  provided). Prints the signed order to validate the wrapping works. */
import fs from 'node:fs';
import { PrivyClient } from '@privy-io/server-auth';
import { createWalletClient, http } from 'viem';
import { toAccount } from 'viem/accounts';
import { polygon } from 'viem/chains';
import { ClobClient, SignatureTypeV2, Side } from '@polymarket/clob-client-v2';

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 DW = '0x50A8061e9448EB1e5d5e7aF07BE4E4F63C6F24Ff';

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 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,
});
console.log('signer addr:', await clob.getSignerAddress?.() ?? EOA, '| funder(dw):', DW);

const TOKEN = '88275040060084773376557187972215267513049848642895776801789297917961077894224';
try {
  const order = await clob.createOrder(
    { tokenID: TOKEN, price: 0.1, size: 10, side: Side.BUY, feeRateBps: 0 },
    { tickSize: '0.01', negRisk: false },
  );
  console.log('🎯 ORDER BUILT + SIGNED (ERC-7739):');
  console.log(JSON.stringify(fix(order), null, 1).slice(0, 600));
} catch (e) {
  console.log('⚠️ createOrder failed:', e?.message || e);
}