import { IGasConfig } from "./types" ; import { TxChainSetter } from "./chain" ; import { ChainGetter } from "@keplr-wallet/stores" ; import { action , makeObservable , observable } from "mobx" ; import { useState } from "react" ; export class GasConfig extends TxChainSetter implements IGasConfig { @ observable protected _gasRaw : string | undefined = undefined ; constructor ( chainGetter , initialChainId , initialGas ? ) { super ( chainGetter , initialChainId ) ; this . _gasRaw = initialGas ?. toString ( ) ; makeObservable ( this ) ; } get gasRaw ( ) : string { if ( this . _gasRaw == null ) { return this . gas . toString ( ) ; } return this . _gasRaw ; } get gas ( ) : number { if ( this . _gasRaw == null ) { return 0 ; } const r = parseInt ( this . _gasRaw ) ; return Number . isNaN ( r ) ? 0 : r ; } @ action setGas ( gas ) { if ( typeof gas === "number" ) { this . _gasRaw = Math . floor ( gas ) . toString ( ) ; return ; } if ( gas === "" ) { this . _gasRaw = gas ; return ; } if ( ! gas . includes ( "." ) ) { if ( ! Number . isNaN ( Number . parseInt ( gas ) ) ) { this . _gasRaw = gas ; return ; } } } getError ( ) { if ( this . _gasRaw === "" ) { return new Error ( "Gas not set" ) ; } if ( this . _gasRaw && Number . isNaN ( this . _gasRaw ) ) { return new Error ( "Gas is not valid number" ) ; } if ( ! Number . isInteger ( this . gas ) ) { return new Error ( "Gas is not integer" ) ; } if ( this . gas <= 0 ) { return new Error ( "Gas should be greater than 0" ) ; } return ; } } export const useGasConfig = ( chainGetter , chainId , initialGas ? ) => { const [ txConfig ] = useState ( ( ) => new GasConfig ( chainGetter , chainId , initialGas ) ) ; txConfig . setChain ( chainId ) ; return txConfig ; } ;