fromJsonRpcError static method

PosApiError fromJsonRpcError(
  1. JsonRpcError error
)

Implementation

static PosApiError fromJsonRpcError(JsonRpcError error) {
  final errorParts = splitComplex(error.message ?? '');
  final extraTypes = [
    'unableToParseAmountWith6Decimals',
    'invalidTokenMintAddress',
    'invalidMintAccountOwner',
  ];
  final errorTypes = [
    ...PosApiError.values.map((e) => e.name),
    ...extraTypes,
  ];

  PosApiError? checkFailedToEstimateGasReason(PosApiError? posApiError) {
    if (posApiError == PosApiError.failedToEstimateGas) {
      final insufficientFunds = PosApiError.insufficientFundsForTransfer;
      if (errorParts.contains(insufficientFunds.name)) {
        return insufficientFunds;
      }
      final exceedsBalance = PosApiError.transferAmountExceedsBalance;
      if (errorParts.contains(exceedsBalance.name)) {
        return exceedsBalance;
      }
    }
    return null;
  }

  // Fist try to parse the error from its code
  PosApiError? apiErrorFromCode = _fromErrorCode(error.code);
  if (apiErrorFromCode != null) {
    if (apiErrorFromCode == PosApiError.failedToEstimateGas) {
      return checkFailedToEstimateGasReason(apiErrorFromCode) ??
          apiErrorFromCode;
    }
    // rpcError and internal will be identified by message value
    if (apiErrorFromCode != PosApiError.rpcError &&
        apiErrorFromCode != PosApiError.internal) {
      return apiErrorFromCode;
    }
  }

  String? mergeTypes(String part) {
    if (extraTypes.contains(part)) {
      // invalidTokenMintAddress and invalidMintAccountOwner are merged with invalidAsset
      if (part == 'invalidTokenMintAddress' ||
          part == 'invalidMintAccountOwner') {
        return 'invalidAsset';
      }
      // unableToParseAmountWith6Decimals is merged with invalidAmount
      return 'invalidAmount';
    }
    return null;
  }

  // if _fromErrorCode gives null error then parse the message value
  for (var part in errorParts) {
    if (errorTypes.contains(part)) {
      part = mergeTypes(part) ?? part;
      PosApiError? posApiError = PosApiError._fromName(part);
      posApiError =
          checkFailedToEstimateGasReason(posApiError) ?? posApiError;
      return posApiError ?? PosApiError.unknown;
    }
  }

  // if everything fails return unknown
  return PosApiError.unknown;
}