/** M3-pivot: deploy the user's Polymarket DEPOSIT WALLET (ERC-1967 proxy) via the
* relayer, signed server-side by the user's Privy wallet (server-auth adapter).
* Replaces the wrong Safe flow. Gasless. Poll until STATE_CONFIRMED. */
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 } 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;
console.log('EOA owner:', EOA);
// viem WalletClient with a custom account backed by Privy server-auth
const account = toAccount({
address: EOA,
async signMessage({ message }) {
const m = typeof message === 'string' ? message : (message.raw ?? message);
const { signature } = await privy.walletApi.ethereum.signMessage({ address: EOA, chainType: 'ethereum', message: m });
return signature;
},
async signTypedData(typedData) {
const { signature } = await privy.walletApi.ethereum.signTypedData({ address: EOA, chainType: 'ethereum', typedData });
return signature;
},
async signTransaction() { throw new Error('signTransaction not supported (relayer flow)'); },
});
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 expected = await relay.deriveDepositWalletAddress();
console.log('expected deposit wallet:', expected);
console.log('deploying deposit wallet via relayerβ¦');
const resp = await relay.deployDepositWallet();
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('final:', JSON.stringify(result).slice(0, 200));
console.log(result?.state === RelayerTransactionState.STATE_CONFIRMED ? 'π― deposit wallet DEPLOYED + CONFIRMED' : 'β οΈ not confirmed (see above)');