import { BN } from "avalanche" ; import { CONFIG_C , sendAvaC } from "../eth" ; const { CONFIG , avm , bintools } = require ( '../ava' ) ; const Web3 = require ( "web3" ) ; export async function sendDrop ( address , sendAmount ) { let addressChain = getAddressChain ( address ) ; if ( addressChain === 'X' ) { let txId = await sendDropX ( address , sendAmount ) ; return txId ; } else if ( addressChain === 'C' ) { let receipt = await sendAvaC ( address , sendAmount ) ; return receipt . transactionHash ; } else { throw new Error ( "Invalid Address" ) ; } } export async function sendDropX ( addr , sendAmount ) { let myAddresses = [ CONFIG . FAUCET_ADDRESS ] ; let utxos = ( await avm . getUTXOs ( myAddresses ) ) . utxos ; let balance = await avm . getBalance ( CONFIG . FAUCET_ADDRESS , CONFIG . ASSET_ID ) ; let balanceVal = new BN ( balance . balance ) ; if ( sendAmount . gt ( balanceVal ) ) { console . log ( "Insufficient funds. Remaining AVAX: " , balanceVal . toString ( ) ) ; return { status : 'error' , message : 'Insufficient funds to create the transaction. Please file an issues on the repo: https://github.com/ava-labs/faucet-site' } ; } let memo = bintools . stringToBuffer ( "Faucet drip" ) ; let unsigned_tx = await avm . buildBaseTx ( utxos , sendAmount , CONFIG . ASSET_ID , [ addr ] , myAddresses , myAddresses , memo ) . catch ( ( err ) => { console . log ( err ) ; } ) ; if ( unsigned_tx . status ) { return unsigned_tx ; } let signed_tx = avm . signTx ( unsigned_tx ) ; let txid = await avm . issueTx ( signed_tx ) ; console . log ( `(X) Sent a drop with tx id:  ${ txid } to address: ${ addr }` ) ; return txid ; } export type AddressChainType = 'X' | 'C' ; export function getAddressChain ( address ) { if ( address [ 0 ] === 'X' ) { return 'X' ; } else if ( address [ 0 ] === 'C' ) { return 'C' ; } else if ( Web3 . utils . isAddress ( address ) ) { return 'C' ; } throw new Error ( "Not a valid address." ) ; } export function parseEvmBechAddress ( address ) { let ethAddr = address . substring ( 2 ) ; let deserial = bintools . cb58Decode ( ethAddr ) ; let hex = deserial . toString ( 'hex' ) ; return hex ; }