import { xrpIO } from "xrpio";

type Wallet = {
    address: string,
    secret: string
}

type DatawriterConfig = {
    receiveAddress: string
    sendWallet: Wallet
    xrpNode: string
    contractAddress: string
}

export class Datawriter {

    constructor(private config: DatawriterConfig) {
    }


    async callEndpoint(endpointName: string, parameter: any, fee?: number) {
        const xrpio: xrpIO = new xrpIO(this.config.xrpNode)
        await xrpio.connect()
        try{
            const dataHash = await xrpio.treeWrite(
                JSON.stringify(parameter),
                this.config.receiveAddress,
                this.config.sendWallet.secret
            )
            const hash = await xrpio.writeRaw(
                {
                    data: JSON.stringify({
                        endpoint: endpointName,
                        data: dataHash
                    })
                },
                this.config.contractAddress,
                this.config.sendWallet.secret,
                undefined,
                fee ? String(fee) : undefined
            )
        }catch(e){
            console.log(e)
        }finally{
            await xrpio.disconnect()
        }
    }
}