clockwork_http/instructions/
request_ack.rs

1use {
2    crate::state::{Config, Fee, FeeAccount, Request, SEED_CONFIG, SEED_FEE, SEED_REQUEST},
3    anchor_lang::{prelude::*, system_program},
4    std::mem::size_of,
5};
6
7#[derive(Accounts)]
8#[instruction()]
9pub struct RequestAck<'info> {
10    #[account(mut)]
11    pub ack_authority: Signer<'info>,
12
13    #[account(mut)]
14    pub caller: SystemAccount<'info>,
15
16    #[account(seeds = [SEED_CONFIG], bump)]
17    pub config: Account<'info, Config>,
18
19    #[account(
20        init_if_needed,
21        seeds = [
22            SEED_FEE,
23            worker.key().as_ref(),
24        ],
25        bump,
26        space = 8 + size_of::<Fee>(),
27        payer = ack_authority
28    )]
29    pub fee: Account<'info, Fee>,
30
31    #[account(
32        mut,
33        seeds = [
34            SEED_REQUEST,
35            request.api.as_ref(),
36            request.caller.as_ref(),
37            request.id.as_bytes().as_ref()
38        ],
39        bump,
40        close = caller,
41        has_one = caller
42    )]
43    pub request: Account<'info, Request>,
44
45    #[account(address = system_program::ID)]
46    pub system_program: Program<'info, System>,
47
48    #[account()]
49    pub worker: SystemAccount<'info>,
50}
51
52pub fn handler<'info>(ctx: Context<RequestAck>) -> Result<()> {
53    // Get accounts
54    let config = &ctx.accounts.config;
55    let fee = &mut ctx.accounts.fee;
56    let request = &mut ctx.accounts.request;
57    let worker = &mut ctx.accounts.worker;
58
59    // Payout request fee
60    let current_slot = Clock::get().unwrap().slot;
61    let is_authorized_worker = request.workers.contains(&worker.key());
62    let is_within_execution_window = current_slot
63        < request
64            .created_at
65            .checked_add(config.timeout_threshold)
66            .unwrap();
67    if is_authorized_worker && is_within_execution_window {
68        // Pay worker for executing request
69        fee.pay_to_worker(request)?;
70    } else {
71        // Either someone is spamming or this request has timed out. Do not pay worker.
72        // TODO Perhaps rather than being paid to the admin, this could be put in an escrow account where all workers could claim equal rewards.
73        // TODO If not claimed within X slots, the admin can claim their rewards and close the account.
74        fee.pay_to_admin(request)?;
75    }
76
77    Ok(())
78}