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
use anchor_lang::prelude::*;
use std::mem::size_of;

declare_id!("6t7fjmgyNdoMJMftaZin9w2n6YGSB8tHbFvu22bqh1EY");

/**
 * The Cross And Pile Program (P2P Heads or Tails)
 * 
 * Accounts:
 * requester: PDA owned by the Solrand Program used to store data
 * oracle: The Oracle's account. Refer to Published Addreses.
 * oracle_vault: PDA owned by the Solrand Program for paying Oracle
 * solrand_program: The Program Address for the Solrand Program
 * coin: PDA owned by Cross & Pile used for storing data
 * vault: PDA owned by Cross & Pile used for escrowing sol and paying winner
 * initiator: The account creating the coin
 * acceptor: The account accepting the offer to flip
 * rent: The Rent Program
 * system_program: The System Program
 * 
 * Considerations:
 * 1. The CPI call to RequestRandom should happen only after or all funds are locked into the contract.
 * 2. Once a CPI call to RequestRandom is made, no funds should be allowed to be withdrawn.
 * 
 */


#[program]
pub mod cross_pile {
    use super::*;

    pub fn create_coin(
        ctx: Context<CreateCoin>,
        coin_bump: u8,
        _req_bump: u8,
        vault_bump: u8,
        amount: u64,
    ) -> ProgramResult {
        let authority_key = ctx.accounts.initiator.key();
        // Set data for PDAs
        { 
            let coin = &mut ctx.accounts.coin.load_init()?;
            let clock: Clock = Clock::get().unwrap();
            
            coin.initiator = authority_key;
            coin.acceptor = ctx.accounts.acceptor.key();
            coin.is_flipping = false;
            coin.created_at = clock.unix_timestamp;
            coin.bump = coin_bump;

            let vault = &mut ctx.accounts.vault;
            vault.amount = amount;
            vault.bump = vault_bump;
        }

        // Transfer authority for the oracle requester to the Coin PDA
        let cpi_accounts = solrandhypn::cpi::accounts::TransferAuthority {
            requester: ctx.accounts.requester.to_account_info(),
            authority: ctx.accounts.initiator.to_account_info(),
            new_authority: ctx.accounts.coin.to_account_info(),
            system_program: ctx.accounts.system_program.to_account_info()
        };	

        let cpi_context = CpiContext::new(
            ctx.accounts.solrand_program.clone(),
            cpi_accounts
        );

        solrandhypn::cpi::transfer_authority(cpi_context)?;

        // Transfer sol from Initiator to Vault PDA
        let ix = anchor_lang::solana_program::system_instruction::transfer(
            &ctx.accounts.initiator.key(),
            &ctx.accounts.vault.key(),
            amount,
        );

        anchor_lang::solana_program::program::invoke(
            &ix,
            &[
                ctx.accounts.initiator.to_account_info(),
                ctx.accounts.vault.to_account_info(),
                ctx.accounts.system_program.to_account_info(),
            ],
        )?;

        Ok(())
    }


    pub fn approve_flip<'key, 'accounts, 'remaining, 'info>(
        ctx: Context<'key, 'accounts, 'remaining, 'info, ApproveFlip<'info>>
    ) -> ProgramResult {
        // Transfer sol from Acceptor to Vault PDA
        {
            let ix = anchor_lang::solana_program::system_instruction::transfer(
                &ctx.accounts.authority.key(),
                &ctx.accounts.vault.key(),
                ctx.accounts.vault.amount,
            );

            anchor_lang::solana_program::program::invoke(
                &ix,
                &[
                    ctx.accounts.authority.to_account_info(),
                    ctx.accounts.vault.to_account_info(),
                    ctx.accounts.system_program.to_account_info(),
                ],
            )?;
        }

        // Use Coin PDA to Request Random From Oracle
        let coin_acc = &ctx.remaining_accounts[0];

        let cpi_accounts = solrandhypn::cpi::accounts::RequestRandom {
            requester: ctx.accounts.requester.to_account_info(),
            vault: ctx.accounts.oracle_vault.clone(),
            authority: coin_acc.to_account_info(),
            oracle: ctx.accounts.oracle.to_account_info(),
            system_program: ctx.accounts.system_program.to_account_info()
        };

        let (_coin_authority, coin_bump) =
            Pubkey::find_program_address(&[b"coin-seed".as_ref(), ctx.accounts.initiator.key.as_ref()], &ctx.program_id);

        let coin_seeds = &[
            b"coin-seed".as_ref(),
            ctx.accounts.initiator.key.as_ref(),
            &[coin_bump]
        ];

        let signer = &[
            &coin_seeds[..]
        ];

        let cpi_context = CpiContext::new_with_signer(
            ctx.accounts.solrand_program.clone(),
            cpi_accounts,
            signer
        );

        solrandhypn::cpi::request_random(cpi_context)?;

        Ok(())
    }

    pub fn reveal_coin<'key, 'accounts, 'remaining, 'info>(
        ctx: Context<'key, 'accounts, 'remaining, 'info, RevealCoin<'info>>
    ) -> ProgramResult {
        {
            let authority_key = ctx.accounts.authority.key();

            if authority_key != ctx.accounts.initiator.key() && authority_key != ctx.accounts.acceptor.key() {
                return Err(ErrorCode::Unauthorized.into());
            }
        }
        // Determine winner from random number & transfer prize
        {
            let requester_loader: AccountLoader<solrandhypn::Requester> = AccountLoader::try_from_unchecked(ctx.program_id, &ctx.accounts.requester).unwrap();
            let requester = requester_loader.load()?;
            let mut winner = ctx.accounts.initiator.clone();

            if requester.active_request {
                return Err(ErrorCode::OracleNotCompleted.into());
            }

            // Take first byte (u8) and check if even
            // Even random => acceptor wins & initiator loses
            if requester.random[0] % 2 == 0 {
                winner = ctx.accounts.acceptor.clone();
            }

            **winner.try_borrow_mut_lamports()? += ctx.accounts.vault.to_account_info().lamports();
            **ctx.accounts.vault.to_account_info().try_borrow_mut_lamports()? = 0;
        }

        // Transfer back ownership of requester
        let coin_acc = &ctx.remaining_accounts[0];

        let cpi_accounts = solrandhypn::cpi::accounts::TransferAuthority {
            requester: ctx.accounts.requester.to_account_info(),
            authority: coin_acc.to_account_info(),
            new_authority: ctx.accounts.initiator.to_account_info(),
            system_program: ctx.accounts.system_program.to_account_info()
        };

        let (_coin_authority, coin_bump) =
            Pubkey::find_program_address(&[b"coin-seed".as_ref(), ctx.accounts.initiator.key.as_ref()], &ctx.program_id);

        let coin_seeds = &[
            b"coin-seed".as_ref(),
            ctx.accounts.initiator.key.as_ref(),
            &[coin_bump]
        ];

        let signer = &[
            &coin_seeds[..]
        ];

        let cpi_context = CpiContext::new_with_signer(
            ctx.accounts.solrand_program.clone(),
            cpi_accounts,
            signer
        );

        solrandhypn::cpi::transfer_authority(cpi_context)?;

        return Ok(());
    }
}

#[derive(Accounts)]
#[instruction(coin_bump: u8, req_bump: u8, vault_bump: u8)]
pub struct CreateCoin<'info> {
    #[account(
        init, 
        seeds = [b"coin-seed".as_ref(), initiator.key().as_ref()],
        bump = coin_bump,
        payer = initiator,
        space = 8 + size_of::<Coin>()
    )]
    pub coin: AccountLoader<'info, Coin>,
    #[account(
        init, 
        seeds = [b"vault-seed".as_ref(), initiator.key().as_ref()],
        bump = vault_bump,
        payer = initiator,
        space = 8 + size_of::<Vault>()
    )]
    pub vault: Account<'info, Vault>,
    #[account(mut)]
    pub requester: AccountInfo<'info>,
    #[account(mut, signer)]
    pub initiator: AccountInfo<'info>,
    pub acceptor: AccountInfo<'info>,
    pub oracle: AccountInfo<'info>,
    pub oracle_vault: AccountInfo<'info>,
    pub solrand_program: AccountInfo<'info>,
    pub rent: Sysvar<'info, Rent>,
    pub system_program: Program<'info, System>,
}

#[derive(Accounts)]
pub struct ApproveFlip<'info> {
    #[account(mut, signer)]
    pub authority: AccountInfo<'info>,
    #[account(mut)]
    pub vault: Account<'info, Vault>,
    pub initiator: AccountInfo<'info>,
    #[account(mut)]
    pub requester: AccountInfo<'info>,
    #[account(mut)]
    pub oracle: AccountInfo<'info>,
    #[account(mut)]
    pub oracle_vault: AccountInfo<'info>,
    pub solrand_program: AccountInfo<'info>,
    pub system_program: Program<'info, System>,
}

#[derive(Accounts)]
pub struct RevealCoin<'info> {
    #[account(mut)]
    pub initiator: AccountInfo<'info>,
    #[account(mut)]
    pub acceptor: AccountInfo<'info>,
    #[account(mut)]
    pub vault: Account<'info, Vault>,
    #[account(mut)]
    pub requester: AccountInfo<'info>,
    #[account(mut, signer)]
    pub authority: AccountInfo<'info>,
    pub solrand_program: AccountInfo<'info>,
    pub system_program: Program<'info, System>,
}

// Used for signing CPI to oracle
#[account(zero_copy)]
pub struct Coin {
    pub initiator: Pubkey,
    pub acceptor: Pubkey,
    pub is_flipping: bool,
    pub is_cross: bool,
    pub created_at: i64,
    pub bump: u8,
}

// Used for holding the sol balance and transfering to winner
#[account]
pub struct Vault {
    pub amount: u64,
    pub bump: u8,
}

#[error]
pub enum ErrorCode {
    #[msg("You are not authorized to complete this transaction")]
    Unauthorized,
    #[msg("The coin is has already been flipped")]
    AlreadyCompleted,
    #[msg("A coin is already flipping. Only one flip may be made at a time")]
    InflightRequest,
    #[msg("The Oracle has not provided a response yet")]
    OracleNotCompleted,
}