Interacting with Port Finance via Rust

We have two crates for interacting with Port Finance program via Rust:

Token-lending program

A lending protocol for the Token program on the Solana blockchain inspired by Aave and Compound.

Public Keys for Port Finance

Mainnet

Lending Market: 6T4XxKerq744sSuj3jaoV6QiZ8acirf4TrPwQzHAoSy5 Lending program id: port_variable_rate_lending_instructions::id() Staking program id: port_staking_instructions::id()

Reserve Public Keys

You can get all the information below by parsing the reserve data. We provide the account data here for your convenience.

pToken Mint

Oracle Public Keys

Supply Public Keys

Dev Net

Lending Program id: pdQ2rQQU5zH2rDgZ7xH2azMBJegUzUyunJ5Jd637hC4

Staking program id: port_staking_instructions::id()

Lending Market: H27Quk3DSbu55T4dCr1NddTTSAezXwHU67FPCZVKLhSW

Reserve Public Keys

You can get all the information below by parsing the reserve data. We provide the account data here for your convenience.

Fake token Mint

pToken Mint

Oracle Public Keys

Supply Public Keys

Create StakeAccount

For assets that have liquidity mining reward, you need to first create a stake account in order to collateralize and get the reward.

First, get the data of the reserve you want deposit into and unpack it to get the field reserve.config.deposit_staking_pool which is the staking pool id, and generates the seed and keypair by using the Solana built in sha256 hashing function solana_sdk::hash::hashv(&[owner.as_ref(), staking_pool.as_ref(), staking_program_id.as_ref()]), where the owner should be your wallet's public key, and generate the keypair for stake account by solana_sdk::signer::keypair::keypair_from_seed.

Then call create_account and create_stake_account instruction to create the stake account. Owner need to sign the instruction of claiming reward. If you are using a program to create the stake account, you can use an PDA account. Actually, you can use any address to create the stake account, as long as you make sure that there is a one-one mapping between (owner, staking_pool) and stake_account, which means that for every owner and staking_pool, you only have one stake account.

let account_seed = hashv( & [owner.as_ref(), staking_pool.as_ref(), staking_program_id.as_ref()]);
let stake_account_key_pair = keypair_from_seed(account_seed.as_ref()).unwrap();
let instructions = vec![
    create_account(
        &payer.pubkey(),
        &stake_account_key_pair.pubkey(),
        stake_account_rent,
        StakeAccount::LEN as u64,
        &staking_program_id
    ),
    create_stake_account(
        staking_program_id,
        stake_account_key_pair.pubkey(),
        staking_pool,
        owner
    )
];

Refresh Reserves and Obligation

Assuming that you already have your stake account or you are depositing to a reserve without liquidity mining reward, you need to refresh all the reserves the obligation has interacted with and the obligation itself in the same instruction before you depositing / withdrawing / repaying / liquidating.

let mut refresh_instructions = vec![];
//reserve_map is a map of reserve pubkey of reserve data, you can get the oracle pubkey from the reserve data or can hard code it in a config file.
let to_refresh = reserve_map.iter().filter( | (k, _) | {
        obligation
        .borrows
        .iter()
        .map(| li | li.borrow_reserve)
        .chain(obligation.deposits.iter().map(| ob | ob.deposit_reserve))
        .any( | r | r == * * k)
    });
refresh_instructions.extend(
    to_refresh.map( | (k, v) | refresh_reserve(lending_program_id, * k, v.liquidity.oracle_pubkey)),
);
refresh_instructions.push(
    refresh_obligation(
        program_id,
        obligation_pubkey,
        obligation
        .deposits
        .iter()
        .map(|d| d.deposit_reserve)
        .chain(obligation.borrows.iter().map(|b| b.borrow_reserve))
        .collect(),
    )
);

Initialize Obligation

let mut transaction = Transaction::new_with_payer(
    &[
        create_account(
            &payer.pubkey(),
            &obligation_keypair.pubkey(),
            rent.minimum_balance(Obligation::LEN),
            Obligation::LEN as u64,
            &port_finance_variable_rate_lending::id(),
        ),
        init_obligation(
            port_finance_variable_rate_lending::id(),
            obligation.pubkey,
            lending_market.pubkey,
            user_accounts_owner.pubkey(),
        ),
    ],
    Some( & payer.pubkey()),
);

Deposit Liquidity / Collateralize

deposit_reserve_liquidity(
    port_variable_rate_lending::id(),
    liquidity_amount,
    user_liquidity_token_account_pubkey,
    user_collateral_token_account_pubkey,
    reserve_pubkey,
    reserve.liquidity.supply_pubkey,
    reserve.collateral.mint_pubkey,
    self.pubkey,
    user_transfer_authority.pubkey()
)
deposit_obligation_collateral(
    port_variable_rate_lending::id(),
    liquidity_amount,
    user_collateral_token_account_pubkey,
    reserve.collateral.supply_pubkey,
    reserve_pubkey,
    obligation_pubkey,
    lending_market.pubkey,
    obligation.owner,
    user_transfer_authority.pubkey(),
    Some(stake_account_pubkey),
    Some(staking_pool_pubkey),
)
deposit_reserve_liquidity_and_obligation_collateral(
    port_variable_rate_lending::id(),
    liquidity_amount,
    user_liquidity_token_account_pubkey,
    user_collateral_token_account_pubkey,
    reserve_pubkey,
    reserve.liquidity.supply_pubkey,
    reserve.collateral.mint_pubkey,
    lending_market_pubkey,
    reserve.collateral.supply_pubkey,
    obligation_pubkey,
    obligation.owner,
    user_transfer_authority.pubkey(),
    Some(stake_account_pubkey),
    Some(staking_pool_pubkey),
)

Withdraw

There will be a coming withdrawAndRedeem instruction soon, while it is under auditing. So now, you need first uncollateralized the asset then withdraw.

withdraw_obligation_collateral(
    port_finance_variable_rate_lending::id(),
    WITHDRAW_AMOUNT,
    reserve.collateral.supply_pubkey,
    sol_test_reserve.user_collateral_pubkey,
    sol_test_reserve.pubkey,
    test_obligation.pubkey,
    lending_market.pubkey,
    test_obligation.owner,
    Some(stake_account_pubkey),
    Some(staking_pool_pubkey),
)
redeem_reserve_collateral(
    port_finance_variable_rate_lending::id(),
    COLLATERAL_AMOUNT,
    user_collateral_token_account_pubkey,
    user_liquidity_token_account_pubkey,
    reserve_pubkey,
    reserve.collateral.mint_pubkey,
    reserve.liquidity.supply_pubkey,
    lending_market.pubkey,
    user_transfer_authority.pubkey(),
)

Repay

To repay, you can pass number greater then amount you borrow to repay all, for example you can pass u64::MAX in to repay all.

repay_obligation_liquidity(
    port_finance_variable_rate_lending::id(),
    liquidity_amount,
    user_liquidity_token_account_pubkey,
    reserve.liquidity.supply_pubkey,
    reserve_pubkey,
    obligation_pubkey,
    lending_market.pubkey,
    user_transfer_authority.pubkey(),
)

Liquidation

Please refer to https://github.com/port-finance/liquidator

Flash loan

We have an instruction with the following signature for flash loan:

pub enum LendingInstruction {
    // ....
    /// Make a flash loan.
    ///
    /// Accounts expected by this instruction:
    ///
    ///   0. `[writable]` Source liquidity token account.
    ///                     Minted by reserve liquidity mint.
    ///                     Must match the reserve liquidity supply.
    ///   1. `[writable]` Destination liquidity token account.
    ///                     Minted by reserve liquidity mint.
    ///   2. `[writable]` Reserve account.
    ///   3. `[]` Lending market account.
    ///   4. `[]` Derived lending market authority.
    ///   5. `[]` Flash loan receiver program account.
    ///             Must implement an instruction that has tag of 0 and a signature of `(repay_amount: u64)`
    ///             This instruction must return the amount to the source liquidity account.
    ///   6. `[]` Token program id.
    ///   7. `[writable]` Flash loan fee receiver account.
    ///                     Must match the reserve liquidity fee receiver.
    ///   8. `[writable]` Host fee receiver.
    ///   .. `[any]` Additional accounts expected by the receiving program's `ReceiveFlashLoan` instruction.
    FlashLoan {
        /// The amount that is to be borrowed
        amount: u64,
    },
}

In the implementation, we do the following in order:

  1. Perform safety checks and calculate fees

  2. Transfer amount from the source liquidity account to the destination liquidity account

  3. Call the ReceiveFlashLoan function (the flash loan receiver program is required to have this function with tag 0).

    The additional account required for ReceiveFlashLoan is given from the 10th account of the FlashLoan instruction, i.e. after host fee receiver.

  4. Check that the returned amount with the fee is in the reserve account after the completion of ReceiveFlashLoan function.

The flash loan receiver program should have a ReceiveFlashLoan instruction which executes the user-defined operation and return the funds to the reserve in the end.

pub enum FlashLoanReceiverInstruction {

    /// Receive a flash loan and perform user-defined operation and finally return the fund back.
    ///
    /// Accounts expected:
    ///
    ///   0. `[writable]` Source liquidity (matching the destination from above).
    ///   1. `[writable]` Destination liquidity (matching the source from above).
    ///   2. `[]` Token program id
    ///   .. `[any]` Additional accounts provided to the lending program's `FlashLoan` instruction above.
    ReceiveFlashLoan {
        // Amount that is loaned to the receiver program
        amount: u64
    }
}

You can view a sample implementation here.

Last updated