/* eslint-disable import/no-duplicates */ import { ProgramError } from "@project-serum/anchor"; import type { AugmentedProvider } from "@saberhq/solana-contrib"; import { SignerWallet, SolanaProvider } from "@saberhq/solana-contrib"; import { TransactionEnvelope } from "@saberhq/solana-contrib"; import type { TokenAccountData } from "@saberhq/token-utils"; import { deserializeAccount, deserializeAccount as deserializeTokenAccount, getATAAddress, getOrCreateATA, Token, TOKEN_PROGRAM_ID, TokenAmount, u64, } from "@saberhq/token-utils"; import type { AccountInfo, Connection, GetProgramAccountsFilter, TransactionInstruction, } from "@solana/web3.js"; import type { PublicKey } from "@solana/web3.js"; import { Keypair, SystemProgram, SYSVAR_RENT_PUBKEY } from "@solana/web3.js"; import { BN } from "bn.js"; import bs58 from "bs58"; import Decimal from "decimal.js"; import invariant from "tiny-invariant"; import { QuarrySDK } from "../.."; import { QUARRY_ADDRESSES, QUARRY_CODERS } from "../.."; import type { SwapPosition, TokenSwapAccount, UserSwapPoition, } from "../../programs/cremaSwap"; import { calculateTokenAmount, parsePositionsAccount, TokenSwapAccountLayout, } from "../../programs/cremaSwap"; import type { ExchangeRate } from "../../programs/exchangeRate"; import type { PositionData, PositionWrapperData, PositionWrapperDetail, PositionWrapperInfo, PositionWrapperProgram, } from "../../programs/positionWrapper"; import { POSITION_ACCOUNT_SIZE as STAKE_POSITION_ACCOUNT_SIZE, PositionWrapperErrors, WRAPPER_ACCOUNT_SIZE, } from "../../programs/positionWrapper"; import { findPositionAddress, findPositionWrapperAddress, findWrapMintAddress, } from "./pda"; import type { PendingMintAndStake, PendingMintWrapTokens, PendingPositionWrapper, } from "./types"; export class PositionWrapper { readonly program: PositionWrapperProgram; constructor(readonly sdk: QuarrySDK) { this.program = sdk.programs.PositionWrapper; } get provider(): AugmentedProvider { return this.sdk.provider; } async newWrapper({ etrMin, etrMax, swap, baseKP = Keypair.generate(), tokenProgram = TOKEN_PROGRAM_ID, admin = this.provider.wallet.publicKey, payer = this.provider.wallet.publicKey, }: { etrMin: number; etrMax: number; swap: PublicKey; baseKP?: Keypair; tokenProgram?: PublicKey; admin?: PublicKey; payer?: PublicKey; }): Promise { const [wrapper, nonce] = await findPositionWrapperAddress( baseKP.publicKey, this.program.programId ); const [wrapMint, mintNonce] = await findWrapMintAddress( wrapper, this.program.programId ); const tx = new TransactionEnvelope( this.provider, [ this.program.instruction.newWrapper(nonce, mintNonce, etrMin, etrMax, { accounts: { base: baseKP.publicKey, wrapper, swap, wrapMint, admin, payer, tokenProgram, systemProgram: SystemProgram.programId, rent: SYSVAR_RENT_PUBKEY, }, }), ], [baseKP] ); return { positionWrapper: wrapper, wrapMint, tx, }; } updateWrapper( wrapper: PublicKey, etrMin: number, etrMax: number, authority: PublicKey ): TransactionEnvelope { const tx = new TransactionEnvelope(this.provider, [ this.program.instruction.updateWrapper(etrMin, etrMax, { accounts: { wrapper, admin: authority, }, }), ]); return tx; } transferAdmin(wrapper: PublicKey, nextAdmin: PublicKey): TransactionEnvelope { return this.provider.newTX([ this.program.instruction.transferAdmin({ accounts: { wrapper, admin: this.provider.wallet.publicKey, nextAdmin, }, }), ]); } acceptAdmin(wrapper: PublicKey): TransactionEnvelope { return this.provider.newTX([ this.program.instruction.acceptAdmin({ accounts: { wrapper, pendingAdmin: this.provider.wallet.publicKey, }, }), ]); } async mintWrapTokens({ wrapper, positionInfo, authority = this.provider.wallet.publicKey, tokenProgram = TOKEN_PROGRAM_ID, }: { wrapper: PositionWrapperInfo; positionInfo: UserSwapPoition; authority?: PublicKey; tokenProgram?: PublicKey; }): Promise { const instructions: TransactionInstruction[] = []; // Create nft vault account for position wrapper const { address: nftVault, instruction: nftVaultAtaInstruction } = await getOrCreateATA({ provider: this.provider, mint: positionInfo.nftTokenId, owner: wrapper.address, }); if (nftVaultAtaInstruction) { instructions.push(nftVaultAtaInstruction); } // Create wrap token ata account for user if not pass wrapTokenDestination const { address: wrapTokenAccount, instruction: wrapTokenDestinationInstruction, } = await getOrCreateATA({ provider: this.provider, mint: wrapper.wrapMint, owner: this.provider.wallet.publicKey, }); if (wrapTokenDestinationInstruction) { instructions.push(wrapTokenDestinationInstruction); } const wrapTokenDestination = wrapTokenAccount; // Find stake position address const [position, nonce] = await findPositionAddress( positionInfo.nftTokenId, this.program.programId ); const positionAccountInfo = await this.provider.connection.getAccountInfo( position ); if (positionAccountInfo !== null) { console.log( `PDA: ${position.toBase58()} of swap position:${positionInfo.nftTokenId.toBase58()} in wrapper:${wrapper.address.toBase58()} already exist, close it.` ); const tx = new TransactionEnvelope(this.provider, [ this.program.instruction.closePosition({ accounts: { position, nftAccount: positionInfo.nftAccount, authority, }, }), ]); const receipt = await tx.confirm(); console.log("close position tx:", receipt.signature.toString()); } const tx = new TransactionEnvelope(this.provider, [ this.program.instruction.mintWrapTokens(nonce, { accounts: { wrapper: wrapper.address, position, wrapMint: wrapper.wrapMint, wrapTokenDestination, nftMint: positionInfo.nftTokenId, nftVault, nftAccount: positionInfo.nftAccount, swapPosition: positionInfo.positionKey, authority, tokenProgram, systemProgram: SystemProgram.programId, }, }), ]); tx.instructions.unshift(...instructions); return { position, nftVault, tx, }; } async mintAndStake({ wrapper, nftMint, rewarderKey, authority = this.provider.wallet.publicKey, tokenProgram = TOKEN_PROGRAM_ID, }: { wrapper: PositionWrapperInfo; nftMint: PublicKey; rewarderKey: PublicKey; authority?: PublicKey; tokenProgram?: PublicKey; }): Promise { // Get the user swap position const userSwapPosition = await PositionWrapper.fetchSwapPositionByOwner( wrapper.swapKey, nftMint, authority, this.provider.connection ); invariant( userSwapPosition !== null, "Can't find this swap position you own" ); // Mint wrap tokens const mintRes = await this.mintWrapTokens({ wrapper, positionInfo: userSwapPosition, authority, tokenProgram, }); const instructions: TransactionInstruction[] = [...mintRes.tx.instructions]; // Create miner is not exist const rewarder = await this.sdk.mine.loadRewarderWrapper(rewarderKey); const wrapToken = await Token.load( this.sdk.provider.connection, wrapper.wrapMint ); invariant(wrapToken !== null, "Load wrap token failed"); const quarry = await rewarder.getQuarry(wrapToken); const miner = await quarry.getMiner(authority); if (miner === null) { const createMinerRes = await quarry.createMiner({ authority }); instructions.push(...createMinerRes.tx.instructions); } const res = await mintRes.tx.simulate(); if (res.value.err !== null) { console.log(res); } invariant( res.value.err === null, ProgramError.parse(res.value.logs ?? [0], PositionWrapperErrors)?.msg ); const mintEvent = QUARRY_CODERS.PositionWrapper.parseProgramLogEvents( res.value.logs ?? [] )[0]; invariant( mintEvent && mintEvent.name === "MintWrapTokensEvent", "Mint wrap token event not found" ); let stakeAmount = mintEvent.data.amount; const minerAction = await quarry.getMinerActions(authority); const wrapATA = await PositionWrapper.getTokenAccount( this.provider, minerAction.stakedTokenATA ); if (wrapATA !== null) { stakeAmount = stakeAmount.add(wrapATA.amount); } const stakeRes = minerAction.stake( new TokenAmount(minerAction.quarry.token, stakeAmount) ); stakeRes.instructions.unshift(...instructions); return { position: mintRes.position, nftVault: mintRes.nftVault, quarryWrapper: quarry.key, tx: stakeRes, }; } async burnWrapTokens({ wrapper, nftMint, nftAccount, authority = this.provider.wallet.publicKey, tokenProgram = TOKEN_PROGRAM_ID, }: { wrapper: PositionWrapperInfo; nftMint: PublicKey; nftAccount: PublicKey; authority?: PublicKey; tokenProgram?: PublicKey; }): Promise { const [position] = await findPositionAddress(nftMint); const nftVault = await getATAAddress({ mint: nftMint, owner: wrapper.address, }); const wrapTokenAccount = await getATAAddress({ mint: wrapper.wrapMint, owner: authority, }); const tx = new TransactionEnvelope(this.provider, [ this.program.instruction.burnWrapTokens({ accounts: { wrapper: wrapper.address, position, wrapMint: wrapper.wrapMint, wrapTokenAccount, nftVault, nftAccount, authority, tokenProgram, }, }), ]); return tx; } async unstakeAndBurn({ wrapper, nftMint, rewarderKey, isClaim = false, authority = this.provider.wallet.publicKey, tokenProgram = TOKEN_PROGRAM_ID, }: { wrapper: PositionWrapperInfo; nftMint: PublicKey; rewarderKey: PublicKey; isClaim?: boolean; authority?: PublicKey; tokenProgram?: PublicKey; }): Promise { const [position] = await findPositionAddress(nftMint); const positionInfo = await PositionWrapper.fetchStakePosition( position, this.provider.connection ); invariant(positionInfo !== null, "The stake position is null"); const instructions: TransactionInstruction[] = []; const { instruction: wrapTokenATAInstruction } = await getOrCreateATA({ provider: this.provider, mint: wrapper.wrapMint, owner: authority, payer: authority, }); if (wrapTokenATAInstruction) { instructions.push(wrapTokenATAInstruction); } // unstake wrap token const rewarder = await this.sdk.mine.loadRewarderWrapper(rewarderKey); const wrapToken = await Token.load( this.sdk.provider.connection, wrapper.wrapMint ); invariant(wrapToken !== null, "Load wrap token failed"); const quarry = await rewarder.getQuarry(wrapToken); const minerAction = await quarry.getMinerActions(authority); let withdrawAmount = positionInfo.wrapBalance; const wrapATA = await PositionWrapper.getTokenAccount( this.provider, minerAction.stakedTokenATA ); if (wrapATA !== null) { withdrawAmount = withdrawAmount.sub(wrapATA.amount); } const withdrawRes = minerAction.withdraw( new TokenAmount(wrapToken, withdrawAmount) ); instructions.push(...withdrawRes.instructions); const { address: nftAccount, instruction: nftAccountInstruction } = await getOrCreateATA({ provider: this.provider, mint: nftMint, owner: authority, payer: authority, }); if (nftAccountInstruction) { instructions.push(nftAccountInstruction); } // burn wrap token const burnRes = await this.burnWrapTokens({ wrapper, nftMint, nftAccount, authority, tokenProgram, }); instructions.push(...burnRes.instructions); // claim reward if need if (isClaim) { const claimRes = await minerAction.claim(); instructions.push(...claimRes.instructions); } return new TransactionEnvelope(this.provider, instructions); } static async fetchPositionWrapper( wrapper: PublicKey, connection: Connection ): Promise { const accountInfo = await connection.getAccountInfo(wrapper); if (!accountInfo) { return null; } const data = QUARRY_CODERS.PositionWrapper.coder.accounts.decode( "PositionWrapper", accountInfo.data ); return { ...data, address: wrapper }; } static async fetchStakePosition( position: PublicKey, connection: Connection ): Promise { const accountInfo = await connection.getAccountInfo(position); if (!accountInfo) { return null; } return QUARRY_CODERS.PositionWrapper.coder.accounts.decode( "Position", accountInfo.data ); } static async fetchStakePositions( wrapper: PublicKey | null, owner: PublicKey | null, connection: Connection, hold = true ): Promise> { const filters: Array = [ { dataSize: STAKE_POSITION_ACCOUNT_SIZE }, { memcmp: { offset: 177, bytes: hold ? "Ahg1opVcGX" : bs58.encode(new BN(0).toArrayLike(Buffer, "le", 1)), // this is base58 encode [1,0,0,0,0,0,0,0] }, }, ]; if (wrapper !== null) { filters.push({ memcmp: { offset: 8, bytes: wrapper.toBase58(), }, }); } if (owner !== null) { filters.push({ memcmp: { offset: 40, bytes: owner.toBase58(), }, }); } const accounts = await connection.getProgramAccounts( QUARRY_ADDRESSES.PositionWrapper, { filters } ); const positions: Array = []; for (const accountInfo of accounts) { const position = QUARRY_CODERS.PositionWrapper.coder.accounts.decode( "Position", accountInfo.account.data ); positions.push(position); //if (!position.owner.equals(PublicKey.default)) { // positions.push(position); //} } return positions; } static async fetchCremaSwap( swapKey: PublicKey, connection: Connection ): Promise { const accountInfo = await connection.getAccountInfo(swapKey); if (accountInfo === null) return null; return TokenSwapAccountLayout.decode(accountInfo.data); } static async fetchCremaSwaps( swapList: PublicKey[], connection: Connection ): Promise> { const pendings: Array | null>> = []; for (const swapKey of swapList) { pendings.push(connection.getAccountInfo(swapKey)); } const accounts = await Promise.all(pendings); const list: Array = []; for (const accountInfo of accounts) { if (accountInfo === null) { list.push(null); } else { list.push(TokenSwapAccountLayout.decode(accountInfo.data)); } } return list; } static async fetchSwapPositionByIndex( swapPosition: PublicKey, index: number, connection: Connection ): Promise { const accountInfo = await connection.getAccountInfo(swapPosition); if (accountInfo === null) return null; const list = parsePositionsAccount(swapPosition, accountInfo); if (list?.data.positions === undefined) return null; const position = list?.data.positions[index]; if (position === undefined) return null; return { positionKey: swapPosition, ...position, }; } static async fetchSwapPositionByNFT( swapKey: PublicKey, nftMint: PublicKey, connection: Connection ): Promise { const positions = await this.fetchSwapPositions(swapKey, connection); for (const p of positions) { if (p.nftTokenId.equals(nftMint)) { return p; } } return null; } static async fetchSwapPositions( swapKey: PublicKey, connection: Connection ): Promise> { const positionAccounts = await connection.getProgramAccounts( QUARRY_ADDRESSES.CremaSwap, { filters: [ { memcmp: { offset: 1, bytes: swapKey.toBase58(), }, }, { memcmp: { offset: 33, bytes: bs58.encode(new BN(2).toArrayLike(Buffer, "le", 1)), }, }, ], } ); const swapPositions: SwapPosition[] = []; for (const accountInfo of positionAccounts) { const list = parsePositionsAccount( accountInfo.pubkey, accountInfo.account ); if (list?.data.positions === undefined) continue; for (const p of list.data.positions) { swapPositions.push({ positionKey: accountInfo.pubkey, ...p, }); } } return swapPositions; } static async fetchSwapPositionsByOwner( swapKey: PublicKey, owner: PublicKey, connection: Connection ): Promise> { const tokenAccounts = await connection.getTokenAccountsByOwner(owner, { programId: TOKEN_PROGRAM_ID, }); const tokenMints = new Map(); for (const accountInfo of tokenAccounts.value) { const tokenAccount = deserializeTokenAccount(accountInfo.account.data); if (tokenAccount.amount.eq(new u64(1))) { tokenMints.set(tokenAccount.mint.toBase58(), accountInfo.pubkey); } } const positions = await this.fetchSwapPositions(swapKey, connection); const ownerPositions: UserSwapPoition[] = []; for (const position of positions) { const nftAccount = tokenMints.get(position.nftTokenId.toBase58()); if (nftAccount !== undefined) { ownerPositions.push({ ...position, nftAccount, }); } } return ownerPositions; } static async fetchSwapPositionByOwner( swapKey: PublicKey, nftMint: PublicKey, owner: PublicKey, connection: Connection ): Promise { const positions = await this.fetchSwapPositions(swapKey, connection); for (const position of positions) { if (position.nftTokenId.equals(nftMint)) { const accounts = await connection.getTokenAccountsByOwner(owner, { programId: TOKEN_PROGRAM_ID, mint: nftMint, }); for (const accountInfo of accounts.value) { const nftAccount = deserializeTokenAccount(accountInfo.account.data); if (nftAccount.amount.eq(new u64(1))) { return { ...position, nftAccount: accountInfo.pubkey, }; } } } } return null; } static async fetchWrappers( connection: Connection ): Promise> { const filters: Array = [ { dataSize: WRAPPER_ACCOUNT_SIZE }, ]; const accounts = await connection.getProgramAccounts( QUARRY_ADDRESSES.PositionWrapper, { filters } ); const wrappers: Array = []; for (const accountInfo of accounts) { const position = QUARRY_CODERS.PositionWrapper.coder.accounts.decode( "PositionWrapper", accountInfo.account.data ); wrappers.push({ address: accountInfo.pubkey, ...position, }); } return wrappers; } static async fetchWrapperWithDetail( wrapper: PositionWrapperInfo, exchangeRate: ExchangeRate, quote: string | PublicKey, connection: Connection ): Promise { const wrapToken = await connection.getTokenSupply(wrapper.wrapMint); //const wrapToken = await getMintInfo(this.provider, wrapper.wrapMint); const swap = await this.fetchCremaSwap(wrapper.swapKey, connection); invariant(swap !== null, "The swap is null"); const tokenADecimal = exchangeRate.tokenInfo(swap.tokenAMint)?.decimals; const tokenBDecimal = exchangeRate.tokenInfo(swap.tokenBMint)?.decimals; const quoteDecimal = exchangeRate.tokenInfo(quote)?.decimals; invariant( tokenADecimal !== undefined, `token ${swap.tokenAMint.toBase58()} not found` ); invariant( tokenBDecimal !== undefined, `token ${swap.tokenBMint.toBase58()} not found` ); invariant( quoteDecimal !== undefined, `token ${quote.toString()} not found` ); // Calculate the total TVL const stakePositions = await this.fetchStakePositions( wrapper.address, null, connection ); let totalAmountA = new Decimal(0); let totalAmountB = new Decimal(0); let effectiveLiquity = new Decimal(0); for (const position of stakePositions) { const postionTokenAmount = calculateTokenAmount( position.lowerTick, position.upperTick, new Decimal(position.liquity.toString()), swap.currentSqrtPrice ); totalAmountA = totalAmountA.add( postionTokenAmount.lamportsA.div(new Decimal(10).pow(tokenADecimal)) ); totalAmountB = totalAmountB.add( postionTokenAmount.lamportsB.div(new Decimal(10).pow(tokenBDecimal)) ); effectiveLiquity = effectiveLiquity.add( new Decimal(position.wrapBalance.toString()) ); } const totalQuoteAmountA = exchangeRate.swap( swap.tokenAMint, quote, totalAmountA ); const totalQuoteAmountB = exchangeRate.swap( swap.tokenBMint, quote, totalAmountB ); if (totalQuoteAmountA === undefined) { console.log( "swap %s to %s price not found", swap.tokenAMint.toBase58(), quote ); } if (totalQuoteAmountB === undefined) { console.log( "swap %s to %s price not found", swap.tokenBMint.toBase58(), quote ); } let totalTVL = totalQuoteAmountA !== undefined ? totalQuoteAmountA : new Decimal(0); totalTVL = totalQuoteAmountB !== undefined ? totalTVL.add(totalQuoteAmountB) : totalTVL; return { ...wrapper, totalTVL: totalTVL.toDecimalPlaces(quoteDecimal), totalAmountA: totalAmountA.toDecimalPlaces(tokenADecimal), totalAmountB: totalAmountB.toDecimalPlaces(tokenBDecimal), effectiveLiquity: new Decimal(wrapToken.value.amount), }; } static async fetchWrappersWithDetail( exchangeRate: ExchangeRate, quote: string | PublicKey, connection: Connection ): Promise> { const wrappers = await this.fetchWrappers(connection); const details: Array = []; for (const wrapper of wrappers) { const detail = await PositionWrapper.fetchWrapperWithDetail( wrapper, exchangeRate, quote, connection ); details.push(detail); } return details; } static async calculatePositionWrapperAPR( rewarderKey: PublicKey, wrapMint: PublicKey, tvl: Decimal, exchangeRate: ExchangeRate, quote: string | PublicKey, connection: Connection ): Promise<{ apr: Decimal; annualRewardsRate: Decimal; totalRewardsShares: Decimal; rewardShare: Decimal; }> { const provider = SolanaProvider.init({ connection, wallet: new SignerWallet(new Keypair()), }); const sdk = QuarrySDK.load({ provider, }); const wrapToken = await Token.load(connection, wrapMint); invariant( wrapToken !== null, `The wrap token:${wrapMint.toBase58()} not found` ); const rewarder = await sdk.mine.loadRewarderWrapper(rewarderKey); const quarry = await rewarder.getQuarry(wrapToken); const rateQuoteLamports = exchangeRate.swap( rewarder.rewarderData.rewardsTokenMint, quote, new Decimal(rewarder.rewarderData.annualRewardsRate.toString()) ); invariant( rateQuoteLamports !== undefined, `can't find exchange rate for rewarder token with quote:${quote.toString()}` ); const rewardTokenInfo = exchangeRate.tokenInfo( rewarder.rewarderData.rewardsTokenMint ); invariant(rewardTokenInfo !== undefined, `can't find rewarder token info`); const rateQuote = rateQuoteLamports.div( new Decimal(10).pow(rewardTokenInfo.decimals) ); if (quarry.quarryData.rewardsShare.eqn(0) || tvl.eq(new Decimal(0))) { return { apr: new Decimal(0), annualRewardsRate: new Decimal( rewarder.rewarderData.annualRewardsRate.toString() ).div(new Decimal(10).pow(rewardTokenInfo.decimals)), totalRewardsShares: new Decimal( rewarder.rewarderData.totalRewardsShares.toString() ), rewardShare: new Decimal(quarry.quarryData.rewardsShare.toString()), }; } const wrapperAnnualRate = rateQuote .mul(new Decimal(quarry.quarryData.rewardsShare.toString())) .div(new Decimal(rewarder.rewarderData.totalRewardsShares.toString())); const apr = wrapperAnnualRate.div(tvl); return { apr, annualRewardsRate: new Decimal( rewarder.rewarderData.annualRewardsRate.toString() ).div(new Decimal(10).pow(rewardTokenInfo.decimals)), totalRewardsShares: new Decimal( rewarder.rewarderData.totalRewardsShares.toString() ), rewardShare: new Decimal(quarry.quarryData.rewardsShare.toString()), }; } static calculateWrapAmount( wrapper: PositionWrapperInfo, position: SwapPosition ): u64 { const insideUpper = wrapper.etrMax < position.upperTick ? wrapper.etrMax : position.upperTick; const insideLower = wrapper.etrMin > position.lowerTick ? wrapper.etrMin : position.lowerTick; const insideRange = new Decimal(insideUpper - insideLower); const effectiveRange = new Decimal(wrapper.etrMax - wrapper.etrMin); const temp = position.liquity.mul(insideRange.pow(2)).floor(); return new u64(temp.div(effectiveRange.pow(2)).floor().toString()); } static async getTokenAccount( provider: AugmentedProvider, addr: PublicKey ): Promise { const depositorAccInfo = await provider.getAccountInfo(addr); if (depositorAccInfo === null) { return null; } return deserializeAccount(depositorAccInfo.accountInfo.data); } }