Skip to content

Ads

Prove to your advertising partners that an impression or a click came from a real person. For each moment of an ad (on screen, clicked, gone) the SDK signs the current score into a proof with the device key, and your app uploads it to DEA's recording service, which keeps it so it can be verified later.

The SDK does not request, render or wrap ads. Your ad stack keeps doing that.

Note: iOS has the proof call, not the Web ad module. You sign the three proofs with getProof, upload them yourself as the Upload contract says, and the SDK does not check that the user touched the ad.

Deprecated: sendProof and record, which signed and uploaded in one call, still work in this release and are removed in a later release. Use getProof and the upload below.

What iOS has

The Web SDK has an ad module: ads.session_opened(surface?, adUnit?) sends the impression and resolves an AdSession whose id, click() and end() carry the rest, ads.counts counts what happened, and a click is refused when nothing touched the ad's element. iOS has neither the module nor the touch check. It has the call the module is built on: getProof.

Web iOS
The ad is on screen ads.session_opened(surface?, adUnit?, options?) (options since 0.26.0) getProof(event: .adImpression, sessionId: ""), then POST /api/sessions; keep the session_id DEA answers with
The ad is clicked ad.click() getProof(event: .adClick, sessionId: id), then POST /api/sessions
The ad is gone ad.end() getProof(event: .adEnded, sessionId: id), then PUT /api/sessions/{id}
The click is checked against touches Yes, when you pass the ad's element No: your app declares it
One click per ad, nothing after the end Enforced by the SDK Up to you
What happened ads.counts What each upload answered

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

Prerequisites

  • The SDK is installed and started with your appId and your appKey. See the Quick Start. The appKey is required: on a production appId (one without a test_ or sandbox_ prefix) with no appKey, getProof returns nil and lastProofRefusal is app_key_missing, without a request.
  • The device key registered: call attest() and get .passed before the impression. The SDK does not register the key by itself and does not check that you did: without a registration, proofs are still signed, and DEA refuses them, as it refuses every proof signed by a key it has not registered.
  • The user's consent, when requireConsent is on (the default). Before it, nothing is recorded, so the session never becomes sufficient and nothing is signed.

The Quick Start's holder:

import DeaSDK

enum Dea {
    /// The app's one DEA SDK instance. Nil until `start()` has run.
    private(set) static var sdk: DeaSdk?

    static func start() {
        guard sdk == nil else { return }
        let dea = DeaSdk(
            options: DeaSdkOptions(
                appId: "YOUR_APP_ID",
                appKey: "YOUR_APP_KEY"
            )
        )
        dea.start()
        sdk = dea
    }
}

Usage

getProof asks DEA for a single-use nonce before it signs, so it blocks the calling thread. The upload below blocks too. Never call either on the main thread.

An ad session takes three proofs, in this order:

  1. The impression, signed with sessionId: "" and uploaded as POST /api/sessions. DEA opens the ad session and answers {"session_id": "<id>"}. Leave sessionId out and the SDK signs the id of the SDK's own session (sessionInfo.session) instead, which is not an ad session.
  2. The click, if there is one, signed with the id DEA answered and uploaded as POST /api/sessions.
  3. The end, signed with the same id and uploaded as PUT /api/sessions/{id}, the update of the ad session the impression opened.

adUnit is signed into the proof as ad_unit. Pass the same one to the impression, the click and the end. When DEA gives no nonce, the proof is signed without one. The proof carries the current score, written by the core and signed with the device key.

The attestation parameter decides only the tier signed into the proof. Left nil, the SDK uses the registration it holds: B when it passed with an App Attest token (platformAttested) and has not expired, C otherwise.

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 sdkVersion (from import DeaSDK)
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 nil.

Upload a proof

This uploader follows the contract with URLSession. It blocks; call it off the main thread:

import DeaSDK
import Foundation

/// What DEA answered one proof with.
enum Upload {
    /// A 2xx: the answer as JSON, or nil when it was empty or not JSON.
    case accepted([String: Any]?)
    /// A 4xx, which is final, or the last 5xx.
    case refused(status: Int, body: String)
    /// No answer in five sends, the proof expired, or an error that must not be retried.
    case undelivered(String)
}

enum DeaUpload {
    private static let host = "https://poh-api.dep-protocol.com"

    private static let session: URLSession = {
        let config = URLSessionConfiguration.ephemeral
        config.timeoutIntervalForRequest = 15
        config.timeoutIntervalForResource = 15 // 15 s for the whole request
        return URLSession(configuration: config)
    }()

    /// Uploads one proof. `update` sends it as `PUT /api/sessions/{id}`: pass it for `.adEnded`.
    static func send(
        _ signed: SignedProof, by dea: DeaSdk, update: Bool = false, appFields: [String: Any] = [:]
    ) -> Upload {
        guard let appKey = dea.appKey else { return .undelivered("no appKey") }

        // The app's fields first; h_proof and sdk_version are set last, so they win.
        var fields = appFields
        fields["h_proof"] = signed.proof
        fields["sdk_version"] = sdkVersion
        guard let body = try? JSONSerialization.data(withJSONObject: fields) else {
            return .undelivered("the app's fields are not JSON")
        }

        // The path id is the proof's own session_id, URL-encoded.
        var segment = CharacterSet.urlPathAllowed
        segment.remove("/")
        let id = signed.sessionId.addingPercentEncoding(withAllowedCharacters: segment) ?? ""
        let url = URL(string: update ? "\(host)/api/sessions/\(id)" : "\(host)/api/sessions")!
        let expiresAt = (signed.claims?["exp"] as? NSNumber)?.doubleValue ?? 0 // seconds

        var last = Upload.undelivered("not sent")
        for attempt in 1...5 {
            if attempt > 1 {
                let n = attempt - 1
                let ms = min(2000 * (1 << (n - 1)), 30_000) + Int.random(in: 0...999)
                Thread.sleep(forTimeInterval: Double(ms) / 1000)
            }
            if Date().timeIntervalSince1970 >= expiresAt { return .undelivered("proof expired") }

            var request = URLRequest(url: url)
            request.httpMethod = update ? "PUT" : "POST"
            request.httpBody = body
            request.setValue("application/json", forHTTPHeaderField: "Content-Type")
            request.setValue("application/json", forHTTPHeaderField: "Accept")
            request.setValue(appKey, forHTTPHeaderField: "X-App-Key")

            let (data, response, error) = exchange(request)
            if let error {
                if error is URLError {
                    last = .undelivered("no answer: \(error)") // retried, timeouts included
                    continue
                }
                return .undelivered("not retried: \(error)") // DEA may hold the proof
            }
            guard let http = response as? HTTPURLResponse else {
                return .undelivered("not retried: not an HTTP answer")
            }

            let text = String(decoding: data ?? Data(), as: UTF8.self)
            switch http.statusCode {
            case 200..<300:
                let json = data.flatMap { try? JSONSerialization.jsonObject(with: $0) }
                return .accepted(json as? [String: Any])
            case 500..<600:
                last = .refused(status: http.statusCode, body: text) // retried
            default:
                return .refused(status: http.statusCode, body: text) // a 4xx, 429 included: final
            }
        }
        return last
    }

    private static func exchange(_ request: URLRequest) -> (Data?, URLResponse?, Error?) {
        let done = DispatchSemaphore(value: 0)
        var result: (Data?, URLResponse?, Error?) = (nil, nil, nil)
        session.dataTask(with: request) { data, response, error in
            result = (data, response, error)
            done.signal()
        }.resume()
        done.wait()
        return result
    }
}

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.

Note: The click is not checked against touches on iOS. The SDK signs a click whenever your app calls getProof(event: .adClick, …), without looking at what the user touched, and it does not stop a second click or a click after the end. Your app declares the click: sign one per ad, when your ad SDK reports it.

Read why a proof was not recorded

Two steps can fail: signing and the upload.

When getProof returns nil, read lastProofRefusal right after it. It is nil before the first getProof and after a signed one, and holds the reason after a nil. The next getProof, from any thread, overwrites it, so read it before anything else signs:

lastProofRefusal Why
no_core dispose() was called, or no core is loaded (ready is false)
app_key_missing A production appId without appKey. Refused on the device, without a request
no_key No device key could be created 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)
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: there is no ad session for the click and 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

A session that has just started is not sufficient until it has as many actions as the model asks for, 8 with the built-in model (see Evidence). Until then nothing is signed, so an impression declared then is not recorded, and the SDK does not keep it to sign later. Check that getClassification().result is not .insufficient before the impression, as the Example does, rather than spend a request on a refusal. When the impression is refused, there is no ad session for the click and the end.

Read the classification before you request an ad

You can also read the classification before you request an ad, and decide what to do with it in your own ad stack — see Human Scoring.

Examples

One ad, from on screen to gone

This class uses DeaUpload from Upload a proof:

import DeaSDK
import Foundation

/// The proofs for one ad, from on screen to gone. Each method returns at once; the proofs are
/// signed and uploaded in order on a background queue.
final class AdProofs {
    private let adUnit: String
    private let userId: String? // your app user id, signed as appScopedUid
    private let queue = DispatchQueue(label: "ad-proofs") // serial: keeps the three in order
    private var adSessionId: String? // DEA's id for this ad, from the impression's answer
    private var hasClicked = false

    init(adUnit: String, userId: String? = nil) {
        self.adUnit = adUnit
        self.userId = userId
    }

    /// The ad is on screen.
    func shown() {
        queue.async { [self] in
            // Nothing is signed before the session is sufficient, and DEA refuses a proof
            // from a device key it has not registered.
            guard let dea = Dea.sdk,
                let result = (try? dea.getClassification())?.result,
                result != .insufficient,
                dea.attest().verdict == .passed
            else { return }

            guard let signed = dea.getProof(
                event: .adImpression, sessionId: "", adUnit: adUnit, appScopedUid: userId)
            else {
                print("DEA impression not signed: \(dea.lastProofRefusal ?? "")")
                return
            }
            switch DeaUpload.send(signed, by: dea) {
            case .accepted(let answer):
                if let id = answer?["session_id"] as? String, !id.isEmpty {
                    adSessionId = id
                }
            case let other:
                print("DEA impression not recorded: \(other)")
            }
        }
    }

    /// The user clicked the ad. Only the first click is signed.
    func clicked() {
        queue.async { [self] in
            guard let dea = Dea.sdk, let id = adSessionId, !hasClicked else { return }
            hasClicked = true

            guard let signed = dea.getProof(
                event: .adClick, sessionId: id, adUnit: adUnit, appScopedUid: userId)
            else {
                print("DEA click not signed: \(dea.lastProofRefusal ?? "")")
                return
            }
            if case .accepted = DeaUpload.send(signed, by: dea) { return }
            print("DEA click not recorded")
        }
    }

    /// The ad is gone: removed, replaced or dismissed.
    func gone() {
        queue.async { [self] in
            guard let dea = Dea.sdk, let id = adSessionId else { return }
            adSessionId = nil // nothing more is signed for this ad

            guard let signed = dea.getProof(
                event: .adEnded, sessionId: id, adUnit: adUnit, appScopedUid: userId)
            else {
                print("DEA end not signed: \(dea.lastProofRefusal ?? "")")
                return
            }
            // PUT /api/sessions/{id}
            if case .accepted = DeaUpload.send(signed, by: dea, update: true) { return }
            print("DEA end not recorded")
        }
    }
}

Create one AdProofs per ad, and call its methods from your ad SDK's callbacks:

let ad = AdProofs(adUnit: "YOUR_AD_UNIT", userId: userId)
ad.shown()   // your ad SDK reports the ad on screen
ad.clicked() // it reports a click
ad.gone()    // the ad is removed or dismissed

The next ad is a new AdProofs, and its impression opens a new ad session with 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.

let signed = dea.getProof(event: .adImpression, sessionId: "", 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(event:sessionId:attestation:adUnit:appScopedUid:) SignedProof? Signs one proof without uploading it; nil when nothing was signed. Blocking
lastProofRefusal String? Why the last getProof returned nil; nil before the first getProof and after a signed one
appKey String? The key to send as X-App-Key
sdkVersion String The SDK version to send as sdk_version
sendProof(event:sessionId:attestation:adUnit:appScopedUid:extra:update:) RecordOutcome Deprecated, removed in a later release. Use getProof and your own upload
record(event:sessionId:attestation:adUnit:appScopedUid:extra:update:) Bool Deprecated, removed in a later release. Use getProof and your own upload

ProofEvent: .adImpression, .adClick, .adEnded.

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. For SignedProof and the parameters, see the API Reference.