Ads¶
Prove to your advertising partners that an impression or a click came from a real person. On React Native, your app tells the SDK when an ad is on screen, clicked and gone; the native SDK signs a proof for each with the device key, and your app uploads it to DEA's recording service.
The SDK does not request, render or wrap ads. Your ad stack keeps doing that.
Note: React Native has no ad session object and does not check that the user touched the ad. It has one proof call,
getProof(): your app keeps the ad session's id, declares each event itself and uploads each proof as the Upload contract says.Deprecated:
sendProof()andrecord(), which signed and uploaded in one call, still work in this release and are removed in a later release. UsegetProof()and the upload below.
When to use it¶
- You sell ad inventory and want to show buyers verified human traffic
- You want each impression, click and end of an ad recorded with the score at that moment
Compared with the Web SDK¶
| Web | React Native |
|---|---|
ads.session_opened(surface?, adUnit?, options?) (options since 0.26.0) |
getProof('ad.impression', {sessionId: ''}), then POST /api/sessions; keep the session_id DEA answers with |
ad.click() |
getProof('ad.click', {sessionId: id}), then POST /api/sessions |
ad.end() |
getProof('ad.ended', {sessionId: id}), then PUT /api/sessions/{id} |
| A click that nothing touched is refused | Not checked: your app declares the click |
| One click per ad, nothing after the end | Up to you |
ads.counts |
What each upload answered |
Prerequisites¶
- The SDK is installed and initialized with your
appIdand yourappKey. See the Quick Start. TheappKeyis required: on a productionappId(one without atest_orsandbox_prefix) with noappKey,getProof()resolvesnullandgetLastProofRefusal()resolvesapp_key_missing, without a request. - The device key is registered: call
attest()and get'passed'before the impression (on Android this also needsplayIntegrityProject). DEA refuses a proof signed by a key it has not registered.
Keep the sdkVersion that init resolves: the upload sends it.
import {Platform} from 'react-native';
import * as Dea from '@dea/react-native';
export const APP_KEY = Platform.OS === 'ios' ? 'YOUR_IOS_APP_KEY' : 'YOUR_ANDROID_APP_KEY';
export let sdkVersion = '';
export async function startDea(): Promise<void> {
const started = await Dea.init({
appId: Platform.OS === 'ios' ? 'YOUR_IOS_APP_ID' : 'YOUR_ANDROID_APP_ID',
appKey: APP_KEY,
});
sdkVersion = started.sdkVersion;
}
Usage¶
An ad session takes three proofs, in this order:
- The impression, signed with
sessionId: ''and uploaded asPOST /api/sessions. DEA opens the ad session and answers{"session_id": "<id>"}. Do not leavesessionIdout: the native SDK then signs the capture session's id, which is not an ad session's id. - The click, if there is one, signed with the id DEA answered and uploaded as
POST /api/sessions. - The end, signed with the same id and uploaded as
PUT /api/sessions/{id}.
Pass the same adUnit to all three: it is signed into each proof. getProof() fetches a challenge
(a single-use nonce) from DEA before it signs, and never uploads. Nothing is signed until the
session is sufficient: check that
getClassification() does not resolve result: 'insufficient' before the impression when it has
to be recorded.
Upload contract¶
| Item | Rule |
|---|---|
| Host | https://poh-api.dep-protocol.com |
ad.impression |
getProof with sessionId "", then POST /api/sessions. The answer {"session_id": "<id>"} names the ad session |
ad.click |
getProof with sessionId set to the ad session id, then POST /api/sessions |
ad.ended |
getProof with sessionId set to the ad session id, then PUT /api/sessions/{id}, {id} URL-encoded. The path id equals the proof's session_id claim, or DEA answers 400 |
| Headers | Content-Type: application/json, Accept: application/json, X-App-Key with the SDK's appKey property. No X-App-ID |
| Body | One JSON object: the app's own unsigned fields first, then h_proof (the SignedProof.proof) and sdk_version, which win over an app field of the same name |
sdk_version |
Started.sdkVersion, from what init resolves |
| Timeout | 15 s per request |
| Accepted | Any 2xx. An empty body or a body that is not JSON still counts as accepted |
| Retry | Only on no answer (an I/O error or a timeout) or a 5xx |
| Final | Any 4xx, 429 included: no retry |
| Never retry | An error that is neither an HTTP status nor a transport failure, such as an answer that did not parse: DEA took the proof, and the same jti again is a replay |
| Attempts | At most 5 sends in all |
| Backoff | Before retry n (n is 1 after the first failed send): min(2000 * 2^(n-1), 30000) ms, plus a random 0 to 999 ms |
| Expiry | Never send at or after the proof's exp claim (iat plus 90 s): stop and drop the proof |
| Same proof | A retry resends the same h_proof. Each getProof makes a new jti |
The React Native package has no appKey reader: send as X-App-Key the same appKey you passed
to init.
Sign and upload one event¶
SignedProof on React Native does not carry the decoded claims, so this helper takes its expiry
from the clock: the proof's iat is no earlier than the second getProof() was called in, so 90
seconds after that second is never later than exp.
import * as Dea from '@dea/react-native';
import type {ProofEvent} from '@dea/react-native';
import {APP_KEY, sdkVersion} from './dea';
const HOST = 'https://poh-api.dep-protocol.com';
export type Upload =
| {kind: 'accepted'; body: Record<string, unknown> | null} // a 2xx
| {kind: 'refused'; status: number; body: string} // a 4xx (final) or the last 5xx
| {kind: 'undelivered'; why: string}; // nothing signed, no answer, expired, or not retried
const sleep = (ms: number) => new Promise(resolve => setTimeout(() => resolve(undefined), ms));
/** Signs one ad event and uploads it. `ad.ended` goes up as PUT /api/sessions/{id}. */
export async function signAndUpload(
event: ProofEvent,
sessionId: string,
adUnit: string,
appFields: Record<string, unknown> = {},
appScopedUid?: string, // your app user id; left out when undefined
): Promise<Upload> {
const deadline = Math.floor(Date.now() / 1000) * 1000 + 90_000; // never after exp
const signed = await Dea.getProof(event, {sessionId, adUnit, appScopedUid});
if (!signed) {
return {kind: 'undelivered', why: `not signed: ${await Dea.getLastProofRefusal()}`};
}
const update = event === 'ad.ended';
// The path id is the proof's own session_id, URL-encoded.
const url = update
? `${HOST}/api/sessions/${encodeURIComponent(signed.sessionId)}`
: `${HOST}/api/sessions`;
// The app's fields first; h_proof and sdk_version come last, so they win.
const body = JSON.stringify({...appFields, h_proof: signed.proof, sdk_version: sdkVersion});
let last: Upload = {kind: 'undelivered', why: 'not sent'};
for (let attempt = 1; attempt <= 5; attempt++) {
if (attempt > 1) {
const n = attempt - 1;
await sleep(Math.min(2000 * 2 ** (n - 1), 30_000) + Math.floor(Math.random() * 1000));
}
if (Date.now() >= deadline) return {kind: 'undelivered', why: 'proof expired'};
const abort = new AbortController();
const timer = setTimeout(() => abort.abort(), 15_000);
let response: Response;
try {
response = await fetch(url, {
method: update ? 'PUT' : 'POST',
headers: {
'Content-Type': 'application/json',
Accept: 'application/json',
'X-App-Key': APP_KEY,
},
body,
signal: abort.signal,
});
} catch (noAnswer) {
last = {kind: 'undelivered', why: `no answer: ${noAnswer}`}; // retried, timeouts included
continue;
} finally {
clearTimeout(timer);
}
const text = await response.text().catch(() => '');
if (response.status >= 200 && response.status < 300) {
let json: Record<string, unknown> | null = null;
try {
const parsed = JSON.parse(text);
if (parsed && typeof parsed === 'object') json = parsed;
} catch {
// Not JSON: still accepted.
}
return {kind: 'accepted', body: json};
}
if (response.status >= 500) {
last = {kind: 'refused', status: response.status, body: text}; // retried
continue;
}
return {kind: 'refused', status: response.status, body: text}; // a 4xx, 429 included: final
}
return last;
}
A retry resends the same body, so the same h_proof. Do not call getProof() again to retry:
that signs a new proof with a new jti.
One ad, from impression to end¶
import * as Dea from '@dea/react-native';
import {signAndUpload} from './dea-upload';
/** The proofs of one ad. Create one for each ad you show. */
export class AdProofs {
private adSessionId: string | null = null;
private clicked = false;
private queue: Promise<unknown> = Promise.resolve(); // keeps the three in order
constructor(
private readonly adUnit: string,
private readonly userId?: string, // your app user id, signed as appScopedUid
) {}
shown(): void {
this.queued(async () => {
if ((await Dea.attest()).verdict !== 'passed') return;
const answer = await signAndUpload('ad.impression', '', this.adUnit, {}, this.userId);
if (answer.kind !== 'accepted') return console.warn('Impression not recorded', answer);
const id = answer.body?.session_id;
if (typeof id === 'string' && id !== '') this.adSessionId = id;
});
}
click(): void {
this.queued(async () => {
if (this.adSessionId === null || this.clicked) return;
this.clicked = true;
await signAndUpload('ad.click', this.adSessionId, this.adUnit, {}, this.userId);
});
}
end(): void {
this.queued(async () => {
const id = this.adSessionId;
if (id === null) return;
this.adSessionId = null;
await signAndUpload('ad.ended', id, this.adUnit, {}, this.userId);
});
}
private queued(step: () => Promise<void>): void {
this.queue = this.queue.then(step).catch(() => {});
}
}
Call shown(), click() and end() from your ad SDK's callbacks for that ad. A click or an end
before DEA has answered the impression has no ad session id, so nothing is signed for it. The next
ad is a new AdProofs.
Find out why a proof was not accepted¶
When getProof() resolves null, call getLastProofRefusal() right after it. It resolves null
before the first getProof() and after a signed one, and the next getProof() overwrites it. The
value is the native SDK's:
getLastProofRefusal() |
Why |
|---|---|
no_core |
dispose() was called, or no core is loaded |
app_key_missing |
A production appId without appKey. Refused on the device, without a request |
no_key |
The device has no key to sign with |
automated |
Automation detection stopped the SDK, on every account and build. reset() or a new start lifts the stop. See stopped |
not_scored |
The session is not sufficient yet (core code -33) |
core_not_initialised |
The core refused: code -1 |
core_bad_argument |
The core refused: code -2 |
claims_invalid |
The core refused the claims: code -30, or a code outside this list |
claim_reserved |
The core refused the claims: code -31 |
claim_missing |
The core refused the claims: code -32 |
proof_too_large |
The core refused: code -34 |
core_panic |
The core failed: code -99 |
key_sign_failed |
The device key did not sign |
claim_score_missing |
The composed claims lack h_score, h_ts or h_wc |
answer_mismatch |
The composed claims name another session, event or key |
claim_model_version_invalid |
The composed h_mv is not a whole number at or above 0 |
When a proof was signed, the upload's own outcome says the rest:
| Upload outcome | Why |
|---|---|
2xx |
DEA accepted the proof. After an impression, an answer without a session_id (or one that is empty or not JSON) still counts as accepted, but no ad session opened: send no click and no end |
4xx, 429 included |
Final, not retried. For example the device key is not registered (call attest() first), appKey is not the app the device key is registered under, or, for an end, the path id is not the proof's session_id (400) |
5xx |
Retried; after five sends, the last answer |
| No answer: a network error or a timeout | Retried; DEA could not be reached in five sends |
| The proof expired | The retries ran up to the proof's exp, 90 seconds after it was signed. The proof is dropped |
| Another error, such as an answer that did not parse | Not retried: DEA may hold the proof, and the same jti again is a replay |
Read the classification before you request an ad¶
getProof() does not read the classification: once the session is sufficient, every ad your app
declares is signed, whatever the score. To decide whether to request an ad at all, read the
classification first and act on it in your own ad stack — see
Human Scoring.
App user id¶
Pass your app's id for the user as appScopedUid to each getProof() of one ad: the impression,
the click and the end. The SDK signs it into the proof, and DEA stores it on the ad session. Leave
it out and no id is sent. signAndUpload takes it as its last
argument, and the AdProofs class above takes it as userId:
Use an id that does not identify the person, of 1 to 128 characters, and the same one you pass to AI Data Tasks. See App user ids.
API¶
| Member | Returns | Description |
|---|---|---|
getProof(event, options?) |
Promise<SignedProof \| null> |
Signs one ad event without uploading it; null when nothing was signed. options: sessionId, adUnit, appScopedUid |
getLastProofRefusal() |
Promise<string \| null> |
Why the last getProof() resolved null; null before the first getProof() and after a signed one |
sendProof(event, options?) |
Promise<RecordOutcome> |
Deprecated, removed in a later release. Use getProof() and your own upload |
record(event, options?) |
Promise<boolean> |
Deprecated, removed in a later release. Use getProof() and your own upload |
ProofEvent: 'ad.impression', 'ad.click', 'ad.ended'. SignedProof.proof is the compact JWS
to send as h_proof, and SignedProof.sessionId the signed session_id.
Related¶
- Activities: record a game round, a quiz, a lesson or a video
- Human Scoring
- Attest
- Accounts and keys
- API Reference