callRequest method

  1. @override
Future<CallResponseBody> callRequest(
  1. Principal canisterId,
  2. CallOptions fields,
  3. Identity? identity
)
override

Implementation

@override
Future<CallResponseBody> callRequest(
  Principal canisterId,
  CallOptions fields,
  Identity? identity,
) async {
  final id = identity ?? _identity;
  final canister = Principal.from(canisterId);
  final ecid = fields.effectiveCanisterId != null
      ? Principal.from(fields.effectiveCanisterId)
      : canister;
  final callSync = fields.callSync;
  final sender = id != null ? id.getPrincipal() : Principal.anonymous();

  final CallRequest submit = CallRequest(
    canisterId: canister,
    methodName: fields.methodName,
    arg: fields.arg,
    sender: sender,
    ingressExpiry: Expiry(_defaultIngressExpiryDeltaInMilliseconds),
  );

  final rsRequest = HttpAgentCallRequest(
    request: {
      'method': 'POST',
      'headers': {
        'Content-Type': 'application/cbor',
        ..._baseHeaders,
      },
    },
    body: submit,
  );
  final transformedRequest = await _transform(rsRequest);
  final newTransformed = await id!.transformRequest(transformedRequest);
  final body = cbor.cborEncode(newTransformed['body']);

  Future<Map<String, dynamic>> callV3() {
    return _fetch!(
      endpoint: '/api/v3/canister/${ecid.toText()}/call',
      method: FetchMethod.post,
      headers: newTransformed['request']['headers'],
      body: body,
    );
  }

  Future<Map<String, dynamic>> callV2() {
    return withRetry(
      () => _fetch!(
        endpoint: '/api/v2/canister/${ecid.toText()}/call',
        method: FetchMethod.post,
        headers: newTransformed['request']['headers'],
        body: body,
      ),
    );
  }

  Map<String, dynamic> response;
  if (callSync) {
    response = await callV3();
    if (response['statusCode'] == 404) {
      response = await callV2();
    }
  } else {
    response = await callV2();
  }
  final requestId = requestIdOf(submit.toJson());

  if (!(response['ok'] as bool)) {
    throw AgentFetchError(
      statusCode: response['statusCode'],
      statusText: response['statusText'],
      body: response['body'],
    );
  }

  return CallResponseBody.fromJson({...response, 'requestId': requestId});
}