1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
use {
    crate::{errors::*, state::*, instructions::utils::*},
    anchor_lang::{
        prelude::*,
        solana_program::{program::invoke, system_instruction, system_program},
    },
    anchor_spl::token::{approve, Approve, Mint, Token, TokenAccount},
    index_program::state::*,
    std::mem::size_of,
};

// TODO consider the defi yield streaming use-case.
// Those protocols don't know ahead of time how many tokens they are going to send (yield is variable),
//  but they generally want to send tokens from a "yield account" at given moment in time 
//  and continue doing so indefinitely (until cancelled).
// The actual amount transfered may be a function of the recipient's ownership % of the pool.
// How can we support that use-case with this interface? 

#[derive(Accounts)]
#[instruction(
    memo: String,
    amount_raw: u64,
    amount_percent: u64,
    recurrence_interval: u64,
    start_at: u64,
    end_at: u64,
    creditor_payment_pointer_bump: u8,
    creditor_payment_proof_bump: u8,
    debtor_payment_pointer_bump: u8,
    debtor_payment_proof_bump: u8,
    payment_bump: u8,
    task_bump: u8,
    task_pointer_bump: u8,
    task_proof_bump: u8,
)]
pub struct CreatePayment<'info> {

    #[account(
        mut, 
        seeds = [SEED_AUTHORITY], 
        bump = authority.bump,
        owner = crate::ID,
    )]
    pub authority: Box<Account<'info, Authority>>,

    pub clock: Sysvar<'info, Clock>,

    #[account(
        seeds = [SEED_CONFIG], 
        bump = config.bump,
        owner = crate::ID,
    )]
    pub config: Box<Account<'info, Config>>,

    pub creditor: AccountInfo<'info>,

    #[account(
        mut,
        constraint = creditor_payment_index.owner == authority.key(),
        constraint = creditor_payment_index.namespace == creditor_payment_namespace.key(),
        owner = index_program.key(),
    )]
    pub creditor_payment_index: Box<Account<'info, Index>>,

    #[account(
        seeds = [
            SEED_PAYMENT_NAMESPACE,
            creditor.key().as_ref(),
            Role::Creditor.to_string().as_bytes(),
        ],
        bump = creditor_payment_namespace.bump,
        owner = crate::ID,
    )]
    pub creditor_payment_namespace: Box<Account<'info, PaymentNamespace>>,

    #[account(mut)]
    pub creditor_payment_pointer: AccountInfo<'info>,

    #[account(mut)]
    pub creditor_payment_proof: AccountInfo<'info>,

    #[account(
        constraint = creditor_tokens.owner == creditor.key(),
        constraint = creditor_tokens.mint == mint.key(),
        owner = token_program.key(),
    )]
    pub creditor_tokens: Box<Account<'info, TokenAccount>>,

    #[account(mut)]
    pub debtor: Signer<'info>,

    #[account(
        mut,
        constraint = debtor_payment_index.owner == authority.key(),
        constraint = debtor_payment_index.namespace == debtor_payment_namespace.key(),
        owner = index_program.key(),
    )]
    pub debtor_payment_index: Box<Account<'info, Index>>,

    #[account(
        seeds = [
            SEED_PAYMENT_NAMESPACE,
            debtor.key().as_ref(),
            Role::Debtor.to_string().as_bytes(),
        ],
        bump = debtor_payment_namespace.bump,
        owner = crate::ID,
    )]
    pub debtor_payment_namespace: Box<Account<'info, PaymentNamespace>>,

    #[account(mut)]
    pub debtor_payment_pointer: AccountInfo<'info>,

    #[account(mut)]
    pub debtor_payment_proof: AccountInfo<'info>,

    #[account(
        mut,
        constraint = debtor_tokens.owner == debtor.key(),
        constraint = debtor_tokens.mint == mint.key(),
        owner = token_program.key(),
    )]
    pub debtor_tokens: Box<Account<'info, TokenAccount>>,

    #[account(address = index_program::ID)]
    pub index_program: Program<'info, index_program::program::IndexProgram>,

    #[account(owner = token_program.key())]
    pub mint: Box<Account<'info, Mint>>,

    #[account(
        init,
        seeds = [
            SEED_PAYMENT,
            debtor.key().as_ref(),
            debtor_payment_index.clone().into_inner().count.to_be_bytes().as_ref()
        ],
        bump = payment_bump,
        payer = debtor,
        space = 8 + size_of::<Payment>(),
    )]
    pub payment: Box<Account<'info, Payment>>,

    #[account(address = system_program::ID)]
    pub system_program: Program<'info, System>,

    #[account(
        init,
        seeds = [
            SEED_TASK, 
            payment.key().as_ref(),
            start_at.to_string().as_bytes()
        ],
        bump = task_bump,
        payer = debtor,
        space = 8 + size_of::<Task>(),
    )]
    pub task: Box<Account<'info, Task>>,

    #[account(
        mut,
        constraint = task_index.owner == authority.key(),
        constraint = task_index.namespace == task_namespace.key(),
        owner = index_program.key()
    )]
    pub task_index: Box<Account<'info, Index>>,

    #[account(
        seeds = [
            SEED_TASK_NAMESPACE,
            start_at.to_string().as_bytes()
        ],
        bump = task_namespace.bump,
        owner = crate::ID,
    )]
    pub task_namespace: Box<Account<'info, TaskNamespace>>,

    #[account(mut)]
    pub task_pointer: AccountInfo<'info>,

    #[account(mut)]
    pub task_proof: AccountInfo<'info>,

    #[account(address = anchor_spl::token::ID)]
    pub token_program: Program<'info, Token>,
}

pub fn handler(
    ctx: Context<CreatePayment>,
    memo: String,
    amount_raw: u64,
    amount_percent: u64,
    recurrence_interval: u64,
    start_at: u64,
    end_at: u64,
    creditor_payment_pointer_bump: u8,
    creditor_payment_proof_bump: u8,
    debtor_payment_pointer_bump: u8,
    debtor_payment_proof_bump: u8,
    payment_bump: u8,
    task_bump: u8,
    task_pointer_bump: u8,
    task_proof_bump: u8,
) -> ProgramResult {

    // Get accounts.
    let authority = &ctx.accounts.authority;
    let config = &ctx.accounts.config;
    let creditor = &ctx.accounts.creditor;
    let creditor_tokens = &ctx.accounts.creditor_tokens;
    let creditor_payment_index = &ctx.accounts.creditor_payment_index;
    let creditor_payment_pointer = &ctx.accounts.creditor_payment_pointer;
    let creditor_payment_proof = &ctx.accounts.creditor_payment_proof;
    let debtor = &mut ctx.accounts.debtor;
    let debtor_payment_index = &ctx.accounts.debtor_payment_index;
    let debtor_payment_pointer = &ctx.accounts.debtor_payment_pointer;
    let debtor_payment_proof = &ctx.accounts.debtor_payment_proof;
    let debtor_tokens = &mut ctx.accounts.debtor_tokens;
    let index_program = &ctx.accounts.index_program;
    let mint = &ctx.accounts.mint;
    let payment = &mut ctx.accounts.payment;
    let system_program = &ctx.accounts.system_program;
    let task = &mut ctx.accounts.task;
    let task_index = &ctx.accounts.task_index;
    let task_pointer = &ctx.accounts.task_pointer;
    let task_proof = &ctx.accounts.task_proof;
    let token_program = &ctx.accounts.token_program;

    // Validate amounts are legible.
    if amount_raw > 0 { 
        require!(amount_percent == 0, ErrorCode::Unknown);  // Raw payment amount
    } else if amount_percent > 0 { 
        require!(amount_raw == 0, ErrorCode::Unknown);      // Percentage payment amount
        require!(amount_percent <= PERCENTAGE_BASE, ErrorCode::Unknown);
    } else {
        return Err(ErrorCode::Unknown.into());              // Invalid payment amount
    }

    // Validate payment chronology.
    match recurrence_interval {
        0 => require!(start_at == end_at, ErrorCode::InvalidChronology), // One-time payment
        _ => require!(start_at <= end_at, ErrorCode::InvalidChronology)  // Recurring payment
    }

    // Validate the recurrence interval is divisible by minutes.
    require!(
        recurrence_interval % ONE_MINUTE == 0,
        ErrorCode::InvalidRecurrenceInterval
    );

    // Calculate expected number of transfers.
    let num_transfers = match recurrence_interval {
        0 => 1,                                         // One-time payment
        _ => (end_at - start_at) / recurrence_interval, // Recurring payment 
    };

    // Calculate the transfer fee. 
    let transfer_fee = num_transfers * (
            config.transfer_fee_distributor + 
            config.transfer_fee_program
        );

    // Validate debtor has sufficient lamports to cover transfer fee.
    require!(
        debtor.to_account_info().lamports() >= transfer_fee,
        ErrorCode::InsufficientBalance
    );

    // Save payment data.
    payment.id = debtor_payment_index.count; 
    payment.amount_raw = amount_raw;
    payment.amount_percent = amount_percent;
    payment.debtor = debtor.key();
    payment.debtor_tokens = debtor_tokens.key();
    payment.creditor = creditor.key();
    payment.creditor_tokens = creditor_tokens.key();
    payment.memo = memo;
    payment.mint = mint.key();
    payment.recurrence_interval = recurrence_interval;
    payment.start_at = start_at;
    payment.end_at = end_at;
    payment.bump = payment_bump;

    // Save task data.
    task.payment = payment.key();
    task.status = TaskStatus::Pending;
    task.transfer_status = TransferStatus::Pending;
    task.process_at = start_at;
    task.bump = task_bump;

    // Authorize payment account to transfer debtor's tokens.
    approve(
        CpiContext::new(
            token_program.to_account_info(),
            Approve {
                authority: debtor.to_account_info(),
                delegate: authority.to_account_info(),
                to: debtor_tokens.to_account_info(),
            },
        ),
        u64::MAX,
    )?;

    // Collect transfer fee from debtor. Hold funds in payment account.
    invoke(
        &system_instruction::transfer(
            &debtor.key(), 
            &payment.key(), 
            transfer_fee
        ),
        &[
            debtor.to_account_info().clone(),
            payment.to_account_info().clone(),
            system_program.to_account_info().clone(),
        ],
    )?;

    // Create pointer to payment in creditor's payment index.
    index_program::cpi::create_pointer(
        CpiContext::new_with_signer(
            index_program.to_account_info(), 
            index_program::cpi::accounts::CreatePointer {
                index: creditor_payment_index.to_account_info(),
                pointer: creditor_payment_pointer.to_account_info(),
                proof: creditor_payment_proof.to_account_info(),
                owner: authority.to_account_info(),
                payer: debtor.to_account_info(),
                system_program: system_program.to_account_info(),
            },
            &[&[SEED_AUTHORITY, &[authority.bump]]]
        ), 
        creditor_payment_index.count.to_string(), 
        payment.key(), 
        creditor_payment_pointer_bump, 
        creditor_payment_proof_bump
    )?;

    // Create pointer to payment in debtor's payment index.
    index_program::cpi::create_pointer(
        CpiContext::new_with_signer(
            index_program.to_account_info(), 
            index_program::cpi::accounts::CreatePointer {
                index: debtor_payment_index.to_account_info(),
                pointer: debtor_payment_pointer.to_account_info(),
                proof: debtor_payment_proof.to_account_info(),
                owner: authority.to_account_info(),
                payer: debtor.to_account_info(),
                system_program: system_program.to_account_info(),
            },
            &[&[SEED_AUTHORITY, &[authority.bump]]]
        ), 
        debtor_payment_index.count.to_string(), 
        payment.key(), 
        debtor_payment_pointer_bump, 
        debtor_payment_proof_bump
    )?;

    // Create pointer to task in index for time window.
    index_program::cpi::create_pointer(
        CpiContext::new_with_signer(
            index_program.to_account_info(), 
            index_program::cpi::accounts::CreatePointer {
                index: task_index.to_account_info(),
                pointer: task_pointer.to_account_info(),
                proof: task_proof.to_account_info(),
                owner: authority.to_account_info(),
                payer: debtor.to_account_info(),
                system_program: system_program.to_account_info(),
            },
            &[&[SEED_AUTHORITY, &[authority.bump]]]
        ), 
        task_index.count.to_string(), 
        task.key(), 
        task_pointer_bump, 
        task_proof_bump
    )?;

    return Ok(());
}