/** Enable SELLING from the deposit wallet: setApprovalForAll on the CTF (ERC1155)
* outcome tokens to the CTF Exchange V2 + NegRisk Exchange, via the relayer batch
* (server-signed). Run on the DE server (localhost:3240 builder sign; relayer not
* geoblocked). BUY only needs pUSD approval (approve-dw); SELL needs this. */
import fs from 'node:fs';
import pkg from '@polymarket/builder-relayer-client';
import signingPkg from '@polymarket/builder-signing-sdk';
import { PrivyClient } from '@privy-io/server-auth';
import { createWalletClient, http, encodeFunctionData } from 'viem';
import { toAccount } from 'viem/accounts';
import { polygon } from 'viem/chains';
const { RelayClient, RelayerTransactionState } = pkg;
const { BuilderConfig } = signingPkg;
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 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 builderConfig = new BuilderConfig({ remoteBuilderConfig: { url: 'http://localhost:3240/api/polymarket/sign' } });
const relay = new RelayClient('https://relayer-v2.polymarket.com/', 137, walletClient, builderConfig);
const DW = '0x50A8061e9448EB1e5d5e7aF07BE4E4F63C6F24Ff';
const CTF = '0x4D97DCd97eC945f40cF65F87097ACe5EA0476045';
const EXCH = '0xE111180000d2663C0091e4f400237545B87B996B';
const NEGRISK = '0xC5d563A36AE78145C45a50134d48A1215220f80a';
const setApprovalAbi = [{ name: 'setApprovalForAll', type: 'function', stateMutability: 'nonpayable', inputs: [{ type: 'address' }, { type: 'bool' }], outputs: [] }];
const calls = [EXCH, NEGRISK].map((op) => ({ target: CTF, value: '0', data: encodeFunctionData({ abi: setApprovalAbi, functionName: 'setApprovalForAll', args: [op, true] }) }));
const deadline = (Math.floor(Date.now() / 1000) + 3600).toString();
console.log('approving CTF outcome tokens -> Exchange V2 + NegRisk for DW', DW);
const resp = await relay.executeDepositWalletBatch(calls, DW, deadline);
console.log('relayer tx:', resp.transactionID, '| state:', resp.state);
const result = await relay.pollUntilState(resp.transactionID, [RelayerTransactionState.STATE_CONFIRMED, RelayerTransactionState.STATE_FAILED], '90', 3000);
console.log(result?.state === RelayerTransactionState.STATE_CONFIRMED ? 'CTF approvals CONFIRMED' : 'not confirmed: ' + JSON.stringify(result).slice(0, 160));