query method

  1. @override
Future<QueryResponse> query(
  1. Principal canisterId,
  2. QueryFields options,
  3. Identity? identity
)
override

Send a query call to a canister. See {@link https://sdk.dfinity.org/docs/interface-spec/#http-query | the interface spec}. @param canisterId The Principal of the Canister to send the query to. Sending a query to the management canister is not supported (as it has no meaning from an agent). @param options Options to use to create and send the query. @returns The response from the replica. The Promise will only reject when the communication failed. If the query itself failed but no protocol errors happened, the response will be of type QueryResponseRejected.

Implementation

@override
Future<QueryResponse> query(
    Principal canisterId, QueryFields options, Identity? identity) async {
  final canister = canisterId is String
      ? Principal.fromText(canisterId as String)
      : canisterId;
  final id = (identity ?? await _identity);
  final sender = id?.getPrincipal() ?? Principal.anonymous();

  var requestBody = QueryRequest()
    ..request_type = ReadRequestType.TypeQuery
    ..canister_id = canister
    ..method_name = options.methodName
    ..arg = options.arg!
    ..sender = sender
    ..ingress_expiry = Expiry(DEFAULT_INGRESS_EXPIRY_DELTA_IN_MSECS);

  var rsRequest = HttpAgentQueryRequest()
    ..endpoint = Endpoint.Query
    ..body = requestBody
    ..request = {
      "method": "POST",
      "headers": {
        'Content-Type': 'application/cbor',
        ..._baseHeaders,
      },
    };

  var transformedRequest = await _transform(rsRequest);
  Map<String, dynamic> newTransformed =
      await id!.transformRequest(transformedRequest);

  var body = cbor.cborEncode(newTransformed["body"]);

  final response = await _fetch!(
      endpoint: "/api/v2/canister/${canister.toText()}/query",
      method: FetchMethod.post,
      headers: newTransformed["request"]["headers"],
      body: body);

  if (!(response["ok"] as bool)) {
    // ignore: prefer_adjacent_string_concatenation
    throw 'Server returned an error:\n' +
        '  Code: ${response["statusCode"]} (${response["statusText"]})\n' +
        '  Body: ${response["body"]}\n';
  }

  final buffer = response["arrayBuffer"] as Uint8List;

  return QueryResponseWithStatus.fromMap(cbor.cborDecode<Map>(buffer));
}