import * as anchor from "@project-serum/anchor"; import idl from "../idl/zeta_flex.json"; import { ZetaFlex } from "../types/zeta_flex"; import { Network } from "../common/network"; import { PublicKey, Connection, SYSVAR_CLOCK_PUBKEY, Transaction, AccountInfo, } from "@solana/web3.js"; import { Underlying, Auction, Option, Bid, Kind, ComboOption, FlexOptionType, UnderlyingType, SettlementType, toLocalUnderlyingType, toLocalSettlementType, toLocalKind, toLocalOracleMethod, SettlementAccount, ComboOptionParams, ProgramAccount, } from "./types"; import * as programTypes from "./program-types"; import { DummyWallet, TransactionMethodReturnData } from "../common/types"; import * as utils from "../common/utils"; import * as flexUtils from "./flex-utils"; import { State } from "./program-types"; import { Program } from "../common/program"; import * as instructions from "./instructions"; import { EventType } from "../common/events"; import * as constants from "./constants"; export class Flex { /** * Whether the object has been loaded. */ public get isInitialized(): boolean { return this._isInitialized; } private _isInitialized: boolean = false; /** * Anchor program instance. */ public get program(): anchor.Program { return this._program; } private _program: anchor.Program; public get programId(): PublicKey { return this._program.programId; } /** * The solana network being used. */ public get network(): Network { return this._network; } private _network: Network; /** * Anchor provider instance. */ public get provider(): anchor.AnchorProvider { return this._provider; } private _provider: anchor.AnchorProvider; /** * Account storing the zeta-flex state. */ public get state(): State { return this._state; } private _state: State; /** * Address of the state account */ public get stateAddress(): PublicKey { return this._stateAddress; } private _stateAddress: PublicKey; /** * zeta-flex mint authority address */ public get mintAuthorityAddress(): PublicKey { return this._mintAuthorityAddress; } private _mintAuthorityAddress: PublicKey; /** * zeta-flex vault authority address */ public get vaultAuthorityAddress(): PublicKey { return this._vaultAuthorityAddress; } private _vaultAuthorityAddress: PublicKey; /** * A collection of all the current live auctions on zeta-flex */ public get liveAuctions(): Auction[] { return this._liveAuctions; } private _liveAuctions: Auction[] = []; /** * A collection of all auctions including historical on zeta-flex */ public get auctions(): Auction[] { return this._auctions; } private _auctions: Auction[] = []; /** * A collection of all current live options on zeta-flex. */ public get liveOptions(): Option[] { return this._liveOptions; } private _liveOptions: Option[] = []; /** * A collection of all created options on zeta-flex. */ public get options(): Option[] { return this._options; } private _options: Option[] = []; /** * A collection of all current live options on zeta-flex. */ public get liveComboOptions(): ComboOption[] { return this._liveComboOptions; } private _liveComboOptions: ComboOption[] = []; /** * A collection of all created combo options on zeta-flex. */ public get comboOptions(): ComboOption[] { return this._comboOptions; } private _comboOptions: ComboOption[] = []; /** * A collection of all the bid accounts created on zeta-flex. */ public get bids(): Bid[] { return this._bids; } private _bids: Bid[] = []; public get underlyings(): Underlying[] { return this._underlyings; } private _underlyings: Underlying[] = []; /** * Stores the latest timestamp received by websocket subscription * to the system clock account. */ public get clockTimestamp(): number { return this._clockTimestamp; } private _clockTimestamp: number; /** * Websocket subscription id for clock. */ private _clockSubscriptionId: number; public async load( programId: PublicKey, network: Network, connection: Connection, wallet = new DummyWallet(), callback?: (event: EventType, data: any) => void ) { if (flex.isInitialized) { throw Error("Program already initialized"); } flex._network = network; flex._provider = new anchor.AnchorProvider( connection, wallet, utils.defaultCommitment() ); flex._program = new anchor.Program( idl as anchor.Idl, programId, flex._provider ) as anchor.Program; let [state, _stateNonce] = flexUtils.getStateAddress( this._program.programId ); let [mintAuthority, _mintAuthNonce] = flexUtils.getMintAuthorityAddress( this._program.programId ); let [vaultAuthority, _vaultAuthNonce] = flexUtils.getVaultAuthorityAddress( this._program.programId ); this._stateAddress = state; this._vaultAuthorityAddress = vaultAuthority; this._mintAuthorityAddress = mintAuthority; await this.subscribeClock(callback); await this.updateState(true); flex._isInitialized = true; } public async initializeState( settlementPriceThresholdSeconds: number, mintOptionFee: number, feeRecipient: PublicKey, accountCloseThresholdSecs: number ) { if (!this.isInitialized) { throw Error("Flex not initialized yet!"); } let tx = new Transaction().add( await instructions.initializeStateIx( settlementPriceThresholdSeconds, mintOptionFee, feeRecipient, accountCloseThresholdSecs ) ); await utils.processTransaction(Program.FLEX, this._provider, tx); await this.updateState(true); } public async updateStateAccount(args: programTypes.UpdateStateAccountArgs) { let tx = new Transaction().add( await instructions.updateStateAccountIx(args) ); await utils.processTransaction(Program.FLEX, this._provider, tx); await this.updateState(true); } public async initializeWhitelistFeesAccount(userToWhitelist: PublicKey) { let [whitelistFeesAccount, _whitelistNonce] = flexUtils.getWhitelistFeesAccountAddress(this.programId, userToWhitelist); let tx = new Transaction().add( await instructions.initializeWhitelistFeesAccountIx( userToWhitelist, whitelistFeesAccount ) ); await utils.processTransaction(Program.FLEX, this._provider, tx); } public async initializeUnderlying( underlyingMint: PublicKey, oracle: PublicKey, underlyingType: UnderlyingType ) { let tx = new Transaction().add( await instructions.initializeUnderlyingIx( underlyingMint, oracle, underlyingType ) ); await utils.processTransaction(Program.FLEX, this._provider, tx); await this.updateState(); } public async expireOptionOverride( overrideSettlementPrice: number, optionAccount: PublicKey, optionType: FlexOptionType ) { let tx = new Transaction().add( await instructions.expireOptionOverrideIx( overrideSettlementPrice, optionAccount, optionType ) ); await utils.processTransaction(Program.FLEX, this._provider, tx); } public async expireOption( optionAccount: PublicKey, optionType: FlexOptionType ) { let tx = new Transaction().add( await instructions.expireOptionIx(optionAccount, optionType) ); await utils.processTransaction(Program.FLEX, this._provider, tx); } private updateUnderlyings( underlyingAccs: ProgramAccount[] ) { let underlyings = []; underlyingAccs.forEach((acc) => { let underlying = acc.account as programTypes.Underlying; underlyings.push({ address: acc.publicKey, underlyingType: toLocalUnderlyingType(underlying.underlyingType), mint: underlying.mint, oracle: underlying.oracle, count: underlying.count.toNumber(), }); }); this._underlyings = underlyings; } public getUnderlying(underlyingMint: PublicKey): Underlying { for (var i = 0; i < this._underlyings.length; i++) { if (this._underlyings[i].mint.equals(underlyingMint)) { return this._underlyings[i]; } } return null; } private updateOptions( optionAccs: ProgramAccount[], comboOptionAccs: ProgramAccount[] ) { let options: Option[] = []; let liveOptions: Option[] = []; optionAccs.forEach((acc) => { let [flexVaultAddress, _nonce] = flexUtils.getVaultAddress( this.programId, acc.publicKey, acc.account.vaultNonce ); let settlementType = toLocalSettlementType(acc.account.settlementType); let option: Option = { optionAccount: acc.publicKey, vault: flexVaultAddress, underlyingCount: acc.account.underlyingCount.toNumber(), optionMint: acc.account.optionMint, underlyingMint: acc.account.underlyingMint, collateralMint: acc.account.collateralMint, exerciseMint: acc.account.exerciseMint, creator: acc.account.creator, strike: acc.account.strike, expiry: settlementType == SettlementType.CASH ? acc.account.expiry.settlementStart.toNumber() : acc.account.expiry.settlementEnd.toNumber(), settlementStart: acc.account.expiry.settlementStart.toNumber(), settlementEnd: acc.account.expiry.settlementEnd.toNumber(), kind: toLocalKind(acc.account.kind), settlementType, creatorExerciseMintTokenAccount: acc.account.creatorExerciseMintTokenAccount, oracleMethod: toLocalOracleMethod(acc.account.oracleMethod), collateralAmount: Number(acc.account.collateralAmount.toString()), settlementPrice: Number(acc.account.settlementPrice.toString()), profitPerOption: Number(acc.account.profitPerOption.toString()), remainingCollateral: Number(acc.account.remainingCollateral.toString()), }; options.push(option); if (this.clockTimestamp < option.expiry) { liveOptions.push(option); } }); this._options = options; this._liveOptions = liveOptions; let comboOptions: ComboOption[] = []; let liveComboOptions: ComboOption[] = []; comboOptionAccs.forEach((acc) => { let [flexVaultAddress, _nonce] = flexUtils.getVaultAddress( this.programId, acc.publicKey, acc.account.vaultNonce ); let settlementType = toLocalSettlementType(acc.account.settlementType); let optionParams: ComboOptionParams[] = []; (acc.account.optionParams as programTypes.ComboOptionParams[]).forEach( (op) => { let strike = op.strike.toNumber(); let kind = toLocalKind(op.kind); let size = op.size.toNumber(); if (strike != 0 || kind != Kind.UNDEFINED || size != 0) { optionParams.push({ strike, kind, size, }); } } ); let comboOption: ComboOption = { optionAccount: acc.publicKey, vault: flexVaultAddress, underlyingCount: acc.account.underlyingCount.toNumber(), optionMint: acc.account.optionMint, underlyingMint: acc.account.underlyingMint, collateralMint: acc.account.collateralMint, creator: acc.account.creator, expiry: acc.account.expiry.settlementStart.toNumber(), settlementStart: acc.account.expiry.settlementStart.toNumber(), settlementEnd: acc.account.expiry.settlementEnd.toNumber(), settlementType, oracleMethod: toLocalOracleMethod(acc.account.oracleMethod), collateralAmount: Number(acc.account.collateralAmount.toString()), settlementPrice: Number(acc.account.settlementPrice.toString()), profitPerOption: Number(acc.account.profitPerOption.toString()), remainingCollateral: Number(acc.account.remainingCollateral.toString()), optionParams, }; comboOptions.push(comboOption); if (this.clockTimestamp < comboOption.expiry) { liveComboOptions.push(comboOption); } }); this._comboOptions = comboOptions; this._liveComboOptions = liveComboOptions; } public async getSettlementAccountForOption( optionAccount: PublicKey, optionType: FlexOptionType ): Promise { let optionAccountInfo = this.getOption(optionAccount, optionType); let underlying = this.getUnderlying(optionAccountInfo.underlyingMint); let [settlementAccount, _settlementAccountNonce] = flexUtils.getSettlementAddress( this.programId, underlying.address, new anchor.BN(optionAccountInfo.expiry) ); let programSettlementAccount = await this.program.account.settlementAccount.fetch(settlementAccount); return { address: settlementAccount, underlyingMint: programSettlementAccount.underlyingMint, expectedSettlementTs: programSettlementAccount.expectedSettlementTs.toNumber(), actualSettlementTs: programSettlementAccount.actualSettlementTs.toNumber(), settlementPrice: programSettlementAccount.settlementPrice.toNumber(), }; } public async getSettlementAccount( settlementAccount: PublicKey ): Promise { let programSettlementAccount = await this.program.account.settlementAccount.fetch(settlementAccount); return { address: settlementAccount, underlyingMint: programSettlementAccount.underlyingMint, expectedSettlementTs: programSettlementAccount.expectedSettlementTs.toNumber(), actualSettlementTs: programSettlementAccount.actualSettlementTs.toNumber(), settlementPrice: programSettlementAccount.settlementPrice.toNumber(), }; } public getOption( optionAccount: PublicKey, optionType: FlexOptionType ): Option | ComboOption | null { switch (optionType) { case FlexOptionType.Normal: for (var i = 0; i < this._options.length; i++) { if (this._options[i].optionAccount.equals(optionAccount)) { return this._options[i]; } } break; case FlexOptionType.Combo: for (var i = 0; i < this._comboOptions.length; i++) { if (this._comboOptions[i].optionAccount.equals(optionAccount)) { return this._comboOptions[i]; } } break; } return null; } public getOptionByMint( optionMint: PublicKey, optionType: FlexOptionType ): Option | ComboOption | null { switch (optionType) { case FlexOptionType.Normal: for (var i = 0; i < this._options.length; i++) { if (this._options[i].optionMint.equals(optionMint)) { return this._options[i]; } } break; case FlexOptionType.Combo: for (var i = 0; i < this._comboOptions.length; i++) { if (this._comboOptions[i].optionMint.equals(optionMint)) { return this._comboOptions[i]; } } break; } return null; } public getOptionsByCreator( creator: PublicKey, optionType: FlexOptionType ): Option[] | ComboOption[] { switch (optionType) { case FlexOptionType.Normal: let options: Option[] = []; for (var i = 0; i < this._options.length; i++) { if (this._options[i].creator.equals(creator)) { options.push(this._options[i]); } } return options; case FlexOptionType.Combo: let comboOptions: ComboOption[] = []; for (var i = 0; i < this._comboOptions.length; i++) { if (this._comboOptions[i].creator.equals(creator)) { comboOptions.push(this._comboOptions[i]); } } return comboOptions; } } public getLiveOptionsByCreator( creator: PublicKey, optionType: FlexOptionType ): Option[] | ComboOption[] { switch (optionType) { case FlexOptionType.Normal: let options: Option[] = []; for (var i = 0; i < this._liveOptions.length; i++) { if (this._liveOptions[i].creator.equals(creator)) { options.push(this._liveOptions[i]); } } return options; case FlexOptionType.Combo: let comboOptions: ComboOption[] = []; for (var i = 0; i < this._liveComboOptions.length; i++) { if (this._liveComboOptions[i].creator.equals(creator)) { comboOptions.push(this._liveComboOptions[i]); } } return comboOptions; } } public getLiveAuctionsByCreator(creator: PublicKey): Auction[] { let auctions: Auction[] = []; for (var i = 0; i < this._liveAuctions.length; i++) { if (this._liveAuctions[i].creator.equals(creator)) { auctions.push(this._liveAuctions[i]); } } return auctions; } public getAuctionsByCreator(creator: PublicKey): Auction[] { let auctions: Auction[] = []; for (var i = 0; i < this._auctions.length; i++) { if (this._auctions[i].creator.equals(creator)) { auctions.push(this._auctions[i]); } } return auctions; } public getAuctionByKey(auctionAccount: PublicKey): Auction { for (var i = 0; i < this._auctions.length; i++) { if (this._auctions[i].address.equals(auctionAccount)) { return this._auctions[i]; } } return null; } public getBidByKey(bidAccount: PublicKey): Bid { for (var i = 0; i < this._bids.length; i++) { if (this._bids[i].address.equals(bidAccount)) { return this._bids[i]; } } return null; } private async updateBidsAndAuctions( bidAccs: ProgramAccount[], auctionAccs: ProgramAccount[] ) { this._bids = bidAccs.map((acc) => { return { address: acc.publicKey, bidder: acc.account.bidder, amount: acc.account.amount.toNumber(), bidEnd: acc.account.bidEnd.toNumber(), cooldownEnd: acc.account.cooldownEnd.toNumber(), auctionAccount: acc.account.auctionAccount, bidVault: acc.account.bidVault, optionAccount: null, bidCurrencyMint: acc.account.bidCurrencyMint, }; }); let auctionBidsMap: Map = new Map(); // Get all the bid accounts to allocate to a specific auction. this._bids.forEach((bid) => { if (!auctionBidsMap.has(bid.auctionAccount.toString())) { auctionBidsMap.set(bid.auctionAccount.toString(), [bid]); } else { let auctionBids = auctionBidsMap.get(bid.auctionAccount.toString()); auctionBids.push(bid); } }); // Sort auction bids from highst to lowest auctionBidsMap.forEach((auctionBids: Bid[], _auctionAccount: String) => { auctionBids.sort((a, b) => b.amount - a.amount); }); let auctions: Auction[] = []; let liveAuctions: Auction[] = []; await Promise.all( auctionAccs.map(async (acc) => { let auctionAccount = acc.publicKey; let [auctionVault, _] = flexUtils.getAuctionVaultAddress( this.programId, acc.account.auctionTokenMint, acc.account.creator, acc.account.amount, acc.account.bidEnd, acc.account.cooldownEnd, acc.account.auctionVaultNonce ); let optionInfo: Option = undefined; for (let i = 0; i < this._options.length; i++) { if ( this._options[i].optionMint.equals(acc.account.auctionTokenMint) ) { optionInfo = this._options[i]; break; } } let comboOptionInfo: ComboOption = undefined; for (let i = 0; i < this._comboOptions.length; i++) { if ( this._comboOptions[i].optionMint.equals( acc.account.auctionTokenMint ) ) { comboOptionInfo = this._comboOptions[i]; } } let optionInfoToStore: Option | ComboOption = undefined; if (optionInfo) { optionInfoToStore = optionInfo; } else if (comboOptionInfo) { optionInfoToStore = comboOptionInfo; } let bids = auctionBidsMap.get(auctionAccount.toString()); if (bids == undefined) { bids = []; } let auction: Auction = { address: auctionAccount, auctionVault, creator: acc.account.creator, creatorBidCurrencyTokenAccount: acc.account.creatorBidCurrencyTokenAccount, amount: acc.account.amount.toNumber(), bidEnd: acc.account.bidEnd.toNumber(), cooldownEnd: acc.account.cooldownEnd.toNumber(), auctionTokenMint: acc.account.auctionTokenMint, bidCurrencyMint: acc.account.bidCurrencyMint, optionInfo: optionInfoToStore, bids, winningBidder: acc.account.winningBidder, exchangeAmount: acc.account.exchangeAmount.toNumber(), }; auctions.push(auction); if ( this.clockTimestamp < auction.cooldownEnd && auction.exchangeAmount == 0 && auction.winningBidder.equals(PublicKey.default) ) { liveAuctions.push(auction); } }) ); this._auctions = auctions; this._liveAuctions = liveAuctions; } public async updateState(refreshStateAccount: boolean = false) { if (refreshStateAccount) { try { this._state = (await this._program.account.state.fetch( this._stateAddress )) as State; } catch (e) { console.log("State account not initialized yet."); } } let decodedUnderlyingAccs: { publicKey: PublicKey; account: programTypes.Underlying; }[] = []; let decodedOptionAccs: { publicKey: PublicKey; account: programTypes.OptionAccount; }[] = []; let decodedComboOptionAccs: { publicKey: PublicKey; account: programTypes.ComboOptionAccount; }[] = []; let decodedBidAccs: { publicKey: PublicKey; account: programTypes.BidAccount; }[] = []; let decodedAuctionAccs: { publicKey: PublicKey; account: programTypes.AuctionAccount; }[] = []; let allProgramAccounts = await this.provider.connection.getProgramAccounts( this.programId ); allProgramAccounts.forEach((rawAcc) => { let slicedDiscrim = rawAcc.account.data.slice( 0, anchor.ACCOUNT_DISCRIMINATOR_SIZE ); if (slicedDiscrim.equals(constants.UNDERLYING_ACC_DISCRIM)) { decodedUnderlyingAccs.push({ publicKey: rawAcc.pubkey, account: this.program.account.underlying.coder.accounts.decode( "Underlying", rawAcc.account.data ), }); } else if (slicedDiscrim.equals(constants.OPTION_ACC_DISCRIM)) { decodedOptionAccs.push({ publicKey: rawAcc.pubkey, account: this.program.account.optionAccount.coder.accounts.decode( "OptionAccount", rawAcc.account.data ), }); } else if (slicedDiscrim.equals(constants.COMBO_OPTION_ACC_DISCRIM)) { decodedComboOptionAccs.push({ publicKey: rawAcc.pubkey, account: this.program.account.comboOptionAccount.coder.accounts.decode( "ComboOptionAccount", rawAcc.account.data ), }); } else if (slicedDiscrim.equals(constants.BID_ACC_DISCRIM)) { decodedBidAccs.push({ publicKey: rawAcc.pubkey, account: this.program.account.bidAccount.coder.accounts.decode( "BidAccount", rawAcc.account.data ), }); } else if (slicedDiscrim.equals(constants.AUCTION_ACC_DISCRIM)) { decodedAuctionAccs.push({ publicKey: rawAcc.pubkey, account: this.program.account.auctionAccount.coder.accounts.decode( "AuctionAccount", rawAcc.account.data ), }); } }); this.updateUnderlyings(decodedUnderlyingAccs); this.updateOptions(decodedOptionAccs, decodedComboOptionAccs); await this.updateBidsAndAuctions(decodedBidAccs, decodedAuctionAccs); } public async closeOptionAccount( optionAccount: PublicKey, optionType: FlexOptionType, returnInstructions: boolean = false ): Promise { let optionInfo = this.getOption(optionAccount, optionType); let ix: anchor.web3.TransactionInstruction; if (optionType == FlexOptionType.Normal) { ix = await instructions.closeOptionAccountIx(optionInfo as Option); } else { ix = await instructions.closeComboOptionAccountIx( optionInfo as ComboOption ); } let tx = new Transaction(); tx.add(ix); return await utils.processTransaction( Program.FLEX, this._provider, tx, undefined, undefined, returnInstructions ); } public async closeAuctionAccount( auctionAccount: PublicKey, returnInstructions: boolean = false ): Promise { let auctionInfo = this.getAuctionByKey(auctionAccount); let ix = await instructions.closeAuctionAccountIx(auctionInfo); let tx = new Transaction(); tx.add(ix); return await utils.processTransaction( Program.FLEX, this._provider, tx, undefined, undefined, returnInstructions ); } private async subscribeClock( callback?: (type: EventType, data: any) => void ) { if (this._clockSubscriptionId !== undefined) { throw Error("Clock already subscribed to."); } this._clockSubscriptionId = this._provider.connection.onAccountChange( SYSVAR_CLOCK_PUBKEY, async (accountInfo: AccountInfo, _context: any) => { this._clockTimestamp = utils.getClockTimestamp(accountInfo); if (callback !== undefined) { callback(EventType.CLOCK, null); } } ); let accountInfo = await this._provider.connection.getAccountInfo( SYSVAR_CLOCK_PUBKEY ); this._clockTimestamp = utils.getClockTimestamp(accountInfo); } public async close() { if (this._clockSubscriptionId !== undefined) { await this._provider.connection.removeAccountChangeListener( this._clockSubscriptionId ); this._clockSubscriptionId = undefined; } } } export const flex = new Flex();