← Back
/** M2b-2: verify the SERVER can sign on behalf of a delegated user wallet,
 *  using the Privy authorization key (session signer). This proves the full
 *  delegation chain works → server can sign copy orders without the user. */
import fs from 'node:fs';
import { PrivyClient } from '@privy-io/server-auth';

const env = {};
for (const line of fs.readFileSync(new URL('../.env.privy', import.meta.url), 'utf8').split('\n')) {
  const t = line.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 },
});

// find a user's embedded wallet that has delegated/signers
const users = await privy.getUsers();
let target = null;
for (const u of users) {
  for (const a of u.linkedAccounts || []) {
    if (a.type === 'wallet' && a.walletClientType === 'privy') {
      target = { address: a.address, delegated: a.delegated, email: u.email?.address };
    }
  }
}
if (!target) { console.log('⚠️ no embedded wallet found'); process.exit(1); }
console.log('user wallet:', target.address, '| email:', target.email, '| delegated:', target.delegated);

try {
  const { signature } = await privy.walletApi.ethereum.signMessage({
    address: target.address,
    chainType: 'ethereum',
    message: 'SZHub copy-trade test — server-signed on your behalf',
  });
  console.log('🎯 SERVER SIGNED on behalf of user! signature:', signature.slice(0, 24) + '…', '(len', signature.length, ')');
  console.log('→ Delegation chain WORKS: server can sign copy orders without the user.');
} catch (e) {
  console.log('⚠️ sign failed:', e?.message || e);
  process.exit(1);
}