借款
借款指令是我們閃電貸系統的第一部分。它執行三個關鍵步驟以確保安全和原子性貸款:
資金轉移:將請求的
borrow_amount從協議的金庫轉移到借款人的賬戶驗證還款:使用指令內省來確認交易結尾處存在有效的還款指令
資金轉移
首先,我們通過適當的驗證實現資金的實際轉移:
rust
// Make sure we're not sending in an invalid amount that can crash our Protocol
require!(borrow_amount > 0, ProtocolError::InvalidAmount);
// Derive the Signer Seeds for the Protocol Account
let seeds = &[
b"protocol".as_ref(),
&[ctx.bumps.protocol]
];
let signer_seeds = &[&seeds[..]];
// Transfer the funds from the protocol to the borrower
transfer(
CpiContext::new_with_signer(
ctx.accounts.token_program.to_account_info(),
Transfer {
from: ctx.accounts.protocol_ata.to_account_info(),
to: ctx.accounts.borrower_ata.to_account_info(),
authority: ctx.accounts.protocol.to_account_info(),
},
signer_seeds
),
borrow_amount
)?;此代碼確保我們正在轉移有效的金額,並使用協議的程序派生地址 (PDA) 授權轉移。
指令內省
現在進入安全性關鍵部分:使用指令內省來驗證交易結構並確保我們的閃電貸將被還款。
我們首先訪問instructions sysvar,其中包含當前交易中所有指令的信息:
rust
/*
Instruction Introspection
This is the primary means by which we secure our program,
enforce atomicity while making a great UX for our users.
*/
let ixs = ctx.accounts.instructions.to_account_info();最後,我們執行最關鍵的檢查:確保交易中的最後一個指令是一個有效的還款指令:
我們首先檢查借款指令的位置以確保它是唯一的
然後我們檢查指令的數量,確保我們正在加載交易的最後一個指令
接著我們通過驗證指令的程序 ID 和指令的識別符來確認它是還款指令
最後,我們驗證還款指令中傳遞的 ATA 與我們在
Borrow指令中傳遞的 ATA 相同
rust
/*
Repay Instruction Check
Make sure that the last instruction of this transaction is a repay instruction
*/
// Check if this is the first instruction in the transaction.
let current_index = load_current_index_checked(&ctx.accounts.sysvar_instructions)?;
require_eq!(current_index, 0, ProtocolError::InvalidIx);
// Check how many instruction we have in this transaction
let instruction_sysvar = ixs.try_borrow_data()?;
let len = u16::from_le_bytes(instruction_sysvar[0..2].try_into().unwrap());
// Ensure we have a repay ix
if let Ok(repay_ix) = load_instruction_at_checked(len as usize - 1, &ixs) {
// Instruction checks
require_keys_eq!(repay_ix.program_id, ID, ProtocolError::InvalidProgram);
require!(repay_ix.data[0..8].eq(instruction::Repay::DISCRIMINATOR), ProtocolError::InvalidIx);
// We could check the Wallet and Mint separately but by checking the ATA we do this automatically
require_keys_eq!(repay_ix.accounts.get(3).ok_or(ProtocolError::InvalidBorrowerAta)?.pubkey, ctx.accounts.borrower_ata.key(), ProtocolError::InvalidBorrowerAta);
require_keys_eq!(repay_ix.accounts.get(4).ok_or(ProtocolError::InvalidProtocolAta)?.pubkey, ctx.accounts.protocol_ata.key(), ProtocolError::InvalidProtocolAta);
} else {
return Err(ProtocolError::MissingRepayIx.into());
}