import { FixedPointNumber as FN } from '@acala-network/sdk-core' ; export class MayFailedCausedByFee extends Error { constructor ( ) { super ( ) ; this . message = 'the native token balance is less than fee, the transaction may failed.' ; this . name = 'MayFailedCausedByFee' ; } } interface Config { isNativeToken : boolean ; isAllowDeath : boolean ; providers : number ; consumers : number ; nativeFreeBalance : FN ; nativeLockedBalance : FN ; targetFreeBalance : FN ; targetLockedBalance : FN ; ed : FN ; fee : FN ; } const ZERO = FN . ZERO ; export const getMaxAvailableBalance = ( config ) : FN => { const { isNativeToken , isAllowDeath , providers , consumers , nativeFreeBalance , nativeLockedBalance , targetFreeBalance , targetLockedBalance , ed , fee } = config ; if ( isNativeToken ) { const availableBalance = nativeFreeBalance . sub ( nativeLockedBalance ) . max ( ZERO ) ; if ( nativeLockedBalance . lte ( ZERO ) ) { if ( isAllowDeath && ( providers > 0 || consumers === 0 ) ) { return nativeFreeBalance . sub ( fee ) . max ( ZERO ) ; } else { return nativeFreeBalance . sub ( ed ) . sub ( fee ) . max ( ZERO ) ; } } if ( nativeLockedBalance . lt ( ed ) && nativeLockedBalance . gt ( ZERO ) ) return availableBalance . sub ( ed . sub ( nativeLockedBalance ) ) . sub ( fee ) . max ( ZERO ) ; if ( nativeLockedBalance . gte ( ed ) ) return availableBalance . sub ( fee ) . max ( ZERO ) ; } const targetAvailableBalance = targetFreeBalance . sub ( targetLockedBalance ) . max ( ZERO ) ; if ( nativeFreeBalance . add ( nativeLockedBalance ) . gt ( fee ) ) { if ( targetLockedBalance . lte ( ZERO ) ) { if ( isAllowDeath && ( providers > 0 || consumers === 0 ) ) { return targetFreeBalance ; } else { return targetFreeBalance . sub ( ed ) . max ( ZERO ) ; } } if ( targetLockedBalance . lt ( ed ) && targetLockedBalance . gt ( ZERO ) ) return targetAvailableBalance . sub ( ed . sub ( targetLockedBalance ) ) . max ( ZERO ) ; if ( targetLockedBalance . gte ( ed ) ) return targetAvailableBalance . sub ( targetLockedBalance ) . max ( ZERO ) ; } throw new MayFailedCausedByFee ( ) ; } ;