import { Dcomm, BN } from "dcomm/dist"
import { DVMAPI, KeyChain as DVMKeyChain } from "dcomm/dist/apis/dvm"
import {
  EVMAPI,
  KeyChain as EVMKeyChain,
  UnsignedTx,
  Tx,
  UTXOSet
} from "dcomm/dist/apis/evm"
import {
  PrivateKeyPrefix,
  DefaultLocalGenesisPrivateKey,
  Defaults,
  costImportTx
} from "dcomm/dist/utils"

const ip: string = "localhost"
const port: number = 9650
const protocol: string = "http"
const networkID: number = 1337
const dcomm: Dcomm = new Dcomm(ip, port, protocol, networkID)
const astchain: DVMAPI = dcomm.ASTChain()
const actchain: EVMAPI = dcomm.ACTChain()
const xKeychain: DVMKeyChain = astchain.keyChain()
const cHexAddress: string = "0x8db97C7cEcE249c2b98bDC0226Cc4C2A57BF52FC"
const privKey: string = `${PrivateKeyPrefix}${DefaultLocalGenesisPrivateKey}`
const cKeychain: EVMKeyChain = actchain.keyChain()
xKeychain.importKey(privKey)
cKeychain.importKey(privKey)
const cAddressStrings: string[] = actchain.keyChain().getAddressStrings()
const astChainBlockchainId: string =
  Defaults.network[networkID].AST.blockchainID

const main = async (): Promise<any> => {
  const baseFeeResponse: string = await actchain.getBaseFee()
  const baseFee = new BN(parseInt(baseFeeResponse, 16) / 1e9)
  let fee: BN = baseFee
  const evmUTXOResponse: any = await actchain.getUTXOs(
    cAddressStrings,
    astChainBlockchainId
  )
  const utxoSet: UTXOSet = evmUTXOResponse.utxos
  let unsignedTx: UnsignedTx = await actchain.buildImportTx(
    utxoSet,
    cHexAddress,
    cAddressStrings,
    astChainBlockchainId,
    cAddressStrings,
    fee
  )
  const importCost: number = costImportTx(unsignedTx)
  fee = baseFee.mul(new BN(importCost))

  unsignedTx = await actchain.buildImportTx(
    utxoSet,
    cHexAddress,
    cAddressStrings,
    astChainBlockchainId,
    cAddressStrings,
    fee
  )

  const tx: Tx = unsignedTx.sign(cKeychain)
  const txid: string = await actchain.issueTx(tx)
  console.log(`Success! TXID: ${txid}`)
}

main()
