Skip to content

AI Data Tasks

Show your users short AI data tasks inside your app, such as picking the better of two answers. The SDK carries the task screens as one HTML page, contributionPageHtml. Your app shows it in a web view and answers four calls from it. The page fetches a task from the project the user picked, shows the consent screen and the task, and sends the answer with a proof that the SDK signs. Your app never sees the task, the answer, the score or the proof.

When to use it

  • Your app rewards its users for completing tasks, for example from an "Earn rewards" button
  • DEA has projects open for your app

Prerequisites

  • The SDK is installed and initialized with your appId and appKey. See the Quick Start and Accounts and keys.
  • attest() answered Verdict.passed. DEA refuses a task request signed by a key it has not registered.
  • An app user id for each user. It is required: the project list and every task carry it as publisherUserId. See App user ids.
  • The webview_flutter and http packages in your app's pubspec.yaml. The samples use them.

How a task runs

Step Your app The page
1 Lists the projects open to the user, and shows them in its own screen
2 Opens a screen with a web view, and loads the page for the picked project Asks for its boot values
3 Delivers the boot values Fetches a task, and shows the consent screen when DEA asks for it, then the task
4 Answers the page's calls: ready, attest, signRequest, signContribution Sends the answer to DEA
5 Closes the screen when the outcome arrives Posts one outcome

Usage

1. List the projects

The page runs a task on one project, which the user picks first. The project list is not part of the page: your app requests it from DEA and shows it.

Item Value
Request POST, to ContributionHosts.apiBase followed by /api/tasks/projects
Headers Content-Type: application/json, Accept: application/json, and X-App-Key with the SDK's appKey
Body {"h_proof": "<signed request>"}, signed by signRequest(eventType: 'projects', claims: ...)
Claims to sign publisher_user_id: your app user id. platform: android or ios. sdk_version: packageVersion
Answer 200 {"projects": [...]}. Each project has project_id, name, pattern_id (the task type) and pattern_name. Show them in this order
Answer 204 No project is open to this user
Another answer Refused. The body's errorCode says why
import 'dart:convert';
import 'dart:io' show Platform;

import 'package:dea_sdk/dea_sdk.dart';
import 'package:http/http.dart' as http;

/// The projects open to this user.
Future<List<Map<String, Object?>>> listProjects(String userId) async {
  final dea = DeaSdk.instance;
  if (dea == null) throw StateError('the SDK is not initialized');
  final proof = await dea.signRequest(
    eventType: 'projects',
    claims: {
      'publisher_user_id': userId,
      'platform': Platform.isIOS ? 'ios' : 'android',
      'sdk_version': packageVersion,
    },
  );
  if (proof == null) throw StateError('not signed: ${dea.lastRequestRefusal}');

  final appKey = dea.appKey;
  final answer = await http
      .post(
        Uri.parse('${ContributionHosts.apiBase}/api/tasks/projects'),
        headers: {
          'Content-Type': 'application/json',
          'Accept': 'application/json',
          if (appKey != null) 'X-App-Key': appKey,
        },
        body: jsonEncode({'h_proof': proof}),
      )
      .timeout(const Duration(seconds: 15));
  if (answer.statusCode == 204) return []; // no project is open to this user
  if (answer.statusCode != 200) {
    throw StateError('refused ${answer.statusCode}: ${answer.body}');
  }
  final projects = (jsonDecode(answer.body) as Map<String, Object?>)['projects'] as List? ?? [];
  return [for (final project in projects) Map<String, Object?>.from(project as Map)];
}

2. Load the page

Load contributionPageHtml into the web view as a string, with ContributionHosts.apiBase as its base URL:

controller.loadHtmlString(contributionPageHtml, baseUrl: ContributionHosts.apiBase);

The base URL is required. The page hashes the task and the answer with Web Crypto, which works only in a secure context, and it sends its requests to its own origin. With no base URL, or another one, the page stops with PAGE_INSECURE, or DEA refuses its requests.

ContributionHosts holds the hosts this build of the SDK talks to. Your app passes them to the page in the boot message:

Constant Boot value What it is
ContributionHosts.apiBase apiBase DEA's API origin, and the page's base URL
ContributionHosts.widgetOrigin widgetOrigin The origin the task's widget is downloaded from
ContributionHosts.mediaOrigin mediaOrigin The origin of the task's images

3. Install the bridge

The page and your app talk through two functions. Each takes one JSON object, as a string.

Function Direction Who defines it
window.deaHost.post(json) Page to app Your app, before the page's own script runs
window.deaPage.deliver(json) App to page The page. Your app calls it with runJavaScript

With webview_flutter:

  1. Add a JavaScript channel to the controller with addJavaScriptChannel, before you load the page.
  2. Insert a <script> that defines window.deaHost before the page's </head>. It posts to the channel with a random key in front of each message. Drop every message without that key: the channel is visible to every frame of the page, and only the page's own script has the key.
  3. Let the web view navigate only to about:, data: and ContributionHosts.apiBase.

4. Answer the page

Message Direction What your app does
{"t": "ready"} Page to app Deliver the boot message. The page sends ready every 100 ms until the boot message arrives
{"t": "boot", ...} App to page Starts the first task. See the boot values below
{"t": "call", "id", "method", "args"} Page to app Deliver {"t": "result", "id", "value"} with the answer below, or {"t": "error", "id", "message"}. Answer each call within 30 seconds
{"t": "event", "event"} Page to app A step of the task. Nothing to answer
{"t": "outcome", "outcome", "errorCode"} Page to app The task ended. See How a task ends
{"t": "start", "projectId"} App to page Runs another task on the page, for example after submitted
{"t": "close"} App to page Ends the task on screen. The page posts closed

The boot values:

Field Value
appKey The SDK's appKey
publisherUserId Your app user id
projectId The project_id of the project the user picked
apiBase ContributionHosts.apiBase
widgetOrigin ContributionHosts.widgetOrigin
mediaOrigin ContributionHosts.mediaOrigin
sdkVersion packageVersion

The four calls:

method args value to answer
ready None null, once the SDK is initialized
attest None {"verdict": "passed"}: the name of attest()'s verdict
signRequest The claims to sign, with event_type The string that signRequest(eventType: event_type, claims: ...) returns, or null
signContribution item_id and artifact_hash {"tuple": {"h_proof": "<proof>"}}, from signRequest(eventType: 'contribution', claims: ..., scored: true)

Sign the claims as the page sends them, without event_type, which goes in eventType. When the claims carry platform and sdk_version, set them to android or ios, and packageVersion. Add no claim: DEA refuses a request with a claim the route does not take.

When signRequest returns null for signContribution, answer {"reason": "<lastRequestRefusal>", "outcome": "refused"}. When lastRequestRefusal contains -33, the session is not sufficient yet: add "code": -33. The page then asks the user to take a moment with the task and shows it again.

5. Run another task, or close

The page posts one outcome for each task. After submitted, deliver {"t": "start", "projectId": "<the same project>"} to show another task on the same page. Use the same project for every task until the user leaves the screen. After no_task, the project has nothing left for this user: show the project list again.

Example

A task screen

This widget loads the page, answers it and reports the outcome. Create it with the user's app user id and the project_id the user picked:

import 'dart:convert';
import 'dart:io' show Platform;
import 'dart:math';

import 'package:dea_sdk/dea_sdk.dart';
import 'package:flutter/material.dart';
import 'package:webview_flutter/webview_flutter.dart';

/// One AI data task.
class TaskScreen extends StatefulWidget {
  const TaskScreen({
    super.key,
    required this.userId,
    required this.projectId,
    required this.onOutcome,
  });

  final String userId;
  final String projectId;

  /// Called once, with the outcome and its errorCode.
  final void Function(String outcome, String? errorCode) onOutcome;

  @override
  State<TaskScreen> createState() => _TaskScreenState();
}

class _TaskScreenState extends State<TaskScreen> {
  /// Only the page's own script has it.
  final String _key = '${Random.secure().nextInt(1 << 32)}${Random.secure().nextInt(1 << 32)}|';
  late final WebViewController _web;
  bool _ended = false;

  @override
  void initState() {
    super.initState();
    final bridge = '<script>window.deaHost = { post: function (m) { '
        'DeaHostChannel.postMessage(${jsonEncode(_key)} + m); } };</script>';
    _web = WebViewController()
      ..setJavaScriptMode(JavaScriptMode.unrestricted)
      ..addJavaScriptChannel('DeaHostChannel', onMessageReceived: (message) => _received(message.message))
      ..setNavigationDelegate(NavigationDelegate(onNavigationRequest: _pageOnly))
      // The page, with the bridge ahead of its own script and the API origin as its base URL.
      ..loadHtmlString(
        contributionPageHtml.replaceFirst('</head>', '$bridge</head>'),
        baseUrl: ContributionHosts.apiBase,
      );
  }

  /// Page to app.
  void _received(String raw) {
    if (!raw.startsWith(_key)) return; // not the page
    final Object? message = jsonDecode(raw.substring(_key.length));
    if (message is! Map<String, Object?>) return;
    switch (message['t']) {
      case 'ready':
        _deliver(_boot());
      case 'call':
        _answer(message['id']! as int, message['method']! as String, message['args']);
      case 'outcome':
        if (_ended) return;
        _ended = true;
        widget.onOutcome(message['outcome']! as String, message['errorCode'] as String?);
    }
  }

  Map<String, Object?> _boot() => {
        't': 'boot',
        'appKey': DeaSdk.instance?.appKey,
        'publisherUserId': widget.userId,
        'projectId': widget.projectId,
        'apiBase': ContributionHosts.apiBase,
        'widgetOrigin': ContributionHosts.widgetOrigin,
        'mediaOrigin': ContributionHosts.mediaOrigin,
        'sdkVersion': packageVersion,
      };

  /// The four calls.
  Future<void> _answer(int id, String method, Object? args) async {
    final dea = DeaSdk.instance;
    if (dea == null) {
      _deliver({'t': 'error', 'id': id, 'message': 'the SDK is not initialized'});
      return;
    }
    final fields = args is Map<String, Object?> ? args : const <String, Object?>{};
    final Object? value;
    switch (method) {
      case 'ready':
        value = null;
      case 'attest':
        value = {'verdict': (await dea.attest()).verdict.name};
      case 'signRequest':
        value = await _sign(dea, fields['event_type'] as String? ?? '', fields, scored: false);
      case 'signContribution':
        final proof = await _sign(dea, 'contribution', fields, scored: true);
        if (proof != null) {
          value = {
            'tuple': {'h_proof': proof},
          };
        } else {
          final why = dea.lastRequestRefusal ?? 'nothing signed';
          value = {
            'reason': why,
            'outcome': 'refused',
            if (why.contains('-33')) 'code': -33, // not sufficient yet
          };
        }
      default:
        _deliver({'t': 'error', 'id': id, 'message': 'no method $method'});
        return;
    }
    _deliver({'t': 'result', 'id': id, 'value': value});
  }

  /// Signs the claims the page sent, as sent. Only platform and sdk_version are the app's to set.
  Future<String?> _sign(DeaSdk dea, String eventType, Map<String, Object?> fields, {required bool scored}) {
    final claims = Map<String, Object?>.of(fields)..remove('event_type');
    if (claims.containsKey('platform')) claims['platform'] = Platform.isIOS ? 'ios' : 'android';
    if (claims.containsKey('sdk_version')) claims['sdk_version'] = packageVersion;
    return dea.signRequest(eventType: eventType, claims: claims, scored: scored);
  }

  /// App to page: one JSON object, as a string.
  void _deliver(Map<String, Object?> message) {
    _web.runJavaScript('window.deaPage && window.deaPage.deliver(${jsonEncode(jsonEncode(message))});');
  }

  /// The page and the task's frame only: nothing navigates away.
  NavigationDecision _pageOnly(NavigationRequest request) {
    final url = Uri.parse(request.url);
    final local = url.scheme == 'about' || url.scheme == 'data';
    final page = url.scheme == 'https' && url.origin == ContributionHosts.apiBase;
    return local || page ? NavigationDecision.navigate : NavigationDecision.prevent;
  }

  @override
  Widget build(BuildContext context) => Scaffold(body: SafeArea(child: WebViewWidget(controller: _web)));
}

List the projects, show them, and open the screen with the one the user picks:

Navigator.of(context).push(MaterialPageRoute<void>(
  builder: (_) => TaskScreen(
    userId: userId,
    projectId: picked['project_id']! as String,
    onOutcome: (outcome, errorCode) {
      Navigator.of(context).pop();
      if (outcome == 'no_task') showProjects(); // the project has nothing left: list them again
    },
  ),
));

showProjects stands for your own code.

How a task ends

The page posts exactly one outcome for each task. When the task ends on one of the page's own screens (thank you, not sent, task unavailable), the outcome comes after the user taps "Back to the app".

outcome What happened
submitted DEA stored the answer
consent_declined The user tapped "Not now" on the consent screen. Nothing was recorded or sent
no_task The picked project has nothing left for this user. Show the project list again
widget_unavailable The task's widget failed its origin or hash check. Nothing was sent
not_sent The answer could not be sent: retries ran out, DEA refused it, or the session was not sufficient on three tries
not_attested Your app answered attest with a verdict other than passed, the boot message has no appKey, or signRequest answered null. The task did not start
closed Your app delivered close before the task ended
error DEA refused the task or the consent, did not answer, or the page could not start. errorCode names the reason
errorCode Why
PAGE_NO_BOOT No boot message within 30 seconds. Your app hears it only when it receives the page's messages
PAGE_NO_HOSTS The boot message has no apiBase, widgetOrigin or sdkVersion
PAGE_INSECURE The page is not in a secure context: it was loaded without ContributionHosts.apiBase as its base URL
PAGE_ERROR The page failed while it started a task
NETWORK DEA did not answer
Another value DEA's own code, such as IDENTITY_MISMATCH

The event messages come in this order: consent_required, task_shown, not_enough_signal (the same task shows again), sending, and waiting_to_send (no answer from DEA yet, retrying).

Troubleshooting

What you see Why What to do
After 30 seconds the page says "No host bridge is installed", and your app hears nothing window.deaHost is not defined when the page runs, so the page cannot post to your app Insert the bridge script before </head>
After 30 seconds the page says "The app did not start this task", and your app hears nothing Your app drops the page's messages, its outcome included Add the channel before loadHtmlString, and check the channel name and the key
error with PAGE_NO_BOOT Your app hears the page, but does not answer ready with the boot message Deliver the boot message on every ready
error with PAGE_INSECURE The page was loaded with no base URL or another one Load it with loadHtmlString(..., baseUrl: ContributionHosts.apiBase)
not_attested attest() did not answer Verdict.passed, appKey is null, or signRequest returned null (read lastRequestRefusal) See Attest and Accounts and keys
error with CLAIM_PROFILE A signed request carries a claim the route does not take, or an app user id that is empty or longer than 128 characters Sign the claims as the page sends them, and change only platform and sdk_version
error with IDENTITY_MISMATCH This device key is bound to another app user id See App user ids
not_sent soon after the user answers Your app answered signContribution with a refusal without "code": -33, or with that code three times Add "code": -33 when lastRequestRefusal contains -33, so the page shows the task again
The task ends 30 seconds after a call Your app did not answer that call Answer every call with a result or an error message

API

Member Returns Description
contributionPageHtml String The task page
ContributionHosts.apiBase String DEA's API origin: the page's base URL, and the host of the project list
ContributionHosts.widgetOrigin String The origin of the task's widget. Boot value widgetOrigin
ContributionHosts.mediaOrigin String The origin of the task's images. Boot value mediaOrigin
signRequest({eventType, claims, scored, sessionId}) Future<String?> Signs a task request with the device key; null when nothing was signed. scored: true adds the session's score
lastRequestRefusal String? Why the last signRequest returned null
attest() Future<Attestation> Registers the device key. See Attest
appKey String? Boot value appKey, and the X-App-Key header of the project list
packageVersion String Boot value sdkVersion, and the sdk_version claim

All of them come from package:dea_sdk/dea_sdk.dart.