Ads¶
Prove to your advertising partners that an impression or a click came from a real person. On Flutter, your app tells the SDK when an ad is on screen, clicked and gone; the SDK signs a proof for each with the device key, and your app uploads it to DEA's recording service, which keeps it.
The SDK does not request, render or wrap ads. Your ad stack keeps doing that.
What Flutter has¶
The Flutter SDK has one proof call on DeaSdk: getProof(). It signs a proof for one ad event,
ProofEvent.adImpression, adClick or adEnded, with the score the core has at that moment, and
returns it as a SignedProof. It never uploads: your app uploads each proof as the
Upload contract says, in the order the Web SDK's ad module sends them and with
the same ad session ids.
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.
It does not have what the Web SDK's ad module adds on top of those proofs:
- The ad session object. There is no
ads.session_opened(),ad.id,ad.click(),ad.end()orads.counts. Your app keeps DEA's ad session id for each ad itself and uploads each proof itself. - The check that the user touched the ad. The Web SDK watches the ad's element and refuses a click that nothing touched.
Note: The click is not checked against touches on Flutter: your app declares it, and the SDK signs it. Sign a click only from the handler of a real tap on the ad, at most one per ad, and none after the end.
Like the Web module, getProof() does not read the classification: a bot result does not stop a
proof, and the score inside the proof tells DEA how human the
session was. But nothing is signed until the session is
sufficient: until it has as many
actions as the
model asks for, 8 with the built-in model (see
Evidence). Before that, getProof() returns
null with lastProofRefusal not_scored, so an impression reported then is not recorded, and the
SDK does not keep it to sign later. Check that getClassification().result is not insufficient
before the impression when it has to be recorded — see
Find out why a proof was not accepted.
When to use it¶
- You sell ad inventory and want to show buyers verified human traffic
- You want each impression, click and ad end recorded with the score at that moment
Prerequisites¶
- The SDK is installed and initialized with this platform's
appIdand itsappKey. See the Quick Start and Accounts and keys. TheappKeyis required: on a productionappId(one without atest_orsandbox_prefix) with noappKey,getProof()returnsnullandlastProofRefusalisapp_key_missing, without a request. - The device key is registered: call
attest()and getVerdict.passedbefore the impression.getProof()does not register the key itself, and DEA refuses a proof signed by a key it has not registered. Without apassedattestation,getProof()still signs, and the proof claims tierC. package:httpin your app'spubspec.yaml, for the upload example below. Any HTTP client that follows the contract works.
Pass each to DeaSdk.init, the value issued for the platform the app runs on:
import 'dart:io' show Platform;
import 'package:dea_sdk/dea_sdk.dart';
import 'package:flutter/material.dart';
void main() {
DeaSdk.init(
DeaOptions(
appId: Platform.isIOS ? 'YOUR_IOS_APP_ID' : 'YOUR_ANDROID_APP_ID',
),
appKey: Platform.isIOS ? 'YOUR_IOS_APP_KEY' : 'YOUR_ANDROID_APP_KEY',
);
runApp(const MyApp());
}
Usage¶
The three proofs of one ad go up in this order, as the Web module sends them:
| Step | Event | sessionId |
Uploaded as |
|---|---|---|---|
| The ad is on screen | ProofEvent.adImpression |
'' (empty) |
POST /api/sessions. DEA answers with the ad's session id |
| The user taps the ad | ProofEvent.adClick |
DEA's id | POST /api/sessions |
| The ad is gone | ProofEvent.adEnded |
DEA's id | PUT /api/sessions/{id} |
The ad's session id is not the capture session: never pass getSessionInfo().session. sessionId
has no default, so each call names it. Pass the ad unit the ad loaded into as adUnit: it is
signed into the proof as ad_unit. Pass the same value for the click and the end.
getProof() first asks DEA for a single-use nonce, which goes inside the signature; when DEA does
not give one, the proof is signed without it. A proof is valid for 90 seconds after it is signed.
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 |
packageVersion (from package:dea_sdk/dea_sdk.dart) |
| 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 |
DeaSdk.appKey is the key to send: the appKey you passed, the development key on a test_ or
sandbox_ account that named none, or null. Nothing is kept on the device: a proof still unsent
when the app is closed is lost.
Upload a proof¶
This uploader follows the contract with package:http:
import 'dart:async';
import 'dart:convert';
import 'dart:io' show SocketException;
import 'dart:math';
import 'package:dea_sdk/dea_sdk.dart';
import 'package:http/http.dart' as http;
const _host = 'https://poh-api.dep-protocol.com';
final _random = Random();
/// What DEA answered one proof with.
sealed class Upload {}
/// A 2xx. [body] is the answer as JSON, or null when it was empty or not JSON.
final class Accepted extends Upload {
Accepted(this.body);
final Map<String, Object?>? body;
}
/// A 4xx, which is final, or the last 5xx.
final class Refused extends Upload {
Refused(this.status, this.body);
final int status;
final String body;
}
/// No answer in five sends, the proof expired, or an error that must not be retried.
final class Undelivered extends Upload {
Undelivered(this.why);
final String why;
}
/// Uploads one proof. [update] sends it as `PUT /api/sessions/{id}`: pass it for adEnded.
Future<Upload> uploadProof(
DeaSdk dea,
SignedProof signed, {
bool update = false,
Map<String, Object?> appFields = const {},
}) async {
final appKey = dea.appKey;
if (appKey == null) return Undelivered('no appKey');
// The app's fields first; h_proof and sdk_version come last, so they win.
final body = jsonEncode({
...appFields,
'h_proof': signed.proof,
'sdk_version': packageVersion,
});
// The path id is the proof's own session_id, URL-encoded.
final uri = Uri.parse(update
? '$_host/api/sessions/${Uri.encodeComponent(signed.sessionId)}'
: '$_host/api/sessions');
final headers = {
'Content-Type': 'application/json',
'Accept': 'application/json',
'X-App-Key': appKey,
};
final expiresAt = (signed.claims?['exp'] as num?)?.toInt() ?? 0; // seconds
Upload last = Undelivered('not sent');
for (var attempt = 1; attempt <= 5; attempt++) {
if (attempt > 1) {
final n = attempt - 1;
final wait = min(2000 * (1 << (n - 1)), 30000) + _random.nextInt(1000);
await Future<void>.delayed(Duration(milliseconds: wait));
}
if (DateTime.now().millisecondsSinceEpoch ~/ 1000 >= expiresAt) {
return Undelivered('proof expired');
}
final http.Response answer;
try {
final send = update ? http.put : http.post;
answer = await send(uri, headers: headers, body: body)
.timeout(const Duration(seconds: 15));
} on TimeoutException catch (e) {
last = Undelivered('no answer: $e'); // retried
continue;
} on SocketException catch (e) {
last = Undelivered('no answer: $e'); // retried
continue;
} on http.ClientException catch (e) {
last = Undelivered('no answer: $e'); // retried
continue;
} catch (e) {
return Undelivered('not retried: $e'); // DEA may hold the proof
}
final status = answer.statusCode;
if (status >= 200 && status < 300) {
Map<String, Object?>? json;
try {
final decoded = jsonDecode(answer.body);
if (decoded is Map<String, Object?>) json = decoded;
} catch (_) {
// Not JSON: still accepted.
}
return Accepted(json);
}
if (status >= 500) {
last = Refused(status, answer.body); // retried
continue;
}
return Refused(status, answer.body); // 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.
Find out why a proof was not accepted¶
Two steps can fail: signing and the upload.
When getProof() returns null, read lastProofRefusal right after it. It is null before the
first getProof() and after a signed one, and holds the reason after a null. The next
getProof() overwrites it, so read it before anything else signs:
lastProofRefusal |
Why |
|---|---|
no_core |
dispose() was called, or no core is loaded: isScoring is false, and error says why |
app_key_missing |
A production appId without appKey. Refused on the device, without a request |
no_key |
No device key could be created or read on this device |
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): fewer actions than the model asks for, 8 with the built-in model, which getClassification() reports as insufficient. Sign the impression again once the session is sufficient, if the ad is still on screen |
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 platform refused to sign with the device key |
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 session opened: do not sign the click or the 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: an I/O 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¶
The proofs record ads you have already shown. To decide whether to request an ad at all, read the classification first, and decide what to do with it in your own ad stack — see Human Scoring.
Examples¶
One ad, from impression to end¶
This class uses uploadProof from Upload a proof:
import 'package:dea_sdk/dea_sdk.dart';
/// The proofs of one ad: the impression, at most one click, and the end.
class AdProofs {
AdProofs(this.adUnit, {this.userId});
final String adUnit;
/// Your app user id, signed as appScopedUid.
final String? userId;
/// DEA's session id for this ad, from its answer to the impression.
String? _sessionId;
bool _clicked = false;
bool _ended = false;
/// Keeps the three in order: each starts after the one before has finished.
Future<void> _last = Future.value();
Future<void> _queued(Future<void> Function() step) =>
_last = _last.then((_) => step()).catchError((Object _) {});
/// The ad is on screen.
Future<void> shown() => _queued(() async {
final dea = DeaSdk.instance;
if (dea == null) return;
final attestation = await dea.attest();
if (attestation.verdict != Verdict.passed) return;
final signed = await dea.getProof(
sessionId: '', // empty: DEA makes the session id
event: ProofEvent.adImpression,
adUnit: adUnit,
appScopedUid: userId,
);
if (signed == null) {
print('Impression not signed: ${dea.lastProofRefusal}');
return;
}
final answer = await uploadProof(dea, signed);
if (answer is! Accepted) {
print('Impression not recorded: $answer');
return;
}
final id = answer.body?['session_id'];
if (id is String && id.isNotEmpty) _sessionId = id;
});
/// The user tapped the ad. Call it from your ad's click callback.
Future<void> clicked() => _queued(() async {
final dea = DeaSdk.instance;
final id = _sessionId;
if (dea == null || id == null || _clicked || _ended) return;
_clicked = true;
final signed = await dea.getProof(
sessionId: id,
event: ProofEvent.adClick,
adUnit: adUnit,
appScopedUid: userId,
);
if (signed == null) {
print('Click not signed: ${dea.lastProofRefusal}');
return;
}
await uploadProof(dea, signed);
});
/// The ad is gone: removed, replaced, or its screen closed.
Future<void> ended() => _queued(() async {
final dea = DeaSdk.instance;
final id = _sessionId;
if (dea == null || id == null || _ended) return;
_ended = true;
final signed = await dea.getProof(
sessionId: id,
event: ProofEvent.adEnded,
adUnit: adUnit,
appScopedUid: userId,
);
if (signed == null) {
print('End not signed: ${dea.lastProofRefusal}');
return;
}
await uploadProof(dea, signed, update: true); // PUT /api/sessions/{id}
});
}
Create one AdProofs per ad you show, and call shown(), clicked() and ended() 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, and DEA gives it a new id.
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. The AdProofs class above takes it as userId.
final signed = await dea.getProof(
sessionId: '',
event: ProofEvent.adImpression,
adUnit: adUnit,
appScopedUid: 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({sessionId, event, …}) |
Future<SignedProof?> |
Signs one proof without uploading it; null when nothing was signed |
lastProofRefusal |
String? |
Why the last getProof() returned null; null before the first getProof() and after a signed one |
appKey |
String? |
The key to send as X-App-Key |
packageVersion |
String |
The SDK version to send as sdk_version |
ProofEvent |
— | adImpression, adClick, adEnded |
sendProof({sessionId, event, …}) |
Future<RecordOutcome> |
Deprecated, removed in a later release. Use getProof() and your own upload |
record({sessionId, event, …}) |
Future<bool> |
Deprecated, removed in a later release. Use getProof() and your own upload |
SignedProof.proof is the compact JWS to send as h_proof; SignedProof.sessionId is the signed
session_id, and SignedProof.claims the decoded claim set, exp included. See the
API Reference for every parameter.
Related¶
- Activities: record a game round, a quiz, a lesson or a video
- Human Scoring
- Attest
- Accounts and keys
- Web: Ads
- API Reference