import * as anchor from "@project-serum/anchor"; import idl from "../idl/covered_call_vault.json"; import { CoveredCallVault } from "../types/covered_call_vault"; import { Network } from "../common/network"; import { PublicKey, Connection, ConfirmOptions, Transaction, AccountMeta, ComputeBudgetProgram, TransactionInstruction, } from "@solana/web3.js"; import { getAccount, getAssociatedTokenAddress, createAssociatedTokenAccountInstruction, } from "@solana/spl-token"; import { TransactionMethodReturnData, DummyWallet, Wallet, } from "./../common/types"; import * as utils from "./../common/utils"; import * as vaultUtils from "./utils"; import * as instructions from "./instructions"; import { Program } from "../common/program"; import * as programTypes from "./program-types"; import * as types from "./types"; import { flex as Flex } from "../flex/flex"; import { Auction, Option, Bid, FlexOptionType } from "../flex/types"; import * as flexUtils from "../flex/flex-utils"; import { VaultEvent, DepositEvent } from "./events"; import * as vaultConstants from "./constants"; export class Vault { public get isInitialized(): boolean { return this._isInitialized; } private _isInitialized: boolean; /** * Anchor program instance. await utils.processTransaction(Program.VAULT, this._provider, tx); */ public get program(): anchor.Program { return this._program; } private _program: anchor.Program; public get programId(): PublicKey { return this._program.programId; } /** * Anchor provider instance. */ public get provider(): anchor.AnchorProvider { return this._provider; } private _provider: anchor.AnchorProvider; public get network(): Network { return this._network; } private _network: Network; public get stateAddress(): PublicKey { return this._stateAddress; } private _stateAddress: PublicKey; public get vaultAuthority(): PublicKey { return this._vaultAuthority; } private _vaultAuthority: PublicKey; public get state(): programTypes.State { return this._state; } private _state: programTypes.State; public get vaults(): types.Vault[] { return this._vaults; } private _vaults: types.Vault[] = []; private _eventListeners: any[] = []; public assertInitialized() { if (!this.isInitialized) { throw Error("Vault not initialized!"); } } public assertUninitialized() { if (this.isInitialized) { throw Error("Vault already initialized!"); } } private init( connection: Connection, programId: PublicKey, wallet: Wallet, network: Network, opts: ConfirmOptions ) { this.assertUninitialized(); this._provider = new anchor.AnchorProvider(connection, wallet, opts); this._network = network; this._program = new anchor.Program( idl as anchor.Idl, programId, this._provider ) as anchor.Program; this._isInitialized = true; } // Wallet has to be state admin. public async load( programId: PublicKey, network: Network, connection: Connection, wallet = new DummyWallet(), opts = utils.defaultCommitment() ) { vault.init(connection, programId, wallet, network, opts); let [state, _stateNonce] = vaultUtils.getStateAddress(); let [vaultAuthority, _vaultAuthorityNonce] = vaultUtils.getVaultAuthorityAddress(); this._stateAddress = state; this._vaultAuthority = vaultAuthority; await this.updateState(); } public async initializeState( managementFeePercentage: number, yieldFeePercentage: number, feeRecipients: Array ): Promise { if (feeRecipients.length != 2) { throw Error("Expect 2 fee recipients"); } let tx = new Transaction().add( await instructions.initializeStateIx( managementFeePercentage, yieldFeePercentage, feeRecipients ) ); let txId = await utils.processTransaction( Program.VAULT, this._provider, tx ); await this.updateStateAccount(); return txId; } public async updateFeeRecipients( feeRecipients: Array ): Promise { let tx = new Transaction().add( await instructions.updateFeeRecipientsIx(feeRecipients) ); let txId = await utils.processTransaction( Program.VAULT, this._provider, tx ); await this.updateStateAccount(); return txId; } public async initializeVault( vaultName: string, underlyingMint: PublicKey, epochTimes: instructions.EpochTimes, depositLimit: anchor.BN ): Promise { let tx = new Transaction().add( await instructions.initializeVaultIx( vaultName, underlyingMint, epochTimes, depositLimit ) ); let txId = await utils.processTransaction( Program.VAULT, this._provider, tx ); await this.updateVaults(); return txId; } public async updateDepositLimit( vault: PublicKey, newDepositLimit: anchor.BN ): Promise { let tx = new Transaction().add( await instructions.updateVaultDepositLimitIx(vault, newDepositLimit) ); return await utils.processTransaction(Program.VAULT, this._provider, tx); } // strike is native integer 6 d.p public async initializeOption( vault: PublicKey, strike: anchor.BN ): Promise { await Flex.updateState(); let tx = new Transaction() .add( ComputeBudgetProgram.setComputeUnitLimit({ units: 300_000, }) ) .add( ComputeBudgetProgram.setComputeUnitPrice({ microLamports: 1, }) ) .add(await instructions.initializeOptionIx(vault, strike)); let txId = await utils.processTransaction( Program.VAULT, this._provider, tx ); await this.updateVaults(); return txId; } public async fundVaultWallet( lamports: number ): Promise { let tx = new Transaction().add( await instructions.fundVaultAuthorityIx(lamports) ); return await utils.processTransaction(Program.VAULT, this._provider, tx); } public async initializeAuction( vault: PublicKey, bidEnd: anchor.BN, cooldownEnd: anchor.BN ): Promise { await this.updateVaults(); let vaultInfo = this.getVault(vault); if (vaultInfo.option == null) { throw Error("Cannot initialize auction without creating an option."); } let vaultOptionTokenAccountInfo = await getAccount( this._provider.connection, vaultInfo.vaultOptionTokenAccount ); if (Number(vaultOptionTokenAccountInfo.amount) == 0) { throw Error("Cannot initialize auction with zero option tokens."); } let tx = new Transaction(); tx.add( await instructions.initializeAuctionIx( vault, utils.bigIntToBN(vaultOptionTokenAccountInfo.amount), vaultInfo.option.optionMint, bidEnd, cooldownEnd ) ); let txId = await utils.processTransaction( Program.VAULT, this._provider, tx ); await Flex.updateState(); return txId; } public getAuctionForVault(vault: PublicKey): Auction | null { let vaultInfo = this.getVault(vault); let auctions = Flex.getAuctionsByCreator(this.vaultAuthority); for (var i = 0; i < auctions.length; i++) { if ( auctions[i].optionInfo.optionMint.equals(vaultInfo.option.optionMint) ) { // There can only be one live auction per vault. return auctions[i]; } } return null; } public async cancelAuction( vault: PublicKey ): Promise { let auction = this.getAuctionForVault(vault); if (auction == null) { throw Error("Auction not found for vault"); } let tx = new Transaction().add( await instructions.cancelAuctionIx(vault, auction) ); return await utils.processTransaction(Program.VAULT, this._provider, tx); } public async acceptAuctionBid( vault: PublicKey, bid: Bid ): Promise { let vaultInfo = this.getVault(vault); let auction = this.getAuctionForVault(vault); if (auction == null) { throw Error("Auction not found for vault!"); } // Fine to ignore these ixs We don't support auctions for SOL let [preIxs, _postIxs, _keypair, bidderAuctionTokenAccountAddress] = await utils.createTokenAccountInstructions( this._provider.connection, auction.auctionTokenMint, bid.bidder, this._provider.wallet.publicKey, 0, true ); let tx = new Transaction().add( ...preIxs, await instructions.acceptAuctionBidIx( vaultInfo, auction, bid, bidderAuctionTokenAccountAddress ) ); return await utils.processTransaction(Program.VAULT, this._provider, tx); } public async updateStateAccount() { try { this._state = (await this._program.account.state.fetch( this._stateAddress )) as programTypes.State; } catch (e) { console.log("State account not initialized yet."); } } public async updateState() { await this.updateStateAccount(); await this.updateVaults(); await this.updateDepositAndWithdrawalQueues(); } public async updateVaults() { // We need to update Flex option state to assign // options to a vault contract. await Flex.updateState(); let accs: anchor.ProgramAccount[] = await this.program.account.vault.all(); let vaults = await Promise.all( accs.map(async (acc) => { let vault = acc.account as programTypes.Vault; let option: Option = vault.optionMint.equals(PublicKey.default) ? null : (Flex.getOptionByMint( vault.optionMint, FlexOptionType.Normal ) as Option); let vaultOptionTokenAccount: PublicKey = null; if (option != null) { vaultOptionTokenAccount = flexUtils.getUserOptionMintTokenAccountAddress( Flex.programId, option.optionMint, this.vaultAuthority )[0]; } let epochTimes: types.EpochTimes = { startEpoch: new Date(vault.startEpoch.toNumber() * 1000), endDeposits: new Date(vault.endDeposits.toNumber() * 1000), startSettlement: new Date(vault.startSettlement.toNumber() * 1000), endEpoch: new Date(vault.endEpoch.toNumber() * 1000), epochCadence: vault.epochCadence, }; return { address: acc.publicKey, vaultName: Buffer.from(vault.vaultName).toString().trim(), underlyingMint: vault.underlyingMint, redeemableMint: vault.redeemableMint, vaultUnderlyingTokenAccount: vault.vaultUnderlyingTokenAccount, vaultDepositQueueUnderlyingTokenAccount: vault.vaultDepositQueueUnderlyingTokenAccount, vaultWithdrawQueueRedeemableTokenAccount: vault.vaultWithdrawQueueRedeemableTokenAccount, depositLimit: vault.depositLimit.toNumber(), epochSequenceNumber: vault.epochSequenceNumber.toNumber(), epochTimes, startEpochVaultBalance: vault.startEpochVaultBalance.toNumber(), option, vaultOptionTokenAccount, vaultDepositQueueHeaderAddress: vault.depositQueueHeader, vaultWithdrawQueueHeaderAddress: vault.withdrawQueueHeader, depositQueue: [], withdrawalQueue: [], totalQueuedDeposits: 0, totalQueuedWithdrawals: 0, }; }) ); this._vaults = vaults; } public async exerciseOption( vault: PublicKey ): Promise { let tx = new Transaction().add(await instructions.exerciseOptionIx(vault)); return await utils.processTransaction(Program.VAULT, this._provider, tx); } public async burnOption( vault: PublicKey ): Promise { let tx = new Transaction().add(await instructions.burnOptionIx(vault)); return await utils.processTransaction(Program.VAULT, this._provider, tx); } public async collectCollateral( vault: PublicKey ): Promise { let tx = new Transaction().add( await instructions.collectCollateralIx(vault) ); let txId = await utils.processTransaction( Program.VAULT, this._provider, tx ); await this.updateVaults(); return txId; } public async rolloverVault( vault: PublicKey, collectFees: boolean ): Promise { let remainingAccounts: AccountMeta[] = []; let tx = new Transaction(); let vaultInfo = this.getVault(vault); if (collectFees) { for (var i = 0; i < this.state.feeRecipients.length; i++) { let key = this.state.feeRecipients[i].recipient; let associatedTokenAddress = await getAssociatedTokenAddress( vaultInfo.underlyingMint, key ); remainingAccounts.push({ pubkey: associatedTokenAddress, isSigner: false, isWritable: true, }); try { await getAccount(this._provider.connection, associatedTokenAddress); } catch (e) { tx.add( createAssociatedTokenAccountInstruction( this.provider.wallet.publicKey, associatedTokenAddress, key, vaultInfo.underlyingMint ) ); } } } tx.add( await instructions.rolloverVaultIx(vaultInfo.address, remainingAccounts) ); let txId = await utils.processTransaction( Program.VAULT, this._provider, tx ); await this.updateVaults(); return txId; } public getVault(vault: PublicKey): types.Vault { for (var i = 0; i < this._vaults.length; i++) { if (this._vaults[i].address.equals(vault)) { return this._vaults[i]; } } throw Error(`Vault does not exist: ` + vault.toString()); } private findNode(queueNodes: any[], node: PublicKey): programTypes.QueueNode { for (var i = 0; i < queueNodes.length; i++) { if (queueNodes[i].publicKey.equals(node)) { return queueNodes[i].account as programTypes.QueueNode; } } throw Error("Could not find node in list"); } public async updateDepositQueue(vault: PublicKey, queueNodes: any[]) { let vaultInfo = this.getVault(vault); let depositQueueHeaderInfo = await this._program.account.queueHeader.fetch( vaultInfo.vaultDepositQueueHeaderAddress ); let totalDeposits = 0; if (depositQueueHeaderInfo.count.toNumber() == 0) { vaultInfo.depositQueue = []; } else { let depositQueue: types.QueueNode[] = []; let currNodeAddress = depositQueueHeaderInfo.head; while (!currNodeAddress.equals(PublicKey.default)) { let currNodeInfo = this.findNode(queueNodes, currNodeAddress); totalDeposits += currNodeInfo.amount.toNumber(); depositQueue.push({ address: currNodeAddress, info: currNodeInfo, }); currNodeAddress = currNodeInfo.nextNode; } vaultInfo.depositQueue = depositQueue; } vaultInfo.totalQueuedDeposits = totalDeposits; } public async updateWithdrawalQueue(vault: PublicKey, queueNodes: any[]) { let vaultInfo = this.getVault(vault); let withdrawQueueHeaderInfo = await this._program.account.queueHeader.fetch( vaultInfo.vaultWithdrawQueueHeaderAddress ); let totalWithdrawals = 0; if (withdrawQueueHeaderInfo.count.toNumber() == 0) { vaultInfo.withdrawalQueue = []; } else { let withdrawalQueue: types.QueueNode[] = []; let currNodeAddress = withdrawQueueHeaderInfo.head; while (!currNodeAddress.equals(PublicKey.default)) { let currNodeInfo = this.findNode(queueNodes, currNodeAddress); withdrawalQueue.push({ address: currNodeAddress, info: currNodeInfo, }); totalWithdrawals += currNodeInfo.amount.toNumber(); currNodeAddress = currNodeInfo.nextNode; } vaultInfo.withdrawalQueue = withdrawalQueue; } vaultInfo.totalQueuedWithdrawals = totalWithdrawals; } public async updateDepositAndWithdrawalQueues() { let queueNodes = await this._program.account.queueNode.all(); await Promise.all( this._vaults.map(async (vault) => { await this.updateDepositQueue(vault.address, queueNodes); await this.updateWithdrawalQueue(vault.address, queueNodes); }) ); } public async processDepositQueue(vault: PublicKey) { await this.updateDepositAndWithdrawalQueues(); let vaultInfo = this.getVault(vault); let depositQueue = vaultInfo.depositQueue; if (depositQueue.length != 0) { let createIxForUserAlready: string[] = []; for ( let i = 0; i < depositQueue.length; i += vaultConstants.PROCESS_QUEUE_ACCOUNT_LIMIT ) { let tx = new Transaction(); let remainingAccounts: AccountMeta[] = []; let slice = depositQueue.slice( i, i + vaultConstants.PROCESS_QUEUE_ACCOUNT_LIMIT ); for (let i = 0; i < slice.length; i++) { let node = slice[i]; if (createIxForUserAlready.includes(node.info.userKey.toString())) { return; } let userRedeemableTokenAccountAddress = await getAssociatedTokenAddress( vaultInfo.redeemableMint, node.info.userKey ); try { await getAccount( this._provider.connection, userRedeemableTokenAccountAddress ); } catch (e) { tx.add( createAssociatedTokenAccountInstruction( this._provider.wallet.publicKey, userRedeemableTokenAccountAddress, node.info.userKey, vaultInfo.redeemableMint ) ); createIxForUserAlready.push(node.info.userKey.toString()); } } for (let j = 0; j < slice.length; j++) { let userRedeemableTokenAccountAddress = await getAssociatedTokenAddress( vaultInfo.redeemableMint, slice[j].info.userKey ); remainingAccounts.push({ pubkey: slice[j].address, isSigner: false, isWritable: true, }); remainingAccounts.push({ pubkey: userRedeemableTokenAccountAddress, isSigner: false, isWritable: true, }); remainingAccounts.push({ pubkey: slice[j].info.userKey, isSigner: false, isWritable: true, }); } tx.add( await instructions.processDepositQueueIx(vaultInfo, remainingAccounts) ); let sig = await utils.processTransaction( Program.VAULT, this._provider, tx ); console.log(`Process deposit queue TX: ${sig}`); } } else { console.log("Empty deposit queue..."); } } public async processWithdrawQueue(vault: PublicKey) { await this.updateDepositAndWithdrawalQueues(); let vaultInfo = this.getVault(vault); let withdrawQueue = vaultInfo.withdrawalQueue; if (withdrawQueue.length != 0) { // We can be lazy here by not checking for redeemable token account existence // When we deposit vault we already check and create redeemable account for users let createIxForUserAlready: string[] = []; for ( let i = 0; i < withdrawQueue.length; i += vaultConstants.PROCESS_QUEUE_ACCOUNT_LIMIT ) { let tx = new Transaction(); let remainingAccounts: AccountMeta[] = []; let slice = withdrawQueue.slice( i, i + vaultConstants.PROCESS_QUEUE_ACCOUNT_LIMIT ); for (let j = 0; j < slice.length; j++) { if ( createIxForUserAlready.includes(slice[j].info.userKey.toString()) ) { continue; } let tokenAccountKey = await getAssociatedTokenAddress( vaultInfo.underlyingMint, slice[j].info.userKey ); try { await getAccount(this._provider.connection, tokenAccountKey); } catch (e) { tx.add( createAssociatedTokenAccountInstruction( this._provider.wallet.publicKey, tokenAccountKey, slice[j].info.userKey, vaultInfo.underlyingMint ) ); createIxForUserAlready.push(slice[j].info.userKey.toString()); } remainingAccounts.push({ pubkey: slice[j].address, isSigner: false, isWritable: true, }); remainingAccounts.push({ pubkey: tokenAccountKey, isSigner: false, isWritable: true, }); remainingAccounts.push({ pubkey: slice[j].info.userKey, isSigner: false, isWritable: true, }); } tx.add( await instructions.processWithdrawQueueIx( vaultInfo, remainingAccounts ) ); let sig = await utils.processTransaction( Program.VAULT, this._provider, tx ); console.log(`Process withdrawal queue TX: ${sig}`); } } else { console.log("Empty withdrawal queue..."); } } public async overrideVaultEpochTimes( vault: PublicKey, args: instructions.OverrideVaultEpochTimesArgs ) { let tx = new Transaction().add( await instructions.overrideVaultEpochTimesIx(vault, args) ); await utils.processTransaction(Program.VAULT, this._provider, tx); } public async setVaultToWithdrawOnly(vault: PublicKey) { let tx = new Transaction().add( await instructions.setVaultToWithdrawOnly(vault) ); await utils.processTransaction(Program.VAULT, this._provider, tx); } public subscribeUserEvents( callback: (type: VaultEvent, data: any) => void = undefined ): void { if (this._eventListeners.length > 0) { throw Error("Events already subscribed!"); } this._eventListeners.push( this._program.addEventListener( VaultEvent.DEPOSIT, (event: DepositEvent, _slot) => { callback(VaultEvent.DEPOSIT, event); } ) ); this._eventListeners.push( this._program.addEventListener( VaultEvent.WITHDRAWAL, (event: DepositEvent, _slot) => { callback(VaultEvent.WITHDRAWAL, event); } ) ); } public async close() { for (var i = 0; i < this._eventListeners.length; i++) { await this._program.removeEventListener(this._eventListeners[i]); } this._eventListeners = []; } } export const vault = new Vault();