|
1 |
| -use crate::traits::PSP22; |
| 1 | +use crate::{ |
| 2 | + extensions::PSP3156FlashBorrowerStub, |
| 3 | + traits::{ |
| 4 | + PSP22Error, |
| 5 | + PSP22, |
| 6 | + }, |
| 7 | +}; |
2 | 8 | use brush::traits::{
|
3 | 9 | AccountId,
|
4 | 10 | Balance,
|
5 | 11 | };
|
| 12 | +use ink_lang::ToAccountId; |
6 | 13 | use ink_prelude::vec::Vec;
|
7 | 14 |
|
8 | 15 | #[brush::trait_definition]
|
9 |
| -pub trait PSP22FlashMint: PSP22 + PSP3156FlashBorrower {} |
| 16 | +pub trait PSP22FlashMint: PSP22 + PSP3156FlashBorrower { |
| 17 | + const RETURN_VALUE: [u8; 32] = brush::blake2b_256!("PSP3156FlashBorrower.onFlashLoan"); |
| 18 | + |
| 19 | + #[ink(message)] |
| 20 | + fn max_flashloan(&mut self, token: AccountId) -> Balance { |
| 21 | + if token == Self::env().account_id() { |
| 22 | + Balance::MAX - self.total_supply() |
| 23 | + } else { |
| 24 | + 0 |
| 25 | + } |
| 26 | + } |
| 27 | + |
| 28 | + #[ink(message)] |
| 29 | + fn flash_fee(&mut self, token: AccountId, _amount: Balance) -> Balance { |
| 30 | + assert_eq!( |
| 31 | + token, |
| 32 | + Self::env().account_id(), |
| 33 | + "{}", |
| 34 | + PSP22Error::Custom(String::from("Wrong token")).as_ref() |
| 35 | + ); |
| 36 | + 0 |
| 37 | + } |
| 38 | + |
| 39 | + #[ink(message)] |
| 40 | + fn flashloan( |
| 41 | + &mut self, |
| 42 | + receiver: &mut PSP3156FlashBorrowerStub, |
| 43 | + token: AccountId, |
| 44 | + amount: Balance, |
| 45 | + data: Vec<u8>, |
| 46 | + ) -> Result<(), PSP22Error> { |
| 47 | + let receiver_account = receiver.to_account_id(); |
| 48 | + let fee = self.flash_fee(token, amount); |
| 49 | + self._mint(receiver_account, amount); |
| 50 | + if receiver.on_flash_loan(Self::env().caller(), token, amount, fee, data) != Self::RETURN_VALUE { |
| 51 | + return Err(PSP22Error::Custom(String::from("Invalid return value"))) |
| 52 | + } |
| 53 | + let current_allowance = self.allowance(receiver_account, Self::env().account_id()); |
| 54 | + if current_allowance < amount + fee { |
| 55 | + return Err(PSP22Error::Custom(String::from("Allowance does not allow refund"))) |
| 56 | + } |
| 57 | + self._approve_from_to( |
| 58 | + receiver_account, |
| 59 | + Self::env().account_id(), |
| 60 | + current_allowance - amount - fee, |
| 61 | + )?; |
| 62 | + self._burn(receiver_account, amount + fee); |
| 63 | + Ok(()) |
| 64 | + } |
| 65 | +} |
10 | 66 |
|
11 | 67 | #[brush::trait_definition]
|
12 | 68 | pub trait PSP3156FlashBorrower {
|
|
0 commit comments