Hierarchy

  • MarginAccount

Constructors

Properties

address: PublicKey

The address of the MarginAccount

airspace: PublicKey

The address of the airspace this account is part of

info?: {
    liquidationData?: LiquidationData;
    marginAccount: MarginAccountData;
    positions: AccountPositionList;
}

The raw accounts associated with the margin account.

Type declaration

owner: PublicKey

The owner of the MarginAccount

poolPositions: Record<string, PoolPosition>

The summarized PoolPosition array of pool deposits and borrows.

pools?: Record<string, Pool>
positions: AccountPosition[]

The parsed AccountPosition array of the margin account.

programs: MarginPrograms
provider: AnchorProvider

The provider and wallet that can sign for this margin account

seed: number
valuation: Valuation

The Valuation of the margin account.

walletTokens?: MarginWalletTokens
RISK_CRITICAL_LEVEL: 0.9 = 0.9
RISK_LIQUIDATION_LEVEL: 1 = 1
RISK_WARNING_LEVEL: 0.8 = 0.8
SEED_MAX_VALUE: 65535 = 65535

The maximum MarginAccount seed value equal to 65535. Seeds are a 16 bit number and therefor only 2^16 margin accounts may exist per wallet.

SETUP_LEVERAGE_FRACTION: Number128 = ...

The maximum risk indicator allowed by the library when setting up a

Accessors

  • get riskIndicator(): number
  • A qualitative measure of the the health of a margin account. A higher value means more risk in a qualitative sense. Properties: non-negative, range is [0, infinity) zero only when an account has no exposure at all account is subject to liquidation at a value of one

    Returns number

Methods

  • Send a transaction to close the MarginAccount and return rent to the owner. All positions must have a zero balance and be closed first.

    Example

    // Close all positions. A non zero balance results in an error
    for (const position of marginAccount.getPositions()) {
    await marginAccount.closePosition(position)
    }

    // Close the account and send the transaction
    await marginAccount.closeAccount()

    Memberof

    MarginAccount

    Returns Promise<void>

  • Send a transaction to close a position. A non-zero balance will result in a transaction error. There is a limited capacity for positions so it is recommended to close positions that are no longer needed.

    Example

    // Load the pools
    const poolManager = new PoolManager(programs, provider)
    const pools = await poolManager.loadAll()

    // Get the SOL position
    const depositNoteMint = pools["SOL"].addresses.depositNoteMint
    const position = marginAccount.getPosition(depositNoteMint)

    await marginAccount.closePosition(position)

    Returns

    Memberof

    MarginAccount

    Parameters

    • position: AccountPosition

    Returns Promise<void>

  • Compute the risk indicator using components from Valuation

    Parameters

    • requiredCollateral: number
    • weightedCollateral: number
    • liabilities: number

    Returns number

  • Create the margin account if it does not exist. If no seed is provided, one will be located.

    Example

    // Load programs
    const config = await MarginClient.getConfig("devnet")
    const programs = MarginClient.getPrograms(provider, config)

    // Load tokens and wallet
    const pools = await poolManager.loadAll()
    const walletTokens = await MarginAccount.loadTokens(programs, walletPubkey)

    // Create margin account
    const marginAccount = new MarginAccount({
    programs,
    provider,
    walletPubkey,
    0,
    pools,
    walletTokens
    })

    await marginAccount.createAccount()

    Returns

    Memberof

    MarginAccount

    Returns Promise<void>

  • Derive the address of a metadata account.

    Remarks

    Some account types such as pools, adapters and position mints have metadata associated with them. The metadata type is determined by the account type.

    Returns

    Memberof

    MarginAccount

    Parameters

    • account: Address

    Returns PublicKey

  • Derive the address of a position token account associated with a MarginAccount and position token mint.

    Remarks

    It is recommended to use other functions to find specfic position types. e.g. using Pool.findDepositPositionAddress

    Returns

    Memberof

    MarginAccount

    Parameters

    • positionTokenMint: Address

    Returns PublicKey

  • Derive the address of the config account for a given token.

    Parameters

    • tokenMint: Address

      The mint address for the token to derive the config address for.

    Returns PublicKey

  • Get the AccountPosition PublicKey and sends a transaction to create it if it doesn't exist.

    Remarks

    It is recommended to use other functions to register specfic position types. e.g. using Pool.withRegisterDepositPosition

    In web apps it's recommended to call withGetOrCreatePosition as part of a larger transaction to prompt for a wallet signature less often.

    Example

    // Load margin pools
    const poolManager = new PoolManager(programs, provider)
    const pools = await poolManager.loadAll()

    const depositNote = pools["SOL"].addresses.depositNoteMint
    await marginAccount.getOrRegisterPosition(depositNote)

    Returns

    Memberof

    MarginAccount

    Parameters

    • tokenMint: Address

    Returns Promise<PublicKey>

  • Get the registerd AccountPosition associated with the position mint. Throws an error if the position does not exist.

    Returns

    Memberof

    MarginAccount

    Parameters

    • mint: Address

      The position mint. For example a Pool deposit note mint.

    Returns AccountPosition

  • Get the registerd AccountPosition associated with the position mint.

    Returns

    Memberof

    MarginAccount

    Parameters

    • mint: Address

      The position mint. For example a Pool deposit note mint.

    Returns undefined | AccountPosition

  • Get the time remaining on a liquidation until timeout in seconds.

    Remarks

    If getRemainingLiquidationTime is a negative number then liquidationEnd can be called by the margin account owner regardless of the current margin account health.

    Returns

    Memberof

    MarginAccount

    Returns undefined | number

  • Check if the given address is an authority for this margin account. The owner has authority, as well as a liquidator only during liquidation.

    Parameters

    • authority: PublicKey

    Returns undefined | boolean

  • Send a transaction to end a liquidation.

    Remarks

    The MarginAccount can enter liquidation while it's riskIndicator is at or above 1.0. Liquidation is in progress when isBeingLiquidated returns true. Liquidation can only end when enough collateral is deposited or enough collateral is liquidated to lower riskIndicator sufficiently.

    Returns

    Memberof

    MarginAccount

    Returns Promise<string>

  • Sends a transaction to refresh the metadata for a position.

    Remarks

    When a position is registered some position mint metadata is copied to the position. This data can become out of sync if the mint metadata is changed. Refreshing the position metadata may at the benefit or detriment to the owner.

    Returns

    Memberof

    MarginAccount

    Parameters

    • {: {
          positionMint: Address;
      }

      positionMint }

      • positionMint: Address

    Returns Promise<string>

  • Sends a transaction to register an AccountPosition for the mint. When registering a Pool position, the mint would not be Bitcoin or SOL, but rather the depositNoteMint or loanNoteMint found in pool.addresses. A margin account has a limited capacity of positions.

    Remarks

    It is recommended to use other functions to register specfic position types. e.g. using Pool.withRegisterDepositPosition

    In web apps it's is recommended to use withRegisterPosition as part of a larget transaction to prompt for a wallet signature less often.

    Example

    // Load the pools
    const poolManager = new PoolManager(programs, provider)
    const pools = await poolManager.loadAll()

    // Register the SOL deposit position
    const depositNoteMint = pools["SOL"].addresses.depositNoteMint
    await marginAccount.registerPosition(depositNoteMint)

    Returns

    Memberof

    MarginAccount

    Parameters

    • tokenMint: Address

    Returns Promise<string>

  • Sends a collection of transactions using the MarginAccount AnchorProvider.

    Remarks

    This function has 2 additional features compared to sendAll from web3.js or anchor.

    • Logging a Transaction error will include Transaction logs.
    • If an Transaction array element is itself a TransactionInstruction[][] this function will send those transactions in parallel.

    Returns

    Memberof

    MarginAccount

    Parameters

    • transactions: (TransactionInstruction[] | TransactionInstruction[][])[]

    Returns Promise<string>

  • Sends a transaction using the MarginAccount AnchorProvider

    Returns

    Memberof

    MarginAccount

    Parameters

    • instructions: TransactionInstruction[]
    • Optional signers: Signer[]

    Returns Promise<string>

  • Parameters

    • instructions: TransactionInstruction[]
    • lookupTables: PublicKey[]
    • Optional signers: Signer[]

    Returns Promise<string>

  • Parameters

    • mint: PublicKey
    • account: PublicKey
    • balance: BN

    Returns undefined | AccountPosition

  • Updates all position balances. withUpdatePositionBalance is often included in transactions after modifying balances to synchronize with the margin account.

    Returns

    Memberof

    MarginAccount

    Returns Promise<string>

  • Updates a single position balance. withUpdatePositionBalance is often included in transactions after modifying balances to synchronize with the margin account.

    Returns

    Memberof

    MarginAccount

    Parameters

    • {: {
          position: AccountPosition;
      }

      position }

      • position: AccountPosition

    Returns Promise<string>

  • Create an instruction to perform an action by invoking other adapter programs, allowing them only to refresh the state of the margin account to be consistent with the actual underlying prices or positions, but not permitting new position changes.

    Remarks

    This instruction is not invoked directly, but rather internally for example by Pool when depositing. Accounting invoke is necessary when several position values have to be refreshed but in the interim there aren't enough fresh positions to satisfy margin requirements.

    Returns

    Memberof

    MarginAccount

    Parameters

    • {: {
          adapterInstruction: TransactionInstruction;
          adapterMetadata?: Address;
          adapterProgram?: Address;
          instructions: TransactionInstruction[];
      }

      instructions, adapterProgram, adapterMetadata, adapterInstruction }

      • adapterInstruction: TransactionInstruction
      • Optional adapterMetadata?: Address
      • Optional adapterProgram?: Address
      • instructions: TransactionInstruction[]

    Returns Promise<void>

  • Create an instruction that performs an action by invoking other adapter programs, allowing them to alter the balances of the token accounts belonging to this margin account. The transaction fails if the MarginAccount does not have sufficent collateral.

    Remarks

    This instruction is not invoked directly, but rather internally for example by Pool when depositing.

    Returns

    Memberof

    MarginAccount

    Parameters

    • {: {
          adapterInstruction: TransactionInstruction;
          instructions: TransactionInstruction[];
      }

      instructions, adapterInstruction }

      • adapterInstruction: TransactionInstruction
      • instructions: TransactionInstruction[]

    Returns Promise<void>

  • Create an instruction to close the MarginAccount and return rent to the owner. All positions must have a zero balance and be closed first.

    Example

    const instructions: TransactionInstruction[] = []

    // Close all positions. A non zero balance results in an error
    for (const position of marginAccount.getPositions()) {
    await marginAccount.withClosePosition(instructions, position)
    }

    // Close the account and send the transaction
    await marginAccount.withCloseAccount(instructions)
    await marginAccount.sendAndConfirm(instructions)

    Returns

    Memberof

    MarginAccount

    Parameters

    • instructions: TransactionInstruction[]

    Returns Promise<void>

  • Create an instruction to close a position. A non-zero balance will result in a transaction error. There is a limited capacity for positions so it is recommended to close positions that are no longer needed.

    Example

    // Load the pools
    const poolManager = new PoolManager(programs, provider)
    const pools = await poolManager.loadAll()

    // Get the SOL position
    const depositNoteMint = pools["SOL"].addresses.depositNoteMint
    const position = marginAccount.getPosition(depositNoteMint)

    const instructions: TransactionInstruction[] = []
    await marginAccount.closePosition(instructions, position)
    await marginAccount.sendAndConfirm(instructions)

    Returns

    Memberof

    MarginAccount

    Parameters

    • instructions: TransactionInstruction[]
    • position: AccountPosition

    Returns Promise<void>

  • Get instruction to create the account if it does not exist.

    Example

    const instructions: TransactionInstruction[] = []
    await marginAccount.withCreateAccount(instructions)
    if (instructions.length > 0) {
    await marginAccount.sendAndConfirm(instructions)
    }

    Returns

    Memberof

    MarginAccount

    Parameters

    • instructions: TransactionInstruction[]

    Returns Promise<void>

  • Get instruction to create a new deposit position

    Remarks

    A deposit position are tokens deposited directly into a margin account, without the use of any other programs (like pools).

    Returns

    Returns the address of the token account to be created for the position.

    Parameters

    • args: {
          instructions: TransactionInstruction[];
          tokenMint: Address;
      }
      • instructions: TransactionInstruction[]

        Instructions array to append to.

      • tokenMint: Address

        The mint for the relevant token for the position

    Returns Promise<PublicKey>

  • Get the AccountPosition PublicKey and appends an instructon to create it if it doesn't exist.

    Remarks

    It is recommended to use other functions to register specfic position types. e.g. using Pool.withRegisterDepositPosition

    Example

    // Load margin pools
    const poolManager = new PoolManager(programs, provider)
    const pools = await poolManager.loadAll()

    // Register position
    const positionTokenMint = pools["SOL"].addresses.depositNoteMint
    const instructions: TransactionInstruction[] = []
    await marginAccount.withGetOrRegisterPosition({ instructions, positionTokenMint })
    await marginAccount.sendAndConfirm(instructions)

    Returns

    Memberof

    MarginAccount

    Parameters

    • args: {
          instructions: TransactionInstruction[];
          positionTokenMint: Address;
      }
      • instructions: TransactionInstruction[]

        The instructions to append to

      • positionTokenMint: Address

        The position mint to register a position for

    Returns Promise<PublicKey>

  • Get instruction to end a liquidation

    Remarks

    The MarginAccount can enter liquidation while it's riskIndicator is at or above 1.0. Liquidation is in progress when isBeingLiquidated returns true.

    Authority

    The MarginAccount.provider.wallet will be used as the authority for the transaction. The liquidator may end the liquidation at any time. The margin account owner may end the liquidation only when at least one condition is true:

    1. When enough collateral is deposited or enough collateral is liquidated to lower riskIndicator sufficiently.
    2. When the liquidation has timed out when MarginAccount.getRemainingLiquidationTime() is negative

    Returns

    Memberof

    MarginAccount

    Parameters

    • instructions: TransactionInstruction[]

      The instructions to append to

    Returns Promise<void>

  • Creates an instruction to refresh the metadata for a position.

    Remarks

    When a position is registered some position mint metadata is copied to the position. This data can become out of sync if the mint metadata is changed. Refreshing the position metadata may at the benefit or detriment to the owner.

    Returns

    Memberof

    MarginAccount

    Parameters

    • {: {
          instructions: TransactionInstruction[];
          positionMint: Address;
      }

      instructions, positionMint }

      • instructions: TransactionInstruction[]
      • positionMint: Address

    Returns Promise<void>

  • Get instruction to register new position

    Remarks

    It is recommended to use other functions to register specfic position types. e.g. using Pool.withRegisterDepositPosition

    Example

    // Load the pools
    const poolManager = new PoolManager(programs, provider)
    const pools = await poolManager.loadAll()

    // Register the SOL deposit position
    const positionTokenMint = pools["SOL"].addresses.depositNoteMint
    const instructions: TransactionInstruction[] = []
    const position = await marginAccount.withRegisterPosition({ instructions, positionTokenMint })
    await marginAccount.sendAndConfirm(instructions)

    Returns

    Returns the instruction, and the address of the token account to be created for the position.

    Memberof

    MarginAccount

    Parameters

    • args: {
          instructions: TransactionInstruction[];
          positionTokenMint: Address;
      }
      • instructions: TransactionInstruction[]

        Instructions array to append to.

      • positionTokenMint: Address

        The mint for the relevant token for the position

    Returns Promise<PublicKey>

  • Get instruction to end a liquidation

    Deprecated

    This has been renamed to withLiquidateEnd and will be removed in a future release.

    Parameters

    • instructions: TransactionInstruction[]

    Returns Promise<void>

  • Create instructions to update all position balances. withUpdatePositionBalance often included in transactions after modifying balances ot synchronize with the margin account.

    Example

    const instructions: TransactionInstruction[] = []
    await marginAccount.withUpdateAllPositionBalances({ instructions })
    await marginAccount.sendAndConfirm(instructions)

    Memberof

    MarginAccount

    Parameters

    • {: {
          instructions: TransactionInstruction[];
      }

      instructions }

      • instructions: TransactionInstruction[]

    Returns Promise<void>

  • Get instruction to update the accounting for assets in the custody of the margin account.

    Example

    // Load the pools
    const poolManager = new PoolManager(programs, provider)
    const pools = await poolManager.loadAll()

    // Find the position
    const depositNote = pools["SOL"].addresses.depositNoteMint
    const position = marginAccount.getPosition(depositNote).address

    // Update the position balance
    const instructions: TransactionInstruction[] = []
    await marginAccount.withUpdatePositionBalance({ instructions, position })
    await marginAccount.sendAndConfirm(instructions)

    Returns

    {Promise}

    Memberof

    MarginAccount

    Parameters

    • {: {
          instructions: TransactionInstruction[];
          position: Address;
      }

      instructions, position }

      • instructions: TransactionInstruction[]
      • position: Address

    Returns Promise<void>

  • Create the margin account if it does not exist. If no seed is provided, one will be located.

    Example

    // Load programs
    const config = await MarginClient.getConfig("devnet")
    const programs = MarginClient.getPrograms(provider, config)

    // Load tokens and wallet
    const pools = await poolManager.loadAll()
    const walletTokens = await MarginAccount.loadTokens(programs, walletPubkey)

    // Create margin account
    const marginAccount = await MarginAccount.createAccount({
    programs,
    provider,
    owner: wallet.publicKey,
    seed: 0,
    pools,
    walletTokens
    })

    Static

    Returns

    Memberof

    MarginAccount

    Parameters

    • args: {
          owner: Address;
          pools?: Record<string, Pool>;
          programs: MarginPrograms;
          provider: AnchorProvider;
          seed?: number;
          walletTokens?: MarginWalletTokens;
      }
      • owner: Address

        The address of the MarginAccount owner

      • Optional pools?: Record<string, Pool>

        A Pool collection to calculate pool positions.

      • programs: MarginPrograms
      • provider: AnchorProvider

        A provider that may be used to sign transactions modifying the account

      • Optional seed?: number

        The seed or ID of the MarginAccount in the range of (0, 65535]

      • Optional walletTokens?: MarginWalletTokens

        The tokens in the owners wallet to determine max trade amounts.

    Returns Promise<MarginAccount>

  • Searches for a margin account that does not exist yet and returns its seed.

    Static

    Memberof

    MarginAccount

    Parameters

    • __namedParameters: {
          owner: Address;
          programs: MarginPrograms;
          provider: AnchorProvider;
      }

    Returns Promise<number>

  • Load all margin accounts for a wallet with an optional filter.

    Static

    Returns

    Memberof

    MarginAccount

    Parameters

    • {: {
          filters?: GetProgramAccountsFilter[];
          owner: Address;
          pools?: Record<string, Pool>;
          programs: MarginPrograms;
          provider: AnchorProvider;
          walletTokens?: MarginWalletTokens;
      }

      programs, provider, pools, walletTokens, filters }

      • Optional filters?: GetProgramAccountsFilter[]
      • owner: Address
      • Optional pools?: Record<string, Pool>
      • programs: MarginPrograms
      • provider: AnchorProvider
      • Optional walletTokens?: MarginWalletTokens

    Returns Promise<MarginAccount[]>

Generated using TypeDoc