sendRequest method

Future<Either<String, dynamic>> sendRequest({
  1. required String path,
  2. required RequestType type,
  3. bool keyRequired = false,
  4. bool signatureRequired = false,
  5. bool timestampRequired = false,
  6. Map<String, String>? params,
})

Helper function to perform any kind of request to Binance API

Implementation

Future<Either<String, dynamic>> sendRequest({
  required String path,
  required RequestType type,
  bool keyRequired = false,
  bool signatureRequired = false,
  bool timestampRequired = false,
  Map<String, String>? params,
}) async {
  params ??= {};
  if (timestampRequired)
    params['timestamp'] =
        (DateTime.now().millisecondsSinceEpoch - timestampDifference)
            .toString();

  if (signatureRequired) {
    if (_apiSecret == null) {
      return const Left("Missing API Secret Key");
    }
    var tempUri = Uri.https('', '', params);
    String queryParams = tempUri.toString().substring(7);
    List<int> messageBytes = utf8.encode(queryParams);
    List<int> key = utf8.encode(_apiSecret!);
    Hmac hmac = Hmac(sha256, key);
    Digest digest = hmac.convert(messageBytes);
    String signature = hex.encode(digest.bytes);
    params['signature'] = signature;
  }

  Map<String, String> header = {};
  header[HttpHeaders.contentTypeHeader] = "application/x-www-form-urlencoded";
  if (keyRequired) {
    if (_apiKey == null) {
      return const Left("Missing API Key");
    }
    header["X-MBX-APIKEY"] = _apiKey!;
  }

  final uri = Uri.https(endpoint, path, params);
  http.Response? response;

  switch (type) {
    case RequestType.GET:
      response = await http.get(
        uri,
        headers: keyRequired ? header : null,
      );
      break;
    case RequestType.POST:
      response = await http.post(
        uri,
        headers: header,
      );
      break;
    case RequestType.DELETE:
      response = await http.delete(
        uri,
        headers: header,
      );
      break;
    case RequestType.PUT:
      response = await http.put(uri);
      break;
    default:
  }

  final result = jsonDecode(response!.body);

  if (result is Map) {
    if (result.containsKey("code") && result['code'] != 200) {
      return Left(
          "Binance API returned error ${result["code"]} : ${result["msg"]}");
    }
  }

  return Right(result);
}