populateAuthPayload static method

SessionAuthPayload populateAuthPayload({
  1. required SessionAuthPayload authPayload,
  2. required List<String> chains,
  3. required List<String> methods,
})

Implementation

static SessionAuthPayload populateAuthPayload({
  required SessionAuthPayload authPayload,
  required List<String> chains,
  required List<String> methods,
}) {
  final statement = authPayload.statement ?? '';

  if (chains.isEmpty) return authPayload;

  final requested = authPayload.chains;
  final supported = chains;

  final approvedChains =
      supported.where((value) => requested.contains(value)).toList();
  if (approvedChains.isEmpty) {
    throw ReownSignError(code: -1, message: 'No supported chains');
  }

  final requestedRecaps = ReCapsUtils.getDecodedRecapFromResources(
    resources: authPayload.resources,
  );
  if (requestedRecaps == null) return authPayload;

  ReCapsUtils.isValidRecap(requestedRecaps);

  final resource = ReCapsUtils.getRecapResource(
    recap: requestedRecaps,
    resource: 'eip155',
  );
  List<String> updatedResources = authPayload.resources ?? [];

  if (resource.isNotEmpty) {
    final actions = ReCapsUtils.getReCapActions(abilities: resource);
    final approvedActions =
        actions.where((value) => methods.contains(value)).toList();
    if (approvedActions.isEmpty) {
      throw ReownSignError(
        code: -1,
        message: 'Supported methods don\'t satisfy the requested: $actions, '
            'supported: $methods',
      );
    }
    final formattedActions = ReCapsUtils.assignAbilityToActions(
      'request',
      approvedActions,
      limits: {'chains': approvedChains},
    );
    final updatedRecap = ReCapsUtils.addResourceToRecap(
      recap: requestedRecaps,
      resource: 'eip155',
      actions: formattedActions,
    );
    // remove recap from resources as we will add the updated one
    updatedResources = List<String>.from((authPayload.resources ?? []))
      ..removeLast();
    updatedResources.add(ReCapsUtils.encodeRecap(updatedRecap));
  }
  //
  return SessionAuthPayload.fromJson(authPayload.toJson()).copyWith(
    statement: ReCapsUtils.buildRecapStatement(
      statement,
      ReCapsUtils.getRecapFromResources(resources: updatedResources),
    ),
    chains: approvedChains,
    resources: updatedResources.isNotEmpty ? updatedResources : null,
  );
}