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, CONTRIBUTION_PAGE_HTML. Your app shows it in a
WebView 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.
Warning:
@dea/react-nativehas nosignRequestin JavaScript. Two of the page's calls and the project list need it, so your app signs them through a small native module of its own that calls the native SDK. See Sign from native code.
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
appIdandappKey. See the Quick Start and Accounts and keys. The samples use theAPP_KEYand thesdkVersionthat the Ads page keeps in./dea. attest()answered'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. react-native-webviewin your app.- The
DeaSignnative module below, on Android and on iOS.
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 WebView, 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¶
Sign from native code¶
The JavaScript API of @dea/react-native cannot sign a task request. The native SDK under it can:
DeaSdk.instance on Android and DeaReactRuntime.sdk on iOS are the instances that init started.
Add a native module, DeaSign, with one method:
signRequest(eventType: string, claims: object, scored: boolean):
Promise<{proof: string | null; refusal: string | null}>
Android, in your app's Kotlin sources:
import ai.dea.sdk.DeaSdk
import com.facebook.react.ReactPackage
import com.facebook.react.bridge.Arguments
import com.facebook.react.bridge.NativeModule
import com.facebook.react.bridge.Promise
import com.facebook.react.bridge.ReactApplicationContext
import com.facebook.react.bridge.ReactContextBaseJavaModule
import com.facebook.react.bridge.ReactMethod
import com.facebook.react.bridge.ReadableMap
import com.facebook.react.uimanager.ViewManager
import kotlin.concurrent.thread
/** signRequest of the native SDK that @dea/react-native started. */
class DeaSignModule(context: ReactApplicationContext) : ReactContextBaseJavaModule(context) {
override fun getName() = "DeaSign"
@ReactMethod
fun signRequest(eventType: String, claims: ReadableMap, scored: Boolean, promise: Promise) {
thread { // signRequest blocks
val dea = DeaSdk.instance
val proof = dea?.signRequest(eventType = eventType, claims = claims.toHashMap(), scored = scored)
val answer = Arguments.createMap()
answer.putString("proof", proof)
answer.putString("refusal", if (proof != null) null else dea?.lastRequestRefusal ?: "not initialized")
promise.resolve(answer)
}
}
}
class DeaSignPackage : ReactPackage {
override fun createNativeModules(context: ReactApplicationContext): List<NativeModule> =
listOf(DeaSignModule(context))
override fun createViewManagers(context: ReactApplicationContext): List<ViewManager<*, *>> =
emptyList()
}
Add DeaSignPackage() to the packages your MainApplication returns.
iOS, in a Swift file of your app target. Your app's bridging header imports
<React/RCTBridgeModule.h>:
import DeaReactNative
import DeaSDK
import Foundation
/// signRequest of the native SDK that @dea/react-native started.
@objc(DeaSign)
final class DeaSign: NSObject {
@objc static func requiresMainQueueSetup() -> Bool { false }
@objc func signRequest(
_ eventType: String, claims: [String: Any], scored: Bool,
resolve: @escaping RCTPromiseResolveBlock, reject: @escaping RCTPromiseRejectBlock
) {
DispatchQueue.global(qos: .userInitiated).async { // signRequest blocks
let dea = DeaReactRuntime.sdk
var answer: [String: Any] = ["proof": NSNull(), "refusal": NSNull()]
if let proof = dea?.signRequest(eventType: eventType, claims: claims, scored: scored) {
answer["proof"] = proof
} else {
answer["refusal"] = dea?.lastRequestRefusal ?? "not initialized"
}
resolve(answer)
}
}
}
And an Objective-C file beside it, DeaSign.m:
#import <React/RCTBridgeModule.h>
@interface RCT_EXTERN_MODULE(DeaSign, NSObject)
RCT_EXTERN_METHOD(signRequest:(NSString *)eventType
claims:(NSDictionary *)claims
scored:(BOOL)scored
resolve:(RCTPromiseResolveBlock)resolve
reject:(RCTPromiseRejectBlock)reject)
@end
In JavaScript, put the module's type in one place, ./dea-sign.ts:
import {NativeModules} from 'react-native';
export const DeaSign = NativeModules.DeaSign as {
signRequest(
eventType: string,
claims: Record<string, unknown>,
scored: boolean,
): Promise<{proof: string | null; refusal: string | null}>;
};
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 apiBase of getContributionHosts() followed by /api/tasks/projects |
| Headers | Content-Type: application/json, Accept: application/json, and X-App-Key with your appKey |
| Body | {"h_proof": "<signed request>"}, signed by DeaSign.signRequest('projects', claims, false) |
| Claims to sign | publisher_user_id: your app user id. platform: android or ios. sdk_version: the sdkVersion that init resolves |
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 {Platform} from 'react-native';
import * as Dea from '@dea/react-native';
import {APP_KEY, sdkVersion} from './dea';
import {DeaSign} from './dea-sign';
export type Project = {project_id: string; name: string; pattern_id: string; pattern_name: string};
/** The projects open to this user. */
export async function listProjects(userId: string): Promise<Project[]> {
const {proof, refusal} = await DeaSign.signRequest(
'projects',
{publisher_user_id: userId, platform: Platform.OS, sdk_version: sdkVersion},
false,
);
if (proof === null) throw new Error(`not signed: ${refusal}`);
const {apiBase} = await Dea.getContributionHosts();
const answer = await fetch(`${apiBase}/api/tasks/projects`, {
method: 'POST',
headers: {'Content-Type': 'application/json', Accept: 'application/json', 'X-App-Key': APP_KEY},
body: JSON.stringify({h_proof: proof}),
});
if (answer.status === 204) return []; // no project is open to this user
if (answer.status !== 200) throw new Error(`refused ${answer.status}: ${await answer.text()}`);
return ((await answer.json()).projects ?? []) as Project[];
}
2. Load the page¶
Load CONTRIBUTION_PAGE_HTML into the WebView as a string, with the apiBase of
getContributionHosts() as its base URL:
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.
getContributionHosts() resolves the hosts the native SDK was built with. Your app passes them to
the page in the boot message:
| Field | Boot value | What it is |
|---|---|---|
apiBase |
apiBase |
DEA's API origin, and the page's base URL |
widgetOrigin |
widgetOrigin |
The origin the task's widget is downloaded from |
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 injectJavaScript |
With react-native-webview:
- Define
window.deaHostininjectedJavaScriptBeforeContentLoaded. It callswindow.ReactNativeWebView.postMessagewith a random key in front of each message. - In
onMessage, drop every message without that key: only the page's own script has it. - Let the
WebViewnavigate only toabout:,data:andapiBase, inonShouldStartLoadWithRequest.
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 appKey you passed to init |
publisherUserId |
Your app user id |
projectId |
The project_id of the project the user picked |
apiBase |
apiBase of getContributionHosts() |
widgetOrigin |
widgetOrigin of getContributionHosts() |
mediaOrigin |
mediaOrigin of getContributionHosts() |
sdkVersion |
The sdkVersion that init resolves |
The four calls:
method |
args |
value to answer |
|---|---|---|
ready |
None | null, once init has resolved |
attest |
None | {"verdict": "passed"}: the verdict that attest() resolves |
signRequest |
The claims to sign, with event_type |
The proof that DeaSign.signRequest(event_type, claims, false) resolves, or null |
signContribution |
item_id and artifact_hash |
{"tuple": {"h_proof": "<proof>"}}, from DeaSign.signRequest('contribution', claims, 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 Platform.OS and your sdkVersion. Add no
claim: DEA refuses a request with a claim the route does not take.
When proof is null for signContribution, answer
{"reason": "<refusal>", "outcome": "refused"}. When refusal 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 component loads the page, answers it and reports the outcome. Render it with the user's app
user id, the project_id the user picked, and the hosts that getContributionHosts() resolves:
import React, {useMemo, useRef} from 'react';
import {Platform} from 'react-native';
import {WebView, type WebViewMessageEvent} from 'react-native-webview';
import * as Dea from '@dea/react-native';
import {APP_KEY, sdkVersion} from './dea';
import {DeaSign} from './dea-sign';
type Props = {
userId: string;
projectId: string;
hosts: Dea.ContributionHosts;
/** Called once, with the outcome and its errorCode. */
onOutcome: (outcome: string, errorCode?: string) => void;
};
export function TaskScreen({userId, projectId, hosts, onOutcome}: Props) {
const web = useRef<WebView<object>>(null); // <object> types the props on react-native-webview 14
const ended = useRef(false);
const key = useMemo(() => `${Date.now()}${Math.random()}|`, []); // only the page's script has it
const bridge =
'window.deaHost = { post: function (m) { ' +
`window.ReactNativeWebView.postMessage(${JSON.stringify(key)} + m); } }; true;`;
/** App to page: one JSON object, as a string. */
const deliver = (message: object) =>
web.current?.injectJavaScript(
`window.deaPage && window.deaPage.deliver(${JSON.stringify(JSON.stringify(message))}); true;`,
);
/** Signs the claims the page sent, as sent. Only platform and sdk_version are the app's to set. */
const sign = (eventType: string, fields: Record<string, unknown>, scored: boolean) => {
const {event_type: _eventType, ...claims} = fields;
if ('platform' in claims) claims.platform = Platform.OS;
if ('sdk_version' in claims) claims.sdk_version = sdkVersion;
return DeaSign.signRequest(eventType, claims, scored);
};
/** The four calls. */
const answer = async (method: string, args: unknown): Promise<unknown> => {
const fields = (args ?? {}) as Record<string, unknown>;
switch (method) {
case 'ready':
return null;
case 'attest':
return {verdict: (await Dea.attest()).verdict};
case 'signRequest':
return (await sign(String(fields.event_type), fields, false)).proof;
case 'signContribution': {
const {proof, refusal} = await sign('contribution', fields, true);
if (proof !== null) return {tuple: {h_proof: proof}};
const reason = refusal ?? 'nothing signed';
return {reason, outcome: 'refused', ...(reason.includes('-33') ? {code: -33} : {})};
}
default:
throw new Error(`no method ${method}`);
}
};
/** Page to app. */
const onMessage = (event: WebViewMessageEvent) => {
const raw = event.nativeEvent.data;
if (!raw.startsWith(key)) return; // not the page
const message = JSON.parse(raw.slice(key.length));
switch (message.t) {
case 'ready':
deliver({
t: 'boot',
appKey: APP_KEY,
publisherUserId: userId,
projectId,
apiBase: hosts.apiBase,
widgetOrigin: hosts.widgetOrigin,
mediaOrigin: hosts.mediaOrigin,
sdkVersion,
});
break;
case 'call':
answer(message.method, message.args).then(
value => deliver({t: 'result', id: message.id, value}),
why => deliver({t: 'error', id: message.id, message: String(why)}),
);
break;
case 'outcome':
if (ended.current) return;
ended.current = true;
onOutcome(message.outcome, message.errorCode);
break;
}
};
return (
<WebView<object>
ref={web}
source={{html: Dea.CONTRIBUTION_PAGE_HTML, baseUrl: hosts.apiBase}}
injectedJavaScriptBeforeContentLoaded={bridge}
originWhitelist={['*']}
// The page and the task's frame only: nothing navigates away.
onShouldStartLoadWithRequest={request =>
request.url.startsWith('about:') ||
request.url.startsWith('data:') ||
request.url === hosts.apiBase ||
request.url.startsWith(`${hosts.apiBase}/`)
}
onMessage={onMessage}
/>
);
}
List the projects, show them, and render the screen with the one the user picks:
const hosts = await Dea.getContributionHosts();
<TaskScreen
userId={userId}
projectId={picked.project_id}
hosts={hosts}
onOutcome={outcome => (outcome === 'no_task' ? showProjects() : closeTask())}
/>
showProjects and closeTask stand 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 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 |
Pass the bridge in injectedJavaScriptBeforeContentLoaded |
| 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 | Check the key in onMessage |
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 | Pass baseUrl: hosts.apiBase in source |
not_attested |
attest() did not resolve 'passed', the boot message has no appKey, or DeaSign.signRequest resolved no proof (read refusal) |
See Attest and the native module above |
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 refusal 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 |
|---|---|---|
CONTRIBUTION_PAGE_HTML |
string |
The task page |
getContributionHosts() |
Promise<ContributionHosts> |
apiBase, widgetOrigin and mediaOrigin: the hosts the native SDK was built with. Needs no init |
attest() |
Promise<Attestation> |
Registers the device key. See Attest |
init(config) |
Promise<Started> |
Started.sdkVersion is boot value sdkVersion, and the sdk_version claim |
On the native side, for the DeaSign module:
| Member | Platform | Description |
|---|---|---|
DeaSdk.instance |
Android, ai.dea.sdk |
The SDK that init started |
DeaReactRuntime.sdk |
iOS, module DeaReactNative |
The SDK that init started |
signRequest(eventType, claims, scored) |
Both | Signs a task request with the device key; null or nil when nothing was signed. scored adds the session's score. Blocking |
lastRequestRefusal |
Both | Why the last signRequest signed nothing |