← Back
/** Wrap an arbitrary ERC-20 collateral sitting on the deposit wallet → pUSD (re-tradable).
 *  Generalizes redeem-dw.mjs step 2 to any asset (e.g. native USDC topped up by the user).
 *  Gasless via the Polymarket relayer deposit-wallet batch (DW needs no MATIC).
 *  Run on the main/DE server (relayer not geoblocked; builder-sign at localhost:3240).
 *
 *  Usage: [DRY=1] [WRAP_ASSET=0x...] node --experimental-global-webcrypto wrap-asset.mjs */
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, createPublicClient, http, encodeFunctionData, erc20Abi, maxUint256 } from 'viem';
import { toAccount } from 'viem/accounts';
import { polygon } from 'viem/chains';

const { RelayClient, RelayerTransactionState } = pkg;
const { BuilderConfig } = signingPkg;
const DW = process.env.DEPOSIT_WALLET || '0x50A8061e9448EB1e5d5e7aF07BE4E4F63C6F24Ff';
const DRY = process.env.DRY === '1';
const ASSET = (process.env.WRAP_ASSET || '0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359'); // default = native USDC
const PUSD = '0xC011a7E12a19f7B1f670d46F03B03f3342E82DFB';
const ONRAMP = '0x93070a847efEf7F70739046A929D47a521F5B8ee';
const WRAP_ABI = [{ name: 'wrap', type: 'function', stateMutability: 'nonpayable', inputs: [{ name: 'asset', type: 'address' }, { name: 'to', type: 'address' }, { name: 'amount', type: 'uint256' }], outputs: [] }];

const pub = createPublicClient({ chain: polygon, transport: http('https://polygon.drpc.org') });
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);

let relay = null;
async function getRelay() {
  if (relay) return relay;
  const env = {};
  const envUrl = fs.existsSync(new URL('../.env.privy', import.meta.url)) ? new URL('../.env.privy', import.meta.url) : new URL('./.env.privy', import.meta.url);
  for (const l of fs.readFileSync(envUrl, '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();
  // Multi-tenant EOA selection: require USER_EOA when >1 Privy user exists (the old
  // "last wins" loop could sign with the wrong user's key); auto-pick only when one exists.
  const wallets = [];
  for (const u of users) for (const a of u.linkedAccounts || []) if (a.type === 'wallet' && a.walletClientType === 'privy') wallets.push(a.address);
  const want = (process.env.USER_EOA || '').toLowerCase();
  const EOA = want ? (wallets.find((w) => w.toLowerCase() === want) || null)
    : (wallets.length === 1 ? wallets[0] : null);
  if (!EOA) throw new Error(want ? `USER_EOA ${process.env.USER_EOA} not among Privy embedded wallets` : `set USER_EOA — ${wallets.length} Privy embedded wallets exist, ambiguous`);
  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' } });
  relay = new RelayClient('https://relayer-v2.polymarket.com/', 137, walletClient, builderConfig);
  return relay;
}
async function submit(calls, tag) {
  const r = await getRelay();
  const deadline = (Math.floor(Date.now() / 1000) + 3600).toString();
  const resp = await r.executeDepositWalletBatch(calls, DW, deadline);
  console.log(`[${tag}] relayer tx:`, resp.transactionID, '| state:', resp.state);
  const result = await r.pollUntilState(resp.transactionID, [RelayerTransactionState.STATE_CONFIRMED, RelayerTransactionState.STATE_FAILED], '90', 3000);
  const ok = result?.state === RelayerTransactionState.STATE_CONFIRMED;
  console.log(ok ? `🎯 [${tag}] CONFIRMED` : `⚠️ [${tag}] not confirmed: ${JSON.stringify(result).slice(0, 200)}`);
  return ok;
}

const bal = await pub.readContract({ address: ASSET, abi: erc20Abi, functionName: 'balanceOf', args: [DW] });
const human = Number(bal) / 1e6;
const pusd0 = Number(await pub.readContract({ address: PUSD, abi: erc20Abi, functionName: 'balanceOf', args: [DW] })) / 1e6;
console.log(`asset ${ASSET} on DW: $${human.toFixed(6)} | pUSD before: $${pusd0.toFixed(4)}`);
if (bal <= 10000n) { console.log('nothing to wrap (<$0.01)'); process.exit(0); }
const calls = [];
const allowance = await pub.readContract({ address: ASSET, abi: erc20Abi, functionName: 'allowance', args: [DW, ONRAMP] });
if (allowance < bal) calls.push({ target: ASSET, value: '0', data: encodeFunctionData({ abi: erc20Abi, functionName: 'approve', args: [ONRAMP, maxUint256] }) });
calls.push({ target: ONRAMP, value: '0', data: encodeFunctionData({ abi: WRAP_ABI, functionName: 'wrap', args: [ASSET, DW, bal] }) });
if (DRY) { console.log(`DRY — would wrap $${human.toFixed(4)} → pUSD (${calls.length} call(s); allowance ${allowance < bal ? 'approve+' : ''}wrap)`); process.exit(0); }
const ok = await submit(calls, 'wrap');
if (ok) {
  const pusd1 = Number(await pub.readContract({ address: PUSD, abi: erc20Abi, functionName: 'balanceOf', args: [DW] })) / 1e6;
  console.log(`pUSD after: $${pusd1.toFixed(4)} (+$${(pusd1 - pusd0).toFixed(4)})`);
}