import { EtherspotBundler, ModularSdk, SessionKeyValidator, sleep } from '@etherspot/modular-sdk';
import * as dotenv from 'dotenv';
dotenv.config();

async function main() {
  const bundlerApiKey = process.env.API_KEY as string;
  const walletPrivateKey = process.env.WALLET_PRIVATE_KEY as string;
  const chainId = Number(process.env.CHAIN_ID);

  // initializating sdk...
  const modularSdk = new ModularSdk({ privateKey: privateKey },
    {
      chainId: chainId,
      bundlerProvider: new EtherspotBundler(chainId, bundlerApiKey)
    })

  console.log('address: ', modularSdk.state.EOAAddress);

  // get address of EtherspotWallet
  const address: string = await modularSdk.getCounterFactualAddress();

  console.log('\x1b[33m%s\x1b[0m', `EtherspotWallet address: ${address}`);

  // get instance  of SessionKeyValidator
  const sessionKeyModule = await SessionKeyValidator.create(
    modularSdk,
    new EtherspotBundler(chainId, bundlerApiKey)
  )
  const sessionKey = '0xb1D8541544f240C80d5c4489990bfADAa238b0b3'; // session key which you want to disable

  const response = await sessionKeyModule.disableSessionKey(sessionKey);

  console.log('\x1b[33m%s\x1b[0m', `UserOpHash: `, response.userOpHash);
  console.log('\x1b[33m%s\x1b[0m', `SessionKey: `, response.sessionKey);

  // get transaction hash...
  console.log('Waiting for transaction...');
  let userOpsReceipt = null;
  const timeout = Date.now() + 60000; // 1 minute timeout
  while ((userOpsReceipt == null) && (Date.now() < timeout)) {
    await sleep(2);
    userOpsReceipt = await modularSdk.getUserOpReceipt(response.userOpHash);
  }
  console.log('\x1b[33m%s\x1b[0m', `Transaction Receipt: `, userOpsReceipt);

  const sessionKeys = await sessionKeyModule.getAssociatedSessionKeys();
  console.log('\x1b[33m%s\x1b[0m', `AssociatedSessionKeys: `, sessionKeys);
}