import * as anchor from "@project-serum/anchor"; import { ZetaFlex } from "../types/zeta_flex"; import { ConfirmOptions, PublicKey, Connection, Transaction, TransactionInstruction, Keypair, AccountMeta, ComputeBudgetProgram, } from "@solana/web3.js"; import { TOKEN_PROGRAM_ID, getAccount, createAssociatedTokenAccountInstruction, getAssociatedTokenAddress, AccountLayout as TokenAccountLayout, createCloseAccountInstruction, } from "@solana/spl-token"; import { Position, ComboPosition, Bid, TokenAcc, SettlementType, Kind, OracleMethod, toProgramKind, ComboOptionParams, toProgramOracleMethod, toProgramSettlementType, convertToProgramComboOptionParams, FlexOptionType, Option, } from "./types"; import { TransactionMethodReturnData, Wallet } from "../common/types"; import { Program } from "../common/program"; import { SOL_PUBKEY } from "../common/constants"; import { flex as Flex } from "./flex"; import * as utils from "../common/utils"; import * as flexUtils from "./flex-utils"; import * as instructions from "./instructions"; import { AuctionAccount, ComboOptionParams as ProgramComboOptionParams, InitializeAuctionArgs, InitializeOptionArgs, } from "./program-types"; export class FlexClient { /** * Anchor Program instance. */ 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 publicKey(): PublicKey { return this._provider.wallet.publicKey; } public get whitelistFeesAccountAddress(): PublicKey { return this._whitelistFeesAccountAddress; } private _whitelistFeesAccountAddress: PublicKey; /** * Collection of all tokenAccounts associated with the client */ public get tokenAccounts(): TokenAcc[] { return this._tokenAccounts; } private _tokenAccounts: TokenAcc[] = []; /** * Collection of all client positions on zeta-flex options */ public get optionPositions(): Position[] { return this._optionPositions; } private _optionPositions: Position[] = []; /** * Collection of all client positions on zeta-flex options */ public get comboOptionPositions(): ComboPosition[] { return this._comboOptionPositions; } private _comboOptionPositions: ComboPosition[] = []; /** * Collection of all client bids on zeta-flex auctions */ public get bids(): Bid[] { return this._bids; } private _bids: Bid[] = []; private constructor( connection: Connection, wallet: Wallet, opts: ConfirmOptions ) { this._provider = new anchor.AnchorProvider(connection, wallet, opts); this._program = Flex.program; } public static async load( connection: Connection, wallet: Wallet, opts = utils.defaultCommitment() ): Promise { if (!Flex.isInitialized) { throw Error("Flex program is not initialized"); } let client = new FlexClient(connection, wallet, opts); let [whitelistFeesAccountAddress, _nonce] = flexUtils.getWhitelistFeesAccountAddress( Flex.programId, wallet.publicKey ); client._whitelistFeesAccountAddress = whitelistFeesAccountAddress; await client.updateState(); return client; } public async initializeOption( underlyingMint: PublicKey, collateralMint: PublicKey, exerciseMint: PublicKey, settlementStart: anchor.BN, settlementEnd: anchor.BN, collateralAmount: anchor.BN, strike: anchor.BN, kind: Kind, settlementType: SettlementType, oracleMethod: OracleMethod, returnInstructions: boolean = false ): Promise { try { strike.toNumber(); } catch (e) { throw Error("Strike is > 53 bits"); } let underlying = Flex.getUnderlying(underlyingMint); let [optionAccount, _optionAccountNonce] = flexUtils.getOptionAccountAddress( Flex.program.programId, underlying.address, new anchor.BN(underlying.count) ); let [vault, _vaultNonce] = flexUtils.getVaultAddress( Flex.program.programId, optionAccount ); let [optionMint, _optionMintNonce] = flexUtils.getOptionMintAddress( Flex.program.programId, optionAccount ); let userOptionTokenAccount = await getAssociatedTokenAddress( optionMint, this.publicKey ); let feeRecipientCollateralTokenAccount = await getAssociatedTokenAddress( collateralMint, Flex.state.feeRecipient ); let [optionMintMetadataAccount, _nonce] = flexUtils.getTokenMetadataAccountAddress(optionMint); let userCollateralTokenAddress: PublicKey; let userExerciseTokenAddress: PublicKey; let remainingAccounts: AccountMeta[] = []; let collateralKeypair: Keypair; let exerciseKeypair: Keypair; let preIxs: TransactionInstruction[] = [ ComputeBudgetProgram.setComputeUnitLimit({ units: 300_000, }), ComputeBudgetProgram.setComputeUnitPrice({ microLamports: 1, }), ]; let postIxs: TransactionInstruction[] = []; remainingAccounts.push( { pubkey: this._whitelistFeesAccountAddress, isSigner: false, isWritable: false, }, { pubkey: this.publicKey, isSigner: true, isWritable: false, } ); let amountNeeded: number = collateralAmount.toNumber(); try { await Flex.program.account.whitelistFeesAccount.fetch( this._whitelistFeesAccountAddress ); } catch (e) { amountNeeded += flexUtils.calculateMintingFees( collateralAmount.toNumber() ); } [preIxs, postIxs, collateralKeypair, userCollateralTokenAddress] = await utils.createTokenAccountInstructions( this._provider.connection, collateralMint, this.publicKey, this.publicKey, amountNeeded, true ); if (settlementType == SettlementType.PHYSICAL) { let [_preIxs, _postIxs, _exerciseKeypair, _userExerciseTokenAddress] = await utils.createTokenAccountInstructions( this._provider.connection, exerciseMint, this.publicKey, this.publicKey, 0, false ); preIxs.push(..._preIxs); postIxs.push(..._postIxs); exerciseKeypair = _exerciseKeypair; userExerciseTokenAddress = _userExerciseTokenAddress; remainingAccounts.push( { pubkey: exerciseMint, isSigner: false, isWritable: false, }, { pubkey: userExerciseTokenAddress, isSigner: false, isWritable: false, } ); } try { await getAccount( this.provider.connection, feeRecipientCollateralTokenAccount ); } catch (e) { preIxs.push( createAssociatedTokenAccountInstruction( this.publicKey, feeRecipientCollateralTokenAccount, Flex.state.feeRecipient, collateralMint ) ); } let initOptionArgs: InitializeOptionArgs = { collateralAmount, settlementStart, settlementEnd, strike, kind: toProgramKind(kind), settlementType: toProgramSettlementType(settlementType), oracleMethod: toProgramOracleMethod(oracleMethod), }; let tx: Transaction = utils.combineIxsForTx( ...preIxs, await instructions.initializeOptionV2Ix( initOptionArgs, underlying.address, vault, collateralMint, userCollateralTokenAddress, this.publicKey, optionAccount, optionMint, userOptionTokenAccount, feeRecipientCollateralTokenAccount, optionMintMetadataAccount, remainingAccounts ), ...postIxs ); return await utils.processTransaction( Program.FLEX, this._provider, tx, [collateralKeypair, exerciseKeypair], null, returnInstructions ); } public async initializeComboOption( underlyingMint: PublicKey, collateralMint: PublicKey, settlementStart: anchor.BN, settlementEnd: anchor.BN, optionParams: ComboOptionParams[], settlementType: SettlementType, oracleMethod: OracleMethod, returnInstructions: boolean = false ): Promise { let underlying = Flex.getUnderlying(underlyingMint); let [optionAccount, _optionAccountNonce] = flexUtils.getOptionAccountAddress( Flex.program.programId, underlying.address, new anchor.BN(underlying.count) ); let [vault, _vaultNonce] = flexUtils.getVaultAddress( Flex.program.programId, optionAccount ); let [optionMint, _optionMintNonce] = flexUtils.getOptionMintAddress( Flex.program.programId, optionAccount ); let userOptionTokenAccount = await getAssociatedTokenAddress( optionMint, this.publicKey ); let feeRecipientCollateralTokenAccount = await getAssociatedTokenAddress( collateralMint, Flex.state.feeRecipient ); let [optionMintMetadataAccount, _nonce] = flexUtils.getTokenMetadataAccountAddress(optionMint); let preIxs: TransactionInstruction[] = []; let postIxs: TransactionInstruction[] = []; let remainingAccounts: AccountMeta[] = []; remainingAccounts.push( { pubkey: this._whitelistFeesAccountAddress, isSigner: false, isWritable: false, }, { pubkey: this.publicKey, isSigner: true, isWritable: false, } ); let collateralKeypair: Keypair = undefined; let userCollateralTokenAddress: PublicKey = undefined; let amountNeeded = flexUtils.getCollateralRequiredForComboOption(optionParams); try { await Flex.program.account.whitelistFeesAccount.fetch( this._whitelistFeesAccountAddress ); } catch (e) { amountNeeded += flexUtils.calculateMintingFees(amountNeeded); } [preIxs, postIxs, collateralKeypair, userCollateralTokenAddress] = await utils.createTokenAccountInstructions( this._provider.connection, collateralMint, this.publicKey, this.publicKey, amountNeeded, true ); try { await getAccount( this.provider.connection, feeRecipientCollateralTokenAccount ); } catch (e) { preIxs.push( createAssociatedTokenAccountInstruction( this.publicKey, feeRecipientCollateralTokenAccount, Flex.state.feeRecipient, collateralMint ) ); } let programOptionParams: ProgramComboOptionParams[] = convertToProgramComboOptionParams(optionParams); let initComboOptionArgs = { settlementStart, settlementEnd, optionParams: programOptionParams, settlementType: toProgramSettlementType(settlementType), oracleMethod: toProgramOracleMethod(oracleMethod), }; let tx: Transaction = utils.combineIxsForTx( ...preIxs, await instructions.initializeComboOptionV2Ix( initComboOptionArgs, underlying.address, vault, collateralMint, userCollateralTokenAddress, this.publicKey, optionAccount, optionMint, userOptionTokenAccount, feeRecipientCollateralTokenAccount, optionMintMetadataAccount, remainingAccounts ), ...postIxs ); return await utils.processTransaction( Program.FLEX, this._provider, tx, [collateralKeypair], null, returnInstructions ); } public async burnOption( burnAmount: anchor.BN, optionAccount: PublicKey, optionType: FlexOptionType, returnInstructions: boolean = false ): Promise { await this.updateTokenAccounts(); let optionInfo = Flex.getOption(optionAccount, optionType); let userCollateralTokenAccounts = this.getTokenAccountsByMint( optionInfo.collateralMint ); let userCollateralTokenAddress: PublicKey = undefined; let collateralKeypair: Keypair; let preIxs: TransactionInstruction[] = []; let postIxs: TransactionInstruction[] = []; if (userCollateralTokenAccounts.length == 0) { console.log( "Client has no collateral token account for this option! Creating now..." ); [preIxs, postIxs, collateralKeypair, userCollateralTokenAddress] = await utils.createTokenAccountInstructions( this._provider.connection, optionInfo.collateralMint, this.publicKey, this.publicKey, 0, true ); } else { userCollateralTokenAddress = userCollateralTokenAccounts[0].address; } let userOptionTokenAccounts = this.getTokenAccountsByMint( optionInfo.optionMint ); if (userOptionTokenAccounts.length == 0) { throw Error("User attempted to burn options they don't have"); } let tx: Transaction = utils.combineIxsForTx( ...preIxs, await instructions.burnOptionIx( burnAmount, optionInfo, userCollateralTokenAddress, userOptionTokenAccounts[0].address, this.publicKey ), ...postIxs ); return await utils.processTransaction( Program.FLEX, this._provider, tx, [collateralKeypair], null, returnInstructions ); } public async collectRemainingCollateral( optionAccount: PublicKey, optionType: FlexOptionType, returnInstructions: boolean = false ): Promise { await this.updateTokenAccounts(); let optionInfo = Flex.getOption(optionAccount, optionType); let userCollateralTokenAccounts = this.getTokenAccountsByMint( optionInfo.collateralMint ); let userCollateralTokenAddress: PublicKey; let collateralKeypair: Keypair; let preIxs: TransactionInstruction[] = []; let postIxs: TransactionInstruction[] = []; if (userCollateralTokenAccounts.length == 0) { console.log( "Client has no collateral token account for this option! Creating now..." ); [preIxs, postIxs, collateralKeypair, userCollateralTokenAddress] = await utils.createTokenAccountInstructions( this._provider.connection, optionInfo.collateralMint, this.publicKey, this.publicKey, 0, true ); } else { userCollateralTokenAddress = userCollateralTokenAccounts[0].address; } let userOptionTokenAccounts = this.getTokenAccountsByMint( optionInfo.optionMint ); if (userOptionTokenAccounts.length == 0) { console.log("User has no more option tokens"); let tokenAccAddress = await getAssociatedTokenAddress( optionInfo.optionMint, this.publicKey ); userOptionTokenAccounts.push({ address: tokenAccAddress, mint: optionInfo.optionMint, amount: BigInt(0), }); } let midIxs: TransactionInstruction[] = await Promise.all( userOptionTokenAccounts.map(async (optionTokenAccount) => { return await instructions.collectRemainingCollateralIx( optionInfo, userCollateralTokenAddress, optionTokenAccount.address, this.publicKey ); }) ); let tx: Transaction = utils.combineIxsForTx( ...preIxs, ...midIxs, ...postIxs ); return await utils.processTransaction( Program.FLEX, this._provider, tx, [collateralKeypair], null, returnInstructions ); } public async initializeAuction( auctionTokenMint: PublicKey, bidCurrencyTokenMint: PublicKey, auctionAmount: anchor.BN, bidEnd: anchor.BN, cooldownEnd: anchor.BN, returnInstructions: boolean = false ): Promise { let [auctionAccount, _auctionNonce] = flexUtils.getAuctionAddress( Flex.programId, auctionTokenMint, this.publicKey, auctionAmount, bidEnd, cooldownEnd ); let [auctionVault, _auctionVaultNonce] = flexUtils.getAuctionVaultAddress( Flex.programId, auctionTokenMint, this.publicKey, auctionAmount, bidEnd, cooldownEnd ); let userAuctionTokenAccounts = this.getTokenAccountsByMint(auctionTokenMint); if (userAuctionTokenAccounts.length == 0) { throw Error("User has no auction mint token account"); } let initAuctionArgs: InitializeAuctionArgs = { amount: auctionAmount, bidEnd, cooldownEnd, }; let tx: Transaction = new Transaction(); tx.add( await instructions.initializeAuctionIx( initAuctionArgs, auctionAccount, this.publicKey, auctionVault, auctionTokenMint, userAuctionTokenAccounts[0].address, bidCurrencyTokenMint ) ); return await utils.processTransaction( Program.FLEX, this._provider, tx, [], null, returnInstructions ); } public async acceptBid( bidAccount: PublicKey, returnInstructions: boolean = false ): Promise { let bidAccountInfo = Flex.getBidByKey(bidAccount); if (bidAccountInfo == null) { throw Error("Bid account not found!"); } let auctionAccountInfo = Flex.getAuctionByKey( bidAccountInfo.auctionAccount ); if (auctionAccountInfo == null) { throw Error("Auction account not found!"); } let [preIxs, postIxs, bidKeypair, userBidCurrencyTokenAccountAddress] = await utils.createTokenAccountInstructions( this._provider.connection, bidAccountInfo.bidCurrencyMint, this.publicKey, this.publicKey, 0, true ); // Fine to ignore these ixs We don't support auctions for SOL let [_preIxs, _postIxs, _keypair, bidderAuctionTokenAccountAddress] = await utils.createTokenAccountInstructions( this._provider.connection, auctionAccountInfo.auctionTokenMint, bidAccountInfo.bidder, this.publicKey, 0, true ); preIxs.push(..._preIxs); let tx = utils.combineIxsForTx( ...preIxs, await instructions.acceptBidIx( this.publicKey, bidAccountInfo, auctionAccountInfo, bidderAuctionTokenAccountAddress, userBidCurrencyTokenAccountAddress ), ...postIxs ); return await utils.processTransaction( Program.FLEX, this._provider, tx, [bidKeypair], null, returnInstructions ); } public async cancelAuction( auctionAccount: PublicKey, returnInstructions: boolean = false ): Promise { let auctionAccountInfo = Flex.getAuctionByKey(auctionAccount); if (auctionAccountInfo == null) { throw Error("Auction account not found!"); } let userAuctionTokenAccounts = this.getTokenAccountsByMint( auctionAccountInfo.auctionTokenMint ); let userAuctionTokenAccount: PublicKey = undefined; let preIxs: TransactionInstruction[] = []; let postIxs: TransactionInstruction[] = []; if (userAuctionTokenAccounts.length == 0) { userAuctionTokenAccount = await getAssociatedTokenAddress( auctionAccountInfo.auctionTokenMint, this.publicKey ); preIxs.push( createAssociatedTokenAccountInstruction( this.publicKey, userAuctionTokenAccount, this.publicKey, auctionAccountInfo.auctionTokenMint ) ); } else { userAuctionTokenAccount = userAuctionTokenAccounts[0].address; } let tx: Transaction = utils.combineIxsForTx( ...preIxs, await instructions.cancelAuctionIx( this.publicKey, auctionAccountInfo, userAuctionTokenAccount ), ...postIxs ); return await utils.processTransaction( Program.FLEX, this._provider, tx, [], null, returnInstructions ); } public async bidAuction( amount: number, auctionAccount: PublicKey, bidCurrencyMint?: PublicKey, returnInstructions: boolean = false ): Promise { let auctionAccountInfo = Flex.getAuctionByKey(auctionAccount); if (auctionAccountInfo == null) { throw Error("Auction account not found!"); } let [bidAccountAddress, _bidAccountNonce] = flexUtils.getBidAccountAddress( Flex.program.programId, auctionAccount, this.publicKey ); let [bidVaultAddress, _bidVaultNonce] = flexUtils.getBidVaultAddress( Flex.program.programId, auctionAccount, this.publicKey ); if ( auctionAccountInfo.bidCurrencyMint.equals(PublicKey.default) && !bidCurrencyMint ) { throw Error( "Must specify bid currency mint to bid on auction with any bid currency" ); } let bidCurrencyMintAddress = bidCurrencyMint ? bidCurrencyMint : auctionAccountInfo.bidCurrencyMint; let [preIxs, postIxs, bidKeypair, bidderBidCurrencyTokenAccountAddress] = await utils.createTokenAccountInstructions( this._provider.connection, bidCurrencyMintAddress, this.publicKey, this.publicKey, amount, true ); // Fine to ignore these ixs We don't support auctions for SOL let [_preIxs, _postIxs, _keypair, _userAuctionTokenAccountAddress] = await utils.createTokenAccountInstructions( this._provider.connection, auctionAccountInfo.auctionTokenMint, this.publicKey, this.publicKey, 0, true ); preIxs.push(..._preIxs); let tx: Transaction = utils.combineIxsForTx( ...preIxs, await instructions.bidAuctionIx( auctionAccount, bidAccountAddress, bidVaultAddress, this.publicKey, bidCurrencyMintAddress, bidderBidCurrencyTokenAccountAddress, amount ), ...postIxs ); return await utils.processTransaction( Program.FLEX, this._provider, tx, [bidKeypair], null, returnInstructions ); } public async cancelBid( bidAccount: PublicKey, returnInstructions: boolean = false ): Promise { let bidToCancel = undefined; this._bids.forEach((bid) => { if (bid.address.equals(bidAccount)) { bidToCancel = bid; } }); if (bidToCancel == undefined) { throw Error("Client attempted to cancel non-existent bid."); } let bidVaultInfo = await getAccount( this._provider.connection, bidToCancel.bidVault ); let [preIxs, postIxs, bidKeypair, bidderBidCurrencyTokenAccountAddress] = await utils.createTokenAccountInstructions( this._provider.connection, bidVaultInfo.mint, this.publicKey, this.publicKey, 0, true ); let tx = utils.combineIxsForTx( ...preIxs, await instructions.cancelBidIx( bidToCancel.auctionAccount, this.publicKey, bidAccount, bidToCancel.bidVault, bidderBidCurrencyTokenAccountAddress ), ...postIxs ); return await utils.processTransaction( Program.FLEX, this._provider, tx, [bidKeypair], null, returnInstructions ); } public async exerciseOption( optionAccount: PublicKey, exerciseAmount?: number, returnInstructions: boolean = false ): Promise { await this.updateTokenAccounts(); let optionAccountInfo = Flex.getOption( optionAccount, FlexOptionType.Normal ) as Option; let userCollateralTokenAccount: PublicKey = undefined; let userExerciseTokenAccount: PublicKey = undefined; let userOptionTokenAccounts: PublicKey[] = []; let preIxs: TransactionInstruction[] = []; let postIxs: TransactionInstruction[] = []; this._tokenAccounts.forEach((tokenAcc) => { if (tokenAcc.mint.equals(optionAccountInfo.collateralMint)) { userCollateralTokenAccount = tokenAcc.address; } if (tokenAcc.mint.equals(optionAccountInfo.optionMint)) { userOptionTokenAccounts.push(tokenAcc.address); } if (tokenAcc.mint.equals(optionAccountInfo.exerciseMint)) { userExerciseTokenAccount = tokenAcc.address; } }); if (userOptionTokenAccounts.length == 0) { throw Error("Client attempted to exercise options that they don't have."); } let collateralKeypair: Keypair; if (userCollateralTokenAccount === undefined) { console.log( "Client has no collateral token account for this option! Creating now..." ); [preIxs, postIxs, collateralKeypair, userCollateralTokenAccount] = await utils.createTokenAccountInstructions( this._provider.connection, optionAccountInfo.collateralMint, this.publicKey, this.publicKey, 0, true ); } else { if (optionAccountInfo.collateralMint.equals(SOL_PUBKEY)) { postIxs.push( createCloseAccountInstruction( userCollateralTokenAccount, this.publicKey, this.publicKey ) ); } } let remainingAccounts: AccountMeta[] = []; let exerciseKeypair: Keypair; if (optionAccountInfo.settlementType == SettlementType.PHYSICAL) { let wrappedNativeTokensNeeded = await flexUtils.getTokenAmountToExercise( this.provider.connection, optionAccountInfo, this._tokenAccounts, exerciseAmount ); let [_preIxs, _postIxs, _exerciseKeypair, _userExerciseTokenAccount] = await utils.createTokenAccountInstructions( this._provider.connection, optionAccountInfo.exerciseMint, this.publicKey, this.publicKey, wrappedNativeTokensNeeded, true ); preIxs.push(..._preIxs); postIxs.push(..._postIxs); exerciseKeypair = _exerciseKeypair; userExerciseTokenAccount = _userExerciseTokenAccount; remainingAccounts.push( { pubkey: userExerciseTokenAccount, isSigner: false, isWritable: true, }, { pubkey: optionAccountInfo.creatorExerciseMintTokenAccount, isSigner: false, isWritable: true, }, { pubkey: optionAccountInfo.exerciseMint, isSigner: false, isWritable: false, } ); } let midIxs: TransactionInstruction[] = await Promise.all( userOptionTokenAccounts.map(async (optionTokenAcc) => { return await instructions.exerciseOptionIx( optionAccountInfo, userCollateralTokenAccount, optionTokenAcc, this.publicKey, remainingAccounts, exerciseAmount ); }) ); let tx: Transaction = utils.combineIxsForTx( ...preIxs, ...midIxs, ...postIxs ); let txSig = await utils.processTransaction( Program.FLEX, this._provider, tx, [collateralKeypair, exerciseKeypair], null, returnInstructions ); await this.updateState(); return txSig; } public async exerciseComboOption( optionAccount: PublicKey, exerciseAmount?: number, returnInstructions: boolean = false ): Promise { await this.updateTokenAccounts(); let comboOptionAccountInfo = Flex.getOption( optionAccount, FlexOptionType.Combo ); let userCollateralTokenAccount: PublicKey = undefined; let userOptionTokenAccounts: PublicKey[] = []; let preIxs: TransactionInstruction[] = []; let postIxs: TransactionInstruction[] = []; this._tokenAccounts.forEach((tokenAcc) => { if (tokenAcc.mint.equals(comboOptionAccountInfo.collateralMint)) { userCollateralTokenAccount = tokenAcc.address; } if (tokenAcc.mint.equals(comboOptionAccountInfo.optionMint)) { userOptionTokenAccounts.push(tokenAcc.address); } }); if (userOptionTokenAccounts.length == 0) { throw Error("Client attempted to exercise options that they don't have."); } let collateralKeypair: Keypair; if (userCollateralTokenAccount === undefined) { console.log( "Client has no collateral token account for this option! Creating now..." ); [preIxs, postIxs, collateralKeypair, userCollateralTokenAccount] = await utils.createTokenAccountInstructions( this._provider.connection, comboOptionAccountInfo.collateralMint, this.publicKey, this.publicKey, 0, true ); } else { if (comboOptionAccountInfo.collateralMint.equals(SOL_PUBKEY)) { postIxs.push( createCloseAccountInstruction( userCollateralTokenAccount, this.publicKey, this.publicKey ) ); } } let midIxs: TransactionInstruction[] = await Promise.all( userOptionTokenAccounts.map(async (optionTokenAcc) => { return await instructions.exerciseOptionIx( comboOptionAccountInfo, userCollateralTokenAccount, optionTokenAcc, this.publicKey, [], exerciseAmount ); }) ); let tx: Transaction = utils.combineIxsForTx( ...preIxs, ...midIxs, ...postIxs ); let txSig = await utils.processTransaction( Program.FLEX, this._provider, tx, [collateralKeypair], null, returnInstructions ); await this.updateState(); return txSig; } private updatePositions() { let optionPositions = []; let comboOptionPositions = []; this._tokenAccounts.forEach((tokenAcc) => { Flex.options.forEach((option) => { if ( tokenAcc.mint.equals(option.optionMint) && Number(tokenAcc.amount) != 0 ) { optionPositions.push({ optionAccount: option.optionAccount, amount: Number(tokenAcc.amount), strike: option.strike, expiry: option.expiry, }); } }); Flex.comboOptions.forEach((comboOption) => { if ( tokenAcc.mint.equals(comboOption.optionMint) && Number(tokenAcc.amount) != 0 ) { comboOptionPositions.push({ comboOptionAccount: comboOption.optionAccount, amount: Number(tokenAcc.amount), params: comboOption.optionParams, expiry: comboOption.expiry, }); } }); }); this._optionPositions = optionPositions; this._comboOptionPositions = comboOptionPositions; } public getExpiredPositions(): [Position[], ComboPosition[]] { let expiredOptionPositions: Position[] = []; for (var i = 0; i < this._optionPositions.length; i++) { if (this._optionPositions[i].expiry < Flex.clockTimestamp) { expiredOptionPositions.push(this._optionPositions[i]); } } let expiredComboOptionPositions: ComboPosition[] = []; for (var i = 0; i < this._comboOptionPositions.length; i++) { if (this._comboOptionPositions[i].expiry < Flex.clockTimestamp) { expiredComboOptionPositions.push(this._comboOptionPositions[i]); } } return [expiredOptionPositions, expiredComboOptionPositions]; } public getLivePositions(): [Position[], ComboPosition[]] { let liveOptionPositions: Position[] = []; for (var i = 0; i < this._optionPositions.length; i++) { if (this._optionPositions[i].expiry > Flex.clockTimestamp) { liveOptionPositions.push(this._optionPositions[i]); } } let liveComboOptionPositions: ComboPosition[] = []; for (var i = 0; i < this._comboOptionPositions.length; i++) { if (this._comboOptionPositions[i].expiry > Flex.clockTimestamp) { liveComboOptionPositions.push(this._comboOptionPositions[i]); } } return [liveOptionPositions, liveComboOptionPositions]; } private updateBids() { if (Flex.bids != undefined) { this._bids = Flex.bids.filter((bid) => bid.bidder.equals(this.publicKey)); } for (var i = 0; i < this._bids.length; i++) { let bid = this._bids[i]; const auction = Flex.auctions.find((a) => a.address.equals(bid.auctionAccount) ); if (!auction) { let auctionAccountInfo = Flex.getAuctionByKey(bid.auctionAccount); if (auctionAccountInfo == null) { continue; } let optionInfo = Flex.getOptionByMint( auctionAccountInfo.auctionTokenMint, FlexOptionType.Normal ); if (optionInfo != null) { bid.optionAccount = optionInfo.optionAccount; } let comboOptionInfo = Flex.getOptionByMint( auctionAccountInfo.auctionTokenMint, FlexOptionType.Combo ); if (comboOptionInfo != null) { bid.optionAccount = comboOptionInfo.optionAccount; } } else if ( Flex.getOptionByMint(auction.auctionTokenMint, FlexOptionType.Normal) != null ) { bid.optionAccount = Flex.getOptionByMint( auction.auctionTokenMint, FlexOptionType.Normal ).optionAccount; } else if ( Flex.getOptionByMint(auction.auctionTokenMint, FlexOptionType.Combo) != null ) { bid.optionAccount = Flex.getOptionByMint( auction.auctionTokenMint, FlexOptionType.Combo ).optionAccount; } } } public getCancellableBids(): Bid[] { let cancellableBids: Bid[] = []; for (var i = 0; i < this._bids.length; i++) { if ( Flex.clockTimestamp < this._bids[i].bidEnd || Flex.clockTimestamp > this._bids[i].cooldownEnd ) { cancellableBids.push(this._bids[i]); } } return cancellableBids; } public getAuctionBid(auctionAccount: PublicKey): Bid | null { for (var i = 0; i < this._bids.length; i++) { if (this._bids[i].auctionAccount.equals(auctionAccount)) { return this._bids[i]; } } return null; } private async updateTokenAccounts() { const accounts = await this._provider.connection.getTokenAccountsByOwner( this.publicKey, { programId: TOKEN_PROGRAM_ID, } ); let tokenAccounts: TokenAcc[] = []; for (var i = 0; i < accounts.value.length; i++) { let account = accounts.value[i].account; const accountInfo = TokenAccountLayout.decode(account.data); tokenAccounts.push({ address: accounts.value[i].pubkey, mint: new PublicKey(accountInfo.mint), // TODO: check later - should store as BN? amount: accountInfo.amount, }); } this._tokenAccounts = tokenAccounts; } public getTokenAccountsByMint(mint: PublicKey): TokenAcc[] { let tokenAccounts: TokenAcc[] = []; for (var i = 0; i < this._tokenAccounts.length; i++) { if (this._tokenAccounts[i].mint.equals(mint)) { tokenAccounts.push(this._tokenAccounts[i]); } } return tokenAccounts; } public async updateState() { await Flex.updateState(); this.updateBids(); await this.updateTokenAccounts(); this.updatePositions(); } }