@msafe/sui-app-store 0.0.151 → 0.0.152

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/apps/bucket/helper.ts","../src/apps/bucket/intentions/psm.ts","../src/apps/interface/sui.ts","../src/apps/bucket/api/psm.ts","../src/apps/bucket/api/config.ts","../src/apps/cetus/helper.ts","../src/apps/cetus/intentions/add-liquidity.ts","../src/apps/cetus/api/config.ts","../src/apps/cetus/api/position.ts","../src/apps/cetus/intentions/claim-fee-and-mining.ts","../src/apps/cetus/intentions/decrease-liquidity.ts","../src/apps/cetus/intentions/farming-add.ts","../src/apps/cetus/api/farming.ts","../src/apps/cetus/intentions/farming-batch-harvest.ts","../src/apps/cetus/intentions/farming-claim-fee-and-rewards.ts","../src/apps/cetus/intentions/farming-decrease.ts","../src/apps/cetus/intentions/farming-harvest.ts","../src/apps/cetus/intentions/farming-increase.ts","../src/apps/cetus/intentions/farming-remove.ts","../src/apps/cetus/intentions/farming-stake.ts","../src/apps/cetus/intentions/farming-unstake.ts","../src/apps/cetus/intentions/increase-liquidity.ts","../src/apps/cetus/intentions/remove-liquidity.ts","../src/apps/cetus/intentions/swap.ts","../src/apps/cetus/api/swap.ts","../src/apps/cetus/intentions/vesting-redeem.ts","../src/apps/cetus/api/vesting.ts","../src/apps/cetus/intentions/xcetus-cancel.ts","../src/apps/cetus/api/xcetus.ts","../src/apps/cetus/intentions/xcetus-claim.ts","../src/apps/cetus/intentions/xcetus-convert.ts","../src/apps/cetus/intentions/xcetus-redeem.ts","../src/apps/cetus/intentions/xcetus-redeem-lock.ts","../src/apps/mpay/cancel-stream.ts","../src/apps/interface/sui-js.ts","../src/apps/mpay/common/env.ts","../src/apps/mpay/config/dev.json","../src/apps/mpay/config/prod.json","../src/apps/mpay/common/globals.ts","../src/apps/mpay/error/base.ts","../src/apps/mpay/error/NoBackendError.ts","../src/apps/mpay/error/WalletNotConnectedError.ts","../src/apps/mpay/stream/backend.ts","../src/apps/mpay/error/BackendError.ts","../src/apps/mpay/stream/client.ts","../src/apps/mpay/builder/MPayBuilder.ts","../src/apps/mpay/builder/CreateStreamHelper.ts","../src/apps/mpay/builder/const.ts","../src/apps/mpay/common/transaction.ts","../src/apps/mpay/contract/InspectViewer.ts","../src/apps/mpay/error/InvalidRpcResultError.ts","../src/apps/mpay/stream/metadata.ts","../src/apps/mpay/error/InvalidInputError.ts","../src/apps/mpay/sui/utils.ts","../src/apps/mpay/types/wallet.ts","../src/apps/mpay/utils/random.ts","../src/apps/mpay/contract/BaseContract.ts","../src/apps/mpay/const.ts","../src/apps/mpay/contract/FeeContract.ts","../src/apps/mpay/contract/StreamContract.ts","../src/apps/mpay/error/SanityError.ts","../src/apps/mpay/sui/iterator/iterator.ts","../src/apps/mpay/error/NotEnoughBalanceError.ts","../src/apps/mpay/sui/iterator/coin.ts","../src/apps/mpay/stream/Stream.ts","../src/apps/mpay/error/NotCreatorError.ts","../src/apps/mpay/error/NotRecipientError.ts","../src/apps/mpay/error/RpcError.ts","../src/apps/mpay/error/StreamNotFoundError.ts","../src/apps/mpay/utils/utils.ts","../src/apps/mpay/stream/helper.ts","../src/apps/mpay/error/TransactionFailedError.ts","../src/apps/mpay/stream/query.ts","../src/apps/mpay/error/InvalidStreamGroupError.ts","../src/apps/mpay/sui/iterator/object.ts","../src/apps/mpay/stream/StreamGroup.ts","../src/apps/mpay/intention.ts","../src/apps/mpay/claim-by-proxy-stream.ts","../src/apps/mpay/claim-stream.ts","../src/apps/mpay/create-stream.ts","../src/apps/mpay/decoder/moveCall.ts","../src/apps/mpay/decoder/create.ts","../src/apps/mpay/decoder/decoder.ts","../src/apps/mpay/set-auto-claim-stream.ts","../src/apps/mpay/helper.ts","../src/apps/msafe-core/helper.ts","../src/apps/msafe-core/coin-transfer.ts","../src/apps/msafe-core/object-transfer.ts","../src/apps/msafe-core/plain-payload.ts","../src/apps/navi/helper.ts","../src/apps/navi/config.ts","../src/apps/navi/decoder.ts","../src/apps/navi/intentions/claim-reward.ts","../src/apps/navi/api/incentiveV2.ts","../src/apps/navi/intentions/entry-borrow.ts","../src/apps/navi/intentions/entry-deposit.ts","../src/apps/navi/utils/token.ts","../src/apps/navi/intentions/entry-repay.ts","../src/apps/navi/intentions/entry-withdraw.ts","../src/apps/plain-transaction/helper.ts","../src/apps/registry.ts","../src/apps/scallop/helper.ts","../src/apps/scallop/decoders/decoderLending.ts","../src/apps/scallop/decoders/decoder.ts","../src/apps/scallop/constants/common.ts","../src/apps/scallop/constants/enum.ts","../src/apps/scallop/utils/moveCallHelper.ts","../src/apps/scallop/utils/splitCoinHelper.ts","../src/apps/scallop/decoders/decoderReferral.ts","../src/apps/scallop/decoders/decoderVesca.ts","../src/apps/scallop/intentions/scallopCoreBaseIntention.ts","../src/apps/scallop/intentions/lending/borrow.ts","../src/apps/scallop/intentions/lending/borrow-with-boost.ts","../src/apps/scallop/intentions/lending/borrow-with-referral.ts","../src/apps/scallop/intentions/lending/claim-incentive-reward.ts","../src/apps/scallop/intentions/lending/deposit-collateral.ts","../src/apps/scallop/intentions/lending/migrate-and-claim.ts","../src/apps/scallop/intentions/lending/migrate-scoin.ts","../src/apps/scallop/intentions/lending/migrate-wusd-to-usdc.ts","../src/apps/scallop/intentions/lending/open-obligation.ts","../src/apps/scallop/intentions/lending/repay.ts","../src/apps/scallop/intentions/lending/repay-with-boost.ts","../src/apps/scallop/intentions/lending/stake-spool.ts","../src/apps/scallop/intentions/lending/supply-lending.ts","../src/apps/scallop/intentions/lending/unstake-spool.ts","../src/apps/scallop/intentions/lending/withdraw-and-unstake-lending.ts","../src/apps/scallop/intentions/lending/withdraw-collateral.ts","../src/apps/scallop/intentions/lending/withdraw-lending.ts","../src/apps/scallop/intentions/referral/bind-referral.ts","../src/apps/scallop/intentions/referral/claim-revenue-referral.ts","../src/apps/scallop/intentions/referral/create-referral-link.ts","../src/apps/scallop/intentions/staking/extend-period-and-stake-more.ts","../src/apps/scallop/intentions/staking/extend-stake-period.ts","../src/apps/scallop/intentions/staking/redeem-sca.ts","../src/apps/scallop/intentions/staking/renew-exp-stake-period.ts","../src/apps/scallop/intentions/staking/stake-sca.ts","../src/apps/scallop/intentions/staking/supply-and-stake-lending.ts","../src/apps/scallop/intentions/staking/withdraw-staked-sca.ts","../src/apps/scallop/models/scallopAddress.ts","../src/apps/scallop/models/scallopClient.ts","../src/apps/scallop/models/scallopBuilder.ts","../src/apps/scallop/queries/coreQuery.ts","../src/apps/scallop/queries/spoolQuery.ts","../src/apps/scallop/queries/borrowIncentiveQuery.ts","../src/apps/scallop/utils/builder.ts","../src/apps/scallop/utils/query.ts","../src/apps/scallop/utils/util.ts","../src/apps/scallop/queries/priceQuery.ts","../src/apps/scallop/queries/vescaQuery.ts","../src/apps/scallop/models/scallopQuery.ts","../src/apps/scallop/models/scallopUtils.ts","../src/apps/scallop/builders/borrowIncentiveBuilder.ts","../src/apps/scallop/builders/coreBuilder.ts","../src/apps/scallop/builders/oracle.ts","../src/apps/scallop/constants/pyth.ts","../src/apps/scallop/models/pythClient.ts","../src/apps/scallop/builders/sCoinBuilder.ts","../src/apps/scallop/builders/referralBuilder.ts","../src/apps/scallop/builders/slipPageBuilder.ts","../src/apps/scallop/builders/spoolBuilder.ts","../src/apps/scallop/builders/vescaBuilder.ts","../src/apps/scallop/swap/deepbook/swap.ts","../src/apps/scallop/swap/deepbook/txbuilder.ts","../src/apps/scallop/swap/deepbook/contract.ts","../src/apps/scallop/models/scallop.ts","../src/apps/suilend/helper.ts","../src/apps/suilend/decoder.ts","../src/apps/suilend/intentions/borrow.ts","../src/apps/suilend/intentions/suilendBaseIntention.ts","../src/apps/suilend/intentions/deposit.ts","../src/apps/suilend/intentions/repay.ts","../src/apps/suilend/intentions/withdraw.ts","../src/apps/turbos/helper.ts","../src/apps/turbos/decoder.ts","../src/apps/turbos/config.ts","../src/apps/turbos/intentions/add-liquidity.ts","../src/apps/turbos/intentions/burn.ts","../src/apps/turbos/intentions/collect-fee.ts","../src/apps/turbos/intentions/collect-reward.ts","../src/apps/turbos/intentions/create-pool.ts","../src/apps/turbos/intentions/decrease-liquidity.ts","../src/apps/turbos/intentions/increase-liquidity.ts","../src/apps/turbos/intentions/prix-claim.ts","../src/apps/turbos/intentions/prix-join.ts","../src/apps/turbos/intentions/remove-liquidity.ts","../src/apps/turbos/intentions/swap.ts","../src/apps/turbos/intentions/swap-exact-base-for-quote.ts","../src/apps/turbos/api/deepbook.ts","../src/apps/turbos/utils/sui-kit.ts","../src/apps/turbos/intentions/swap-exact-quote-for-base.ts","../src/apps/volo/helper.ts","../src/apps/volo/decoder.ts","../src/apps/volo/config.ts","../src/apps/volo/intentions/claimTicket.ts","../src/apps/volo/intentions/stake.ts","../src/apps/volo/intentions/unStake.ts","../src/index.ts"],"sourcesContent":["import { TransactionType } from '@msafe/sui3-utils';\nimport { SuiClient } from '@mysten/sui/client';\nimport { Transaction } from '@mysten/sui/transactions';\nimport { IdentifierString, WalletAccount } from '@mysten/wallet-standard';\n\nimport { IAppHelperInternal } from '@/apps/interface/sui';\nimport { SuiNetworks } from '@/types';\n\nimport { PsmIntention } from './intentions/psm';\nimport { BucketIntentionData, TransactionSubType } from './types';\n\nexport type BucketIntention = PsmIntention;\n\nexport class BucketHelper implements IAppHelperInternal<BucketIntentionData> {\n application = 'bucket';\n\n supportSDK = '@mysten/sui' as const;\n\n // TODO: Please refer to the documentation and move the `action` and `txbParams` params into the `appContext` structure.\n async deserialize(input: {\n transaction: Transaction;\n chain: IdentifierString;\n network: SuiNetworks;\n suiClient: SuiClient;\n account: WalletAccount;\n action?: string;\n txbParams?: any;\n }): Promise<{ txType: TransactionType; txSubType: string; intentionData: BucketIntentionData }> {\n console.log('Bucket helper deserialize input: ', input);\n const { txbParams, action } = input;\n\n return {\n txType: TransactionType.Other,\n txSubType: action,\n intentionData: {\n txbParams: { ...txbParams },\n action,\n },\n };\n }\n\n async build(input: {\n intentionData: BucketIntentionData;\n txType: TransactionType;\n txSubType: string;\n suiClient: SuiClient;\n account: WalletAccount;\n network: SuiNetworks;\n }): Promise<Transaction> {\n const { suiClient, account, network } = input;\n\n let intention: BucketIntention;\n switch (input.txSubType) {\n case TransactionSubType.Psm:\n intention = PsmIntention.fromData(input.intentionData);\n break;\n default:\n throw new Error('not implemented');\n }\n\n return intention.build({ suiClient, account, network });\n }\n}\n","import { TransactionType } from '@msafe/sui3-utils';\nimport { SuiClient } from '@mysten/sui/client';\nimport { Transaction } from '@mysten/sui/transactions';\nimport { WalletAccount } from '@mysten/wallet-standard';\n\nimport { BaseIntention } from '@/apps/interface/sui';\nimport { SuiNetworks } from '@/types';\n\nimport { BucketIntentionData, TransactionSubType } from '../types';\nimport { getPsmTx } from '../api/psm';\n\nexport class PsmIntention extends BaseIntention<BucketIntentionData> {\n txType = TransactionType.Other;\n\n txSubType = TransactionSubType.Psm;\n\n constructor(public readonly data: BucketIntentionData) {\n super(data);\n }\n\n async build(input: { network: SuiNetworks; suiClient: SuiClient; account: WalletAccount }): Promise<Transaction> {\n const { account, network } = input;\n const { txbParams } = this.data;\n\n const tx = await getPsmTx(txbParams, account, network);\n return tx;\n }\n\n static fromData(data: BucketIntentionData) {\n return new PsmIntention(data);\n }\n}\n","// interface for @mysten/sui package\nimport { TransactionType } from '@msafe/sui3-utils';\nimport { SuiClient } from '@mysten/sui/client';\nimport { Transaction } from '@mysten/sui/transactions';\nimport { IdentifierString, WalletAccount } from '@mysten/wallet-standard';\nimport sortKeys from 'sort-keys-recursive';\n\nimport { SuiNetworks } from '@/types';\n\nexport interface IAppHelperInternal<T> {\n application: string;\n supportSDK: '@mysten/sui';\n\n deserialize(input: {\n transaction: Transaction;\n chain: IdentifierString;\n network: SuiNetworks;\n suiClient: SuiClient;\n account: WalletAccount;\n appContext?: any;\n }): Promise<{\n txType: TransactionType;\n txSubType: string;\n intentionData: T;\n }>;\n\n build(input: {\n network: SuiNetworks;\n txType: TransactionType;\n txSubType: string;\n intentionData: T;\n suiClient: SuiClient;\n account: WalletAccount;\n }): Promise<Transaction>;\n}\n\nexport interface TransactionIntention<D> {\n txType: TransactionType;\n txSubType: string;\n data: D;\n\n serialize(): string;\n\n build(input: { suiClient: SuiClient; account: WalletAccount; network: SuiNetworks }): Promise<Transaction>;\n}\n\nexport abstract class BaseIntention<D> implements TransactionIntention<D> {\n abstract txType: TransactionType;\n\n abstract txSubType: string;\n\n protected constructor(public readonly data: D) {}\n\n abstract build(input: { network: SuiNetworks; suiClient: SuiClient; account: WalletAccount }): Promise<Transaction>;\n\n serialize() {\n return JSON.stringify(sortKeys(this.data));\n }\n}\n","import { SuiNetworks } from \"@/types\";\nimport { Transaction } from \"@mysten/sui/transactions\";\nimport { WalletAccount } from '@mysten/wallet-standard';\nimport { getBucketClient } from \"./config\";\n\nexport interface PsmIntentionData {\n coin: string;\n amount: string;\n isIn: boolean;\n}\n\nexport const getPsmTx = async (\n txbParams: PsmIntentionData,\n account: WalletAccount,\n network: SuiNetworks,\n): Promise<Transaction> => {\n const { coin, amount, isIn } = txbParams;\n\n const tx = new Transaction();\n const client = getBucketClient(network, account);\n await client.getPsmTx(tx, coin, amount, isIn, account.address);\n\n return tx;\n};\n","import { SuiNetworks } from '@/types';\nimport { WalletAccount } from '@mysten/wallet-standard';\nimport { BucketClient } from 'bucket-protocol-sdk';\n\nexport const getBucketClient = (network: SuiNetworks, account: WalletAccount) => {\n const config = network === 'sui:mainnet' ? 'mainnet' : 'testnet';\n const client = new BucketClient(config, account.address);\n return client;\n};\n","import { TransactionType } from '@msafe/sui3-utils';\nimport { SuiClient } from '@mysten/sui/client';\nimport { Transaction } from '@mysten/sui/transactions';\nimport { IdentifierString, WalletAccount } from '@mysten/wallet-standard';\n\nimport { IAppHelperInternal } from '@/apps/interface/sui';\n\nimport { AddLiquidityIntention } from './intentions/add-liquidity';\nimport { ClaimFeeAndMiningIntention } from './intentions/claim-fee-and-mining';\nimport { DecreaseLiquidityIntention } from './intentions/decrease-liquidity';\nimport { FarmingAddLiquidityIntention } from './intentions/farming-add';\nimport { FarmingBatchHarvestIntention } from './intentions/farming-batch-harvest';\nimport { FarmingClaimFeeAndRewardIntention } from './intentions/farming-claim-fee-and-rewards';\nimport { FarmingDecreaseLiquidityIntention } from './intentions/farming-decrease';\nimport { FarmingHarvestIntention } from './intentions/farming-harvest';\nimport { FarmingIncreaseLiquidityIntention } from './intentions/farming-increase';\nimport { FarmingRemoveLiquidityIntention } from './intentions/farming-remove';\nimport { FarmingStakeIntention } from './intentions/farming-stake';\nimport { FarmingUnstakeIntention } from './intentions/farming-unstake';\nimport { IncreaseLiquidityIntention } from './intentions/increase-liquidity';\nimport { RemoveLiquidityIntention } from './intentions/remove-liquidity';\nimport { SwapIntention } from './intentions/swap';\nimport { VestingRedeemIntention } from './intentions/vesting-redeem';\nimport { XcetusCancelIntention } from './intentions/xcetus-cancel';\nimport { XcetusClaimingStakeRewardsIntention } from './intentions/xcetus-claim';\nimport { XcetusConvertIntention } from './intentions/xcetus-convert';\nimport { XcetusRedeemIntention } from './intentions/xcetus-redeem';\nimport { XcetusRedeemLockIntention } from './intentions/xcetus-redeem-lock';\nimport { SuiNetworks, CetusIntentionData, TransactionSubType } from './types';\n\nexport type CetusIntention =\n | AddLiquidityIntention\n | IncreaseLiquidityIntention\n | FarmingAddLiquidityIntention\n | FarmingIncreaseLiquidityIntention\n | DecreaseLiquidityIntention\n | RemoveLiquidityIntention\n | ClaimFeeAndMiningIntention\n | FarmingDecreaseLiquidityIntention\n | FarmingRemoveLiquidityIntention\n | FarmingClaimFeeAndRewardIntention\n | FarmingHarvestIntention\n | FarmingBatchHarvestIntention\n | FarmingStakeIntention\n | FarmingUnstakeIntention\n | XcetusConvertIntention\n | XcetusRedeemLockIntention\n | XcetusClaimingStakeRewardsIntention\n | XcetusCancelIntention\n | XcetusRedeemIntention\n | VestingRedeemIntention\n | SwapIntention;\n\nexport class CetusHelper implements IAppHelperInternal<CetusIntentionData> {\n application = 'cetus';\n\n supportSDK = '@mysten/sui' as const;\n\n // TODO: Please refer to the documentation and move the `action` and `txbParams` params into the `appContext` structure.\n async deserialize(input: {\n transaction: Transaction;\n chain: IdentifierString;\n network: SuiNetworks;\n suiClient: SuiClient;\n account: WalletAccount;\n action?: string;\n txbParams?: any;\n }): Promise<{ txType: TransactionType; txSubType: string; intentionData: CetusIntentionData }> {\n console.log('Cetus helper deserialize input: ', input);\n const { txbParams, action } = input;\n\n return {\n txType: TransactionType.Other,\n txSubType: action,\n intentionData: {\n txbParams: { ...txbParams },\n action,\n },\n };\n }\n\n async build(input: {\n intentionData: CetusIntentionData;\n txType: TransactionType;\n txSubType: string;\n suiClient: SuiClient;\n account: WalletAccount;\n network: SuiNetworks;\n }): Promise<Transaction> {\n const { suiClient, account, network } = input;\n\n let intention: CetusIntention;\n switch (input.txSubType) {\n case TransactionSubType.OpenAndAddLiquidity:\n intention = AddLiquidityIntention.fromData(input.intentionData);\n break;\n case TransactionSubType.IncreaseLiquidity:\n intention = IncreaseLiquidityIntention.fromData(input.intentionData);\n break;\n case TransactionSubType.DecreaseLiquidity:\n intention = DecreaseLiquidityIntention.fromData(input.intentionData);\n break;\n case TransactionSubType.RemoveLiquidity:\n intention = RemoveLiquidityIntention.fromData(input.intentionData);\n break;\n case TransactionSubType.ClaimFeeAndMining:\n intention = ClaimFeeAndMiningIntention.fromData(input.intentionData);\n break;\n case TransactionSubType.FarmingOpenAndAddLiquidity:\n intention = FarmingAddLiquidityIntention.fromData(input.intentionData);\n break;\n case TransactionSubType.FarmingIncreaseLiquidity:\n intention = FarmingIncreaseLiquidityIntention.fromData(input.intentionData);\n break;\n case TransactionSubType.FarmingDecreaseLiquidity:\n intention = FarmingDecreaseLiquidityIntention.fromData(input.intentionData);\n break;\n case TransactionSubType.FarmingRemoveLiquidity:\n intention = FarmingRemoveLiquidityIntention.fromData(input.intentionData);\n break;\n case TransactionSubType.FarmingClaimFeeAndReward:\n intention = FarmingClaimFeeAndRewardIntention.fromData(input.intentionData);\n break;\n case TransactionSubType.FarmingHarvest:\n intention = FarmingHarvestIntention.fromData(input.intentionData);\n break;\n case TransactionSubType.FarmingBatchHarvest:\n intention = FarmingBatchHarvestIntention.fromData(input.intentionData);\n break;\n case TransactionSubType.FarmingStake:\n intention = FarmingStakeIntention.fromData(input.intentionData);\n break;\n case TransactionSubType.FarmingUnstake:\n intention = FarmingUnstakeIntention.fromData(input.intentionData);\n break;\n case TransactionSubType.xCETUSConvert:\n intention = XcetusConvertIntention.fromData(input.intentionData);\n break;\n case TransactionSubType.xCETUSRedeemLock:\n intention = XcetusRedeemLockIntention.fromData(input.intentionData);\n break;\n case TransactionSubType.xCETUSClaimStakingRwewards:\n intention = XcetusClaimingStakeRewardsIntention.fromData(input.intentionData);\n break;\n case TransactionSubType.xCETUSCancelRedeem:\n intention = XcetusCancelIntention.fromData(input.intentionData);\n break;\n case TransactionSubType.xCETUSRedeem:\n intention = XcetusRedeemIntention.fromData(input.intentionData);\n break;\n case TransactionSubType.VestingRedeem:\n intention = VestingRedeemIntention.fromData(input.intentionData);\n break;\n case TransactionSubType.Swap:\n intention = SwapIntention.fromData(input.intentionData);\n break;\n default:\n throw new Error('not implemented');\n }\n\n return intention.build({ suiClient, account, network });\n }\n}\n","import { TransactionType } from '@msafe/sui3-utils';\nimport { SuiClient } from '@mysten/sui/client';\nimport { Transaction } from '@mysten/sui/transactions';\nimport { WalletAccount } from '@mysten/wallet-standard';\n\nimport { BaseIntention } from '@/apps/interface/sui';\nimport { SuiNetworks } from '@/types';\n\nimport { getAddLiquidityTxb } from '../api/position';\nimport { CetusIntentionData, TransactionSubType } from '../types';\n\nexport class AddLiquidityIntention extends BaseIntention<CetusIntentionData> {\n txType = TransactionType.Other;\n\n txSubType = TransactionSubType.OpenAndAddLiquidity;\n\n constructor(public readonly data: CetusIntentionData) {\n super(data);\n }\n\n async build(input: { network: SuiNetworks; suiClient: SuiClient; account: WalletAccount }): Promise<Transaction> {\n const { account, network } = input;\n const { txbParams } = this.data;\n const txb = await getAddLiquidityTxb(txbParams, account, network);\n return txb;\n }\n\n static fromData(data: CetusIntentionData) {\n return new AddLiquidityIntention(data);\n }\n}\n","import { AggregatorClient, Env } from '@cetusprotocol/aggregator-sdk';\nimport { CetusPeripherySDK, SdkOptions as PeripherySdkOptions } from '@cetusprotocol/cetus-periphery-sdk';\nimport { CetusClmmSDK, SdkOptions } from '@cetusprotocol/cetus-sui-clmm-sdk';\nimport { SuiClient } from '@mysten/sui/client';\nimport { WalletAccount } from '@mysten/wallet-standard';\n\nimport { SuiNetworks } from '../types';\n\nexport const clmmConfig: SdkOptions = {\n fullRpcUrl: 'https://fullnode.mainnet.sui.io/',\n simulationAccount: {\n address: '0x326ce9894f08dcaa337fa232641cc34db957aec9ff6614c1186bc9a7508df0bb',\n },\n cetus_config: {\n package_id: '0x95b8d278b876cae22206131fb9724f701c9444515813042f54f0a426c9a3bc2f',\n published_at: '0x95b8d278b876cae22206131fb9724f701c9444515813042f54f0a426c9a3bc2f',\n config: {\n coin_list_id: '0x8cbc11d9e10140db3d230f50b4d30e9b721201c0083615441707ffec1ef77b23',\n launchpad_pools_id: '0x1098fac992eab3a0ab7acf15bb654fc1cf29b5a6142c4ef1058e6c408dd15115',\n clmm_pools_id: '0x15b6a27dd9ae03eb455aba03b39e29aad74abd3757b8e18c0755651b2ae5b71e',\n admin_cap_id: '0x39d78781750e193ce35c45ff32c6c0c3f2941fa3ddaf8595c90c555589ddb113',\n global_config_id: '0x0408fa4e4a4c03cc0de8f23d0c2bbfe8913d178713c9a271ed4080973fe42d8f',\n coin_list_handle: '0x49136005e90e28c4695419ed4194cc240603f1ea8eb84e62275eaff088a71063',\n launchpad_pools_handle: '0x5e194a8efcf653830daf85a85b52e3ae8f65dc39481d54b2382acda25068375c',\n clmm_pools_handle: '0x37f60eb2d9d227949b95da8fea810db3c32d1e1fa8ed87434fc51664f87d83cb',\n },\n },\n clmm_pool: {\n package_id: '0x1eabed72c53feb3805120a081dc15963c204dc8d091542592abaf7a35689b2fb',\n published_at: '0x70968826ad1b4ba895753f634b0aea68d0672908ca1075a2abdf0fc9e0b2fc6a',\n version: 4,\n config: {\n pools_id: '0xf699e7f2276f5c9a75944b37a0c5b5d9ddfd2471bf6242483b03ab2887d198d0',\n global_config_id: '0xdaa46292632c3c4d8f31f23ea0f9b36a28ff3677e9684980e4438403a67a3d8f',\n global_vault_id: '0xce7bceef26d3ad1f6d9b6f13a953f053e6ed3ca77907516481ce99ae8e588f2b',\n admin_cap_id: '0x89c1a321291d15ddae5a086c9abc533dff697fde3d89e0ca836c41af73e36a75',\n },\n },\n integrate: {\n package_id: '0x996c4d9480708fb8b92aa7acf819fb0497b5ec8e65ba06601cae2fb6db3312c3',\n published_at: '0x8faab90228e4c4df91c41626bbaefa19fc25c514405ac64de54578dec9e6f5ee',\n version: 6,\n },\n deepbook: {\n package_id: '0x000000000000000000000000000000000000000000000000000000000000dee9',\n published_at: '0x000000000000000000000000000000000000000000000000000000000000dee9',\n },\n deepbook_endpoint_v2: {\n package_id: '0x92aee86c01c79146d23938a00c7fff725ee0688c389be36d1bcbe03761b466c6',\n published_at: '0x92aee86c01c79146d23938a00c7fff725ee0688c389be36d1bcbe03761b466c6',\n },\n aggregatorUrl: 'https://api-sui.cetus.zone/router',\n swapCountUrl: 'https://api-sui.cetus.zone/v2/sui/swap/count',\n};\n\nexport const peripheryConfig: PeripherySdkOptions = {\n launchpad: {\n package_id: '0x80d114c5d474eabc2eb2fcd1a0903f1eb5b5096a8dc4184d72453f7a9be728e4',\n published_at: '0x80d114c5d474eabc2eb2fcd1a0903f1eb5b5096a8dc4184d72453f7a9be728e4',\n config: {\n pools_id: '0xfd8d37f7a1276878972d240302c8efe32f577220c1bbc6c8984d8b60dddfcab3',\n admin_cap_id: '0x66c70d58c69353714cc6fe2d3a62492d605a96a9821e2bd8274de17219c69980',\n config_cap_id: '0x02b8d23f033687579966e182c776fe0287cacdbb18bff56c29f141e29a18a4d1',\n },\n },\n ido: {\n package_id: '0x1192c9e20b4b0a8848a73a8c711b43e38f7ea1f307b556aab6ffab4e982e9c59',\n published_at: '0x1192c9e20b4b0a8848a73a8c711b43e38f7ea1f307b556aab6ffab4e982e9c59',\n config: {\n pools_id: '0xefc209b47acf1f23b29d166440904600229e520ad36228aaf2329b7c16be9762',\n admin_cap_id: '0x281859d366951830aeeda90779aa170d8ee6845875545470d33ecb890e78c8ce',\n package_version_id: '0xc93dc996106770af5f4e979b6808518f8cee080f22f35b936f071f59d834bb22',\n },\n },\n xcetus: {\n package_id: '0x9e69acc50ca03bc943c4f7c5304c2a6002d507b51c11913b247159c60422c606',\n published_at: '0x9e69acc50ca03bc943c4f7c5304c2a6002d507b51c11913b247159c60422c606',\n config: {\n xcetus_manager_id: '0x838b3dbade12b1e602efcaf8c8b818fae643e43176462bf14fd196afa59d1d9d',\n lock_manager_id: '0x288b59d9dedb51d0bb6cb5e13bfb30885ecf44f8c9076b6f5221c5ef6644fd28',\n lock_handle_id: '0x7c534bb7b8a2cc21538d0dbedd2437cc64f47106cb4c259b9ff921b5c3cb1a49',\n },\n },\n xcetus_dividends: {\n package_id: '0x785248249ac457dfd378bdc6d2fbbfec9d1daf65e9d728b820eb4888c8da2c10',\n published_at: '0x5aa58e1623885bd93de2331d05c29bf4930e54e56beeabcab8fe5385de2d31dc',\n config: {\n dividend_manager_id: '0x721c990bfc031d074341c6059a113a59c1febfbd2faeb62d49dcead8408fa6b5',\n dividend_admin_id: '0x682ba823134f156eac2bcfb27d85a284954a0e61998dc628c40b9bcb4a46ff30',\n dividend_settle_id: '0xade40abe9f6dd10b83b11085be18f07b63b681cf1c169b041fa16854403388c5',\n venft_dividends_id: '0x9dcdb97b4307684bedaeaf803d381b12321a31ecbb9dad7df2cd5f64384f9456',\n venft_dividends_id_v2: '0xaa21fbc1707786d56302952f8327362f4eb9a431a5bc574834e6d46125390de3',\n },\n },\n cetus_faucet: {\n package_id: '0x6864a6f921804860930db6ddbe2e16acdf8504495ea7481637a1c8b9a8fe54b',\n published_at: '0x6864a6f921804860930db6ddbe2e16acdf8504495ea7481637a1c8b9a8fe54b',\n },\n xtoken: {\n package_id: '',\n published_at: '',\n config: {\n xtoken_manager_id: '',\n lock_manager_id: '',\n lock_handle_id: '',\n },\n },\n xtoken_dividends: {\n package_id: '',\n published_at: '',\n config: {\n dividend_manager_id: '',\n dividend_admin_id: '',\n dividend_settle_id: '',\n },\n },\n token_faucet: {\n package_id: '',\n published_at: '',\n },\n booster: {\n package_id: '',\n published_at: '',\n config: {\n booster_config_id: '',\n booster_pool_handle: '',\n },\n },\n maker_bonus: {\n package_id: '',\n published_at: '',\n config: {\n maker_config_id: '',\n maker_pool_handle: '',\n },\n },\n liquidity_stratefy: {\n package_id: '',\n published_at: '',\n version: undefined,\n config: undefined,\n },\n vaults: {\n package_id: '0xd3453d9be7e35efe222f78a810bb3af1859fd1600926afced8b4936d825c9a05',\n published_at: '0xabbd278f738affe762e9df4765b3409bb1e86a355a4f611ad82b278c18108918',\n version: 1,\n config: {\n admin_cap_id: '0x78a42978709c4032fab7b33b782b5bcef64c1c6603250bf23644650b72144375',\n vaults_manager_id: '0x25b82dd2f5ee486ed1c8af144b89a8931cd9c29dee3a86a1bfe194fdea9d04a6',\n vaults_pool_handle: '0x9036bcc5aa7fd2cceec1659a6a1082871f45bc400c743f50063363457d1738bd',\n haedal: {\n package_id: '0xbde4ba4c2e274a60ce15c1cfff9e5c42e41654ac8b6d906a57efa4bd3c29f47d',\n published_at: '0x1d56b8ec33c3fae897eb7bb1acb79914e8152faed614868928e684c25c8b198d',\n version: 1,\n config: {\n staking_id: '0x47b224762220393057ebf4f70501b6e657c3e56684737568439a04f80849b2ca',\n coin_type: '0xbde4ba4c2e274a60ce15c1cfff9e5c42e41654ac8b6d906a57efa4bd3c29f47d::hasui::HASUI',\n },\n },\n volo: {\n package_id: '0x549e8b69270defbfafd4f94e17ec44cdbdd99820b33bda2278dea3b9a32d3f55',\n published_at: '0x549e8b69270defbfafd4f94e17ec44cdbdd99820b33bda2278dea3b9a32d3f55',\n version: 1,\n config: {\n native_pool: '0x7fa2faa111b8c65bea48a23049bfd81ca8f971a262d981dcd9a17c3825cb5baf',\n vsui_metadata: '0x680cd26af32b2bde8d3361e804c53ec1d1cfe24c7f039eb7f549e8dfde389a60',\n coin_type: '0x549e8b69270defbfafd4f94e17ec44cdbdd99820b33bda2278dea3b9a32d3f55::cert::CERT',\n },\n },\n aftermath: {\n package_id: '0x7f6ce7ade63857c4fd16ef7783fed2dfc4d7fb7e40615abdb653030b76aef0c6',\n published_at: '0x7f6ce7ade63857c4fd16ef7783fed2dfc4d7fb7e40615abdb653030b76aef0c6',\n version: 1,\n config: {\n staked_sui_vault: '0x2f8f6d5da7f13ea37daa397724280483ed062769813b6f31e9788e59cc88994d',\n referral_vault: '0x4ce9a19b594599536c53edb25d22532f82f18038dc8ef618afd00fbbfb9845ef',\n safe: '0xeb685899830dd5837b47007809c76d91a098d52aabbf61e8ac467c59e5cc4610',\n validator_address: '0xd30018ec3f5ff1a3c75656abf927a87d7f0529e6dc89c7ddd1bd27ecb05e3db2',\n coin_type: '0xf325ce1300e8dac124071d3152c5c5ee6174914f8bc2161e88329cf579246efc::afsui::AFSUI',\n },\n },\n },\n },\n limit_order: {\n package_id: '',\n published_at: '',\n version: 1,\n config: {\n rate_orders_indexer_id: '',\n rate_orders_indexer_handle: '',\n global_config_id: '',\n token_list_handle: '',\n user_orders_indexer_id: '',\n user_orders_indexer_handle: '',\n },\n },\n frams: {\n package_id: '0x11ea791d82b5742cc8cab0bf7946035c97d9001d7c3803a93f119753da66f526',\n published_at: '0xd817d90368dafcbf3b051e96546dea6209bffad23289d66025beef80354dcd6b',\n version: 1,\n config: {\n global_config_id: '0x21215f2f6de04b57dd87d9be7bb4e15499aec935e36078e2488f36436d64996e',\n rewarder_manager_id: '0xe0e155a88c77025056da08db5b1701a91b79edb6167462f768e387c3ed6614d5',\n rewarder_manager_handle: '0xb32e312cbb3367d6f3d2b4e57c9225e903d29b7b9f612dae2ddf75bdeb26a5aa',\n admin_cap_id: '0xf10fbf1fea5b7aeaa524b87769461a28c5c977613046360093673991f26d886c',\n },\n },\n dca: {\n package_id: '',\n published_at: '',\n version: 0,\n config: {\n admin_cap_id: '',\n global_config_id: '',\n indexer_id: '',\n user_indexer_id: '',\n in_coin_whitelist_id: '',\n out_coin_whitelist_id: '',\n },\n },\n};\n\nexport const clmmConfigTestnet: SdkOptions = {\n fullRpcUrl: 'https://fullnode.testnet.sui.io/',\n simulationAccount: {\n address: '0xcd0247d0b67e53dde69b285e7a748e3dc390e8a5244eb9dd9c5c53d95e4cf0aa',\n },\n cetus_config: {\n package_id: '0xf5ff7d5ba73b581bca6b4b9fa0049cd320360abd154b809f8700a8fd3cfaf7ca',\n published_at: '0xf5ff7d5ba73b581bca6b4b9fa0049cd320360abd154b809f8700a8fd3cfaf7ca',\n config: {\n coin_list_id: '0x257eb2ba592a5480bba0a97d05338fab17cc3283f8df6998a0e12e4ab9b84478',\n launchpad_pools_id: '0xdc3a7bd66a6dcff73c77c866e87d73826e446e9171f34e1c1b656377314f94da',\n clmm_pools_id: '0x26c85500f5dd2983bf35123918a144de24e18936d0b234ef2b49fbb2d3d6307d',\n admin_cap_id: '0x1a496f6c67668eb2c27c99e07e1d61754715c1acf86dac45020c886ac601edb8',\n global_config_id: '0xe1f3db327e75f7ec30585fa52241edf66f7e359ef550b533f89aa1528dd1be52',\n coin_list_handle: '0x3204350fc603609c91675e07b8f9ac0999b9607d83845086321fca7f469de235',\n launchpad_pools_handle: '0xae67ff87c34aceea4d28107f9c6c62e297a111e9f8e70b9abbc2f4c9f5ec20fd',\n clmm_pools_handle: '0xd28736923703342b4752f5ed8c2f2a5c0cb2336c30e1fed42b387234ce8408ec',\n },\n },\n clmm_pool: {\n package_id: '0x0868b71c0cba55bf0faf6c40df8c179c67a4d0ba0e79965b68b3d72d7dfbf666',\n published_at: '0x1c29d658882c40eeb39a8bb8fe58f71a216a918acb3e3eb3b47d24efd07257f2',\n config: {\n pools_id: '0xc090b101978bd6370def2666b7a31d7d07704f84e833e108a969eda86150e8cf',\n global_config_id: '0x6f4149091a5aea0e818e7243a13adcfb403842d670b9a2089de058512620687a',\n global_vault_id: '0xf3114a74d54cbe56b3e68f9306661c043ede8c6615f0351b0c3a93ce895e1699',\n admin_cap_id: '',\n },\n },\n integrate: {\n package_id: '0x8627c5cdcd8b63bc3daa09a6ab7ed81a829a90cafce6003ae13372d611fbb1a9',\n published_at: '0xf1a5d0c5b0593e41d13f9684ca91365bdfe54a98836c1d33c90e361a031fac74',\n version: 6,\n },\n deepbook: {\n package_id: '0x000000000000000000000000000000000000000000000000000000000000dee9',\n published_at: '0x000000000000000000000000000000000000000000000000000000000000dee9',\n },\n deepbook_endpoint_v2: {\n package_id: '0xa34ffca2c6540e1ca9e53963ab43e7b1eed7b82e37696c743bb7c6179c15dfa6',\n published_at: '0xa34ffca2c6540e1ca9e53963ab43e7b1eed7b82e37696c743bb7c6179c15dfa6',\n },\n aggregatorUrl: 'https://api-sui.devcetus.com/router',\n swapCountUrl: 'https://api-sui.devcetus.com/v2/sui/swap/count',\n};\n\nexport const peripheryConfigTestnet: PeripherySdkOptions = {\n launchpad: {\n package_id: '0x3beee8416089a5cbff9cfd5c0a2ce2937b0452dc7e2a3ab4dc431c7be05c2335',\n published_at: '0x3beee8416089a5cbff9cfd5c0a2ce2937b0452dc7e2a3ab4dc431c7be05c2335',\n config: {\n pools_id: '0xccc10403ab3da4ae943847908e0e674fe1fdab81c6383e4c6dcd0eea0edade3d',\n admin_cap_id: '0x8a72713049dbcfc40902ff209dc5e6066fe455d152baa235957c84d7a3b875ed',\n config_cap_id: '0x16492b4252b01debb60f8a825334020d7fdb9d895b52f8139c98618de30817fc',\n },\n },\n ido: {\n package_id: '0x1352bf18ef20458f7cc773852d4a90b240015a6a54479dda3a1debfc500bf044',\n published_at: '0xbd09a0889ea9970b821512428bab3e2fd01e16809a90a325cd3b3d3573eab6a4',\n config: {\n pools_id: '0x346bee25ab4d15bcfa9484ef5ebd4d7c94eb665ebaa745ff4094936a7f59a8b1',\n admin_cap_id: '0xc1bb19a24d3bb65dfd4f3835637b63347c223c67cde4b0888f1a857974f33cbb',\n package_version_id: '0x3ccf1b38e3259e638b980d4e6b49eac8c5aa94d3cb2ace5e75f0a551c8e67e5e',\n },\n },\n xcetus: {\n package_id: '0xdebaab6b851fd3414c0a62dbdf8eb752d6b0d31f5cfce5e38541bc6c6daa8966',\n published_at: '0xdebaab6b851fd3414c0a62dbdf8eb752d6b0d31f5cfce5e38541bc6c6daa8966',\n config: {\n xcetus_manager_id: '0x3be34cbad122c8b100ed7157d762b9610e68b3c65734e08bc3c3baf857da807d',\n lock_manager_id: '0x7c67e805182e3fecd098bd68a6b06c317f28f8c6249bd771e07904a10b424e60',\n lock_handle_id: '0xc5f3bbfefe9a45c13da7a34bc72cac122ee45d633690476a8ac56bd2c4e78c86',\n },\n },\n xcetus_dividends: {\n package_id: '0x20d948d640edd0c749f533d41efc5f843f212d441220324ad7959c6e1d281828',\n published_at: '0x20d948d640edd0c749f533d41efc5f843f212d441220324ad7959c6e1d281828',\n config: {\n dividend_manager_id: '0x13b7facb704fae1d199ff0038b8acabc253415a77d142b39189dee97d457e442',\n dividend_admin_id: '0x5eb78463007422d4130b21f61c180bcd190819b7792f56e00a61df3b8fb928ef',\n dividend_settle_id: '0x495095e13a170ff494d242ae44ac2c7453011ca6c33cff27498010105e10e4b4',\n venft_dividends_id: '',\n venft_dividends_id_v2: '',\n },\n },\n cetus_faucet: {\n package_id: '0x1a69aee6be709054750949959a67aedbb4200583b39586d5e3eabe57f40012c7',\n published_at: '0x1a69aee6be709054750949959a67aedbb4200583b39586d5e3eabe57f40012c7',\n },\n xtoken: {\n package_id: '',\n published_at: '',\n config: {\n xtoken_manager_id: '',\n lock_manager_id: '',\n lock_handle_id: '',\n },\n },\n xtoken_dividends: {\n package_id: '',\n published_at: '',\n config: {\n dividend_manager_id: '',\n dividend_admin_id: '',\n dividend_settle_id: '',\n },\n },\n token_faucet: {\n package_id: '',\n published_at: '',\n },\n booster: {\n package_id: '',\n published_at: '',\n config: {\n booster_config_id: '',\n booster_pool_handle: '',\n },\n },\n maker_bonus: {\n package_id: '',\n published_at: '',\n config: {\n maker_config_id: '',\n maker_pool_handle: '',\n },\n },\n liquidity_stratefy: {\n package_id: '',\n published_at: '',\n version: undefined,\n config: undefined,\n },\n vaults: {\n package_id: '0x25cff94bdb454bae6a5565d09047bfe2b230025ef3bd2199622ec48d854b86b9',\n published_at: '0x25cff94bdb454bae6a5565d09047bfe2b230025ef3bd2199622ec48d854b86b9',\n config: {\n admin_cap_id: '0x9b2d6f5be2650d16d27cd630c4539a76d7793970343ed3cbb023e13f1637c07c',\n vaults_manager_id: '0xc0a1a937df08880e395d85014ff40c74f13abe7a53abdbffea36f51adaaaf79e',\n vaults_pool_handle: '0x3ab02203de753de9c8198cc0ce7594dc960878f2c34c5c5a4b7742082241860a',\n },\n },\n limit_order: {\n package_id: '',\n published_at: '',\n version: 1,\n config: {\n rate_orders_indexer_id: '',\n rate_orders_indexer_handle: '',\n global_config_id: '',\n token_list_handle: '',\n user_orders_indexer_id: '',\n user_orders_indexer_handle: '',\n },\n },\n frams: {\n package_id: '0xfa0d98e99c1dbdbea1b0fe089fa93ebab40a7719ae4160c42cc78ebfe029fda0',\n published_at: '0xfa0d98e99c1dbdbea1b0fe089fa93ebab40a7719ae4160c42cc78ebfe029fda0',\n config: {\n global_config_id: '0x5082c7a5ee9a758025d7b0a5e8aa08b56625c7cd535b8909d2b7993991e229cc',\n rewarder_manager_id: '0xe789e092dbd9dceadbe89350c4761a6f2e11647aab97f09746a01b151926cc0e',\n rewarder_manager_handle: '0x7e7dd42392b5d82564dc9ad5093a111c5f0598cc9f806cff257d7dacb71f7837',\n admin_cap_id: '0x4ec248bca2d1fc05f39fd7491ab490464a46d128624caa4d3c2a66d957ef40b0',\n },\n },\n dca: {\n package_id: '',\n published_at: '',\n version: 0,\n config: {\n admin_cap_id: '',\n global_config_id: '',\n indexer_id: '',\n user_indexer_id: '',\n in_coin_whitelist_id: '',\n out_coin_whitelist_id: '',\n },\n },\n};\n\nexport const getClmmSdk = (network: SuiNetworks, account: WalletAccount) => {\n const config = network === 'sui:mainnet' ? clmmConfig : clmmConfigTestnet;\n const clmmSdk = new CetusClmmSDK(config);\n clmmSdk.senderAddress = account.address;\n return clmmSdk;\n};\n\nexport const getPeripherySdk = (network: SuiNetworks, account: WalletAccount) => {\n const clmmSdk = getClmmSdk(network, account);\n const config = network === 'sui:mainnet' ? peripheryConfig : peripheryConfigTestnet;\n const peripherySdk = new CetusPeripherySDK(config, clmmSdk);\n return peripherySdk;\n};\n\nconst aggregatorURL = 'https://api-sui.cetus.zone/router_v2/find_routes';\nexport const getAggregatorSdk = (network: SuiNetworks, account: WalletAccount) => {\n const suiClient = new SuiClient({\n url: 'https://fullnode.mainnet.sui.io/',\n });\n const aggregatorSdk = new AggregatorClient(aggregatorURL, account.address, suiClient, Env.Mainnet);\n return aggregatorSdk;\n};\n","import { Transaction } from '@mysten/sui/transactions';\nimport { WalletAccount } from '@mysten/wallet-standard';\n\nimport { SuiNetworks } from '@/types';\n\nimport { getClmmSdk } from './config';\n\nexport const getAddLiquidityTxb = async (\n txbParams: any,\n account: WalletAccount,\n network: SuiNetworks,\n): Promise<Transaction> => {\n const clmmSdk = getClmmSdk(network, account);\n const txb: Transaction = await clmmSdk.Position.createAddLiquidityFixTokenPayload(\n txbParams?.parameter,\n txbParams?.gasEstimateArg,\n );\n return txb;\n};\n\nexport const getIncreaseLiquidityTxb = async (\n txbParams: any,\n account: WalletAccount,\n network: SuiNetworks,\n): Promise<Transaction> => {\n const clmmSdk = getClmmSdk(network, account);\n const txb: Transaction = await clmmSdk.Position.createAddLiquidityFixTokenPayload(\n txbParams?.parameter,\n txbParams?.gasEstimateArg,\n );\n return txb;\n};\n\nexport const getRemoveLiquidityTxb = async (\n txbParams: any,\n account: WalletAccount,\n network: SuiNetworks,\n): Promise<Transaction> => {\n const clmmSdk = getClmmSdk(network, account);\n const txb: Transaction = await clmmSdk.Position.closePositionTransactionPayload(txbParams);\n return txb;\n};\n\nexport const getDecreaseLiquidityTxb = async (\n txbParams: any,\n account: WalletAccount,\n network: SuiNetworks,\n): Promise<Transaction> => {\n const clmmSdk = getClmmSdk(network, account);\n const txb: Transaction = await clmmSdk.Position.removeLiquidityTransactionPayload(txbParams);\n return txb;\n};\n\nexport const getClaimFeeAndMiningTxb = async (\n txbParams: any,\n account: WalletAccount,\n network: SuiNetworks,\n): Promise<Transaction> => {\n const clmmSdk = getClmmSdk(network, account);\n const txb: Transaction = await clmmSdk.Rewarder.collectRewarderTransactionPayload(txbParams);\n return txb;\n};\n","import { TransactionType } from '@msafe/sui3-utils';\nimport { SuiClient } from '@mysten/sui/client';\nimport { Transaction } from '@mysten/sui/transactions';\nimport { WalletAccount } from '@mysten/wallet-standard';\n\nimport { BaseIntention } from '@/apps/interface/sui';\nimport { SuiNetworks } from '@/types';\n\nimport { getClaimFeeAndMiningTxb } from '../api/position';\nimport { CetusIntentionData, TransactionSubType } from '../types';\n\nexport class ClaimFeeAndMiningIntention extends BaseIntention<CetusIntentionData> {\n txType = TransactionType.Other;\n\n txSubType = TransactionSubType.ClaimFeeAndMining;\n\n constructor(public readonly data: CetusIntentionData) {\n super(data);\n }\n\n async build(input: { suiClient: SuiClient; account: WalletAccount; network: SuiNetworks }): Promise<Transaction> {\n const { account, network } = input;\n const { txbParams } = this.data;\n const txb = await getClaimFeeAndMiningTxb(txbParams, account, network);\n return txb;\n }\n\n static fromData(data: CetusIntentionData) {\n return new ClaimFeeAndMiningIntention(data);\n }\n}\n","import { TransactionType } from '@msafe/sui3-utils';\nimport { SuiClient } from '@mysten/sui/client';\nimport { Transaction } from '@mysten/sui/transactions';\nimport { WalletAccount } from '@mysten/wallet-standard';\n\nimport { BaseIntention } from '@/apps/interface/sui';\nimport { SuiNetworks } from '@/types';\n\nimport { getDecreaseLiquidityTxb } from '../api/position';\nimport { CetusIntentionData, TransactionSubType } from '../types';\n\nexport class DecreaseLiquidityIntention extends BaseIntention<CetusIntentionData> {\n txType = TransactionType.Other;\n\n txSubType = TransactionSubType.DecreaseLiquidity;\n\n constructor(public readonly data: CetusIntentionData) {\n super(data);\n }\n\n async build(input: { suiClient: SuiClient; account: WalletAccount; network: SuiNetworks }): Promise<Transaction> {\n const { account, network } = input;\n const { txbParams } = this.data;\n const txb = await getDecreaseLiquidityTxb(txbParams, account, network);\n return txb;\n }\n\n static fromData(data: CetusIntentionData) {\n return new DecreaseLiquidityIntention(data);\n }\n}\n","import { TransactionType } from '@msafe/sui3-utils';\nimport { SuiClient } from '@mysten/sui/client';\nimport { Transaction } from '@mysten/sui/transactions';\nimport { WalletAccount } from '@mysten/wallet-standard';\n\nimport { BaseIntention } from '@/apps/interface/sui';\nimport { SuiNetworks } from '@/types';\n\nimport { getFarmingAddLiquidityTxb } from '../api/farming';\nimport { CetusIntentionData, TransactionSubType } from '../types';\n\nexport class FarmingAddLiquidityIntention extends BaseIntention<CetusIntentionData> {\n txType = TransactionType.Other;\n\n txSubType = TransactionSubType.FarmingOpenAndAddLiquidity;\n\n constructor(public readonly data: CetusIntentionData) {\n super(data);\n }\n\n async build(input: { suiClient: SuiClient; account: WalletAccount; network: SuiNetworks }): Promise<Transaction> {\n const { account, network } = input;\n const { txbParams } = this.data;\n const txb = await getFarmingAddLiquidityTxb(txbParams, account, network);\n return txb;\n }\n\n static fromData(data: CetusIntentionData) {\n return new FarmingAddLiquidityIntention(data);\n }\n}\n","import { Transaction } from '@mysten/sui/transactions';\nimport { WalletAccount } from '@mysten/wallet-standard';\n\nimport { SuiNetworks } from '@/types';\n\nimport { getPeripherySdk } from './config';\n\nexport const getFarmingAddLiquidityTxb = async (\n txbParams: any,\n account: WalletAccount,\n network: SuiNetworks,\n): Promise<Transaction> => {\n const peripherySdk = getPeripherySdk(network, account);\n const txb: Transaction = await peripherySdk.Farms.openPositionAddLiquidityStakePaylod(txbParams);\n return txb;\n};\n\nexport const getFarmingIncreaseLiquidityTxb = async (\n txbParams: any,\n account: WalletAccount,\n network: SuiNetworks,\n): Promise<Transaction> => {\n const peripherySdk = getPeripherySdk(network, account);\n const txb: Transaction = await peripherySdk.Farms.addLiquidityFixCoinPayload(txbParams);\n return txb;\n};\n\nexport const getFarmingDecreaseLiquidityTxb = async (\n txbParams: any,\n account: WalletAccount,\n network: SuiNetworks,\n): Promise<Transaction> => {\n const peripherySdk = getPeripherySdk(network, account);\n const txb: Transaction = await peripherySdk.Farms.removeLiquidityPayload(txbParams);\n return txb;\n};\n\nexport const getFarmingRemoveLiquidityTxb = async (\n txbParams: any,\n account: WalletAccount,\n network: SuiNetworks,\n): Promise<Transaction> => {\n const peripherySdk = getPeripherySdk(network, account);\n const txb: Transaction = await peripherySdk.Farms.removeLiquidityPayload(txbParams);\n return txb;\n};\n\nexport const getFarmingClaimFeeAndRewardTxb = async (\n txbParams: any,\n account: WalletAccount,\n network: SuiNetworks,\n): Promise<Transaction> => {\n const peripherySdk = getPeripherySdk(network, account);\n const txb: Transaction = await peripherySdk.Farms.claimFeeAndClmmReward(txbParams);\n return txb;\n};\n\nexport const getFarmingHarvest = async (\n txbParams: any,\n account: WalletAccount,\n network: SuiNetworks,\n): Promise<Transaction> => {\n const peripherySdk = getPeripherySdk(network, account);\n const txb: Transaction = await peripherySdk.Farms.harvestPayload(txbParams);\n return txb;\n};\n\nexport const getFarmingBatchHarvest = async (\n txbParams: any,\n account: WalletAccount,\n network: SuiNetworks,\n): Promise<Transaction> => {\n const peripherySdk = getPeripherySdk(network, account);\n const params: any = Object.values(txbParams);\n const txb: Transaction = await peripherySdk.Farms.batchHarvestPayload(params);\n return txb;\n};\n\nexport const getFarmingStake = async (\n txbParams: any,\n account: WalletAccount,\n network: SuiNetworks,\n): Promise<Transaction> => {\n const peripherySdk = getPeripherySdk(network, account);\n const txb: Transaction = await peripherySdk.Farms.depositPayload(txbParams);\n return txb;\n};\n\nexport const getFarmingUnstake = async (\n txbParams: any,\n account: WalletAccount,\n network: SuiNetworks,\n): Promise<Transaction> => {\n const peripherySdk = getPeripherySdk(network, account);\n const txb: Transaction = await peripherySdk.Farms.withdrawPayload(txbParams);\n return txb;\n};\n","import { TransactionType } from '@msafe/sui3-utils';\nimport { SuiClient } from '@mysten/sui/client';\nimport { Transaction } from '@mysten/sui/transactions';\nimport { WalletAccount } from '@mysten/wallet-standard';\n\nimport { BaseIntention } from '@/apps/interface/sui';\nimport { SuiNetworks } from '@/types';\n\nimport { getFarmingBatchHarvest } from '../api/farming';\nimport { CetusIntentionData, TransactionSubType } from '../types';\n\nexport class FarmingBatchHarvestIntention extends BaseIntention<CetusIntentionData> {\n txType = TransactionType.Other;\n\n txSubType = TransactionSubType.FarmingBatchHarvest;\n\n constructor(public readonly data: CetusIntentionData) {\n super(data);\n }\n\n async build(input: { suiClient: SuiClient; account: WalletAccount; network: SuiNetworks }): Promise<Transaction> {\n const { account, network } = input;\n const { txbParams } = this.data;\n const txb = await getFarmingBatchHarvest(txbParams, account, network);\n return txb;\n }\n\n static fromData(data: CetusIntentionData) {\n return new FarmingBatchHarvestIntention(data);\n }\n}\n","import { TransactionType } from '@msafe/sui3-utils';\nimport { SuiClient } from '@mysten/sui/client';\nimport { Transaction } from '@mysten/sui/transactions';\nimport { WalletAccount } from '@mysten/wallet-standard';\n\nimport { BaseIntention } from '@/apps/interface/sui';\nimport { SuiNetworks } from '@/types';\n\nimport { getFarmingClaimFeeAndRewardTxb } from '../api/farming';\nimport { CetusIntentionData, TransactionSubType } from '../types';\n\nexport class FarmingClaimFeeAndRewardIntention extends BaseIntention<CetusIntentionData> {\n txType = TransactionType.Other;\n\n txSubType = TransactionSubType.FarmingClaimFeeAndReward;\n\n constructor(public readonly data: CetusIntentionData) {\n super(data);\n }\n\n async build(input: { suiClient: SuiClient; account: WalletAccount; network: SuiNetworks }): Promise<Transaction> {\n const { account, network } = input;\n const { txbParams } = this.data;\n const txb = await getFarmingClaimFeeAndRewardTxb(txbParams, account, network);\n return txb;\n }\n\n static fromData(data: CetusIntentionData) {\n return new FarmingClaimFeeAndRewardIntention(data);\n }\n}\n","import { TransactionType } from '@msafe/sui3-utils';\nimport { SuiClient } from '@mysten/sui/client';\nimport { Transaction } from '@mysten/sui/transactions';\nimport { WalletAccount } from '@mysten/wallet-standard';\n\nimport { BaseIntention } from '@/apps/interface/sui';\nimport { SuiNetworks } from '@/types';\n\nimport { getFarmingDecreaseLiquidityTxb } from '../api/farming';\nimport { CetusIntentionData, TransactionSubType } from '../types';\n\nexport class FarmingDecreaseLiquidityIntention extends BaseIntention<CetusIntentionData> {\n txType = TransactionType.Other;\n\n txSubType = TransactionSubType.FarmingDecreaseLiquidity;\n\n constructor(public readonly data: CetusIntentionData) {\n super(data);\n }\n\n async build(input: { suiClient: SuiClient; account: WalletAccount; network: SuiNetworks }): Promise<Transaction> {\n const { account, network } = input;\n const { txbParams } = this.data;\n const txb = await getFarmingDecreaseLiquidityTxb(txbParams, account, network);\n return txb;\n }\n\n static fromData(data: CetusIntentionData) {\n return new FarmingDecreaseLiquidityIntention(data);\n }\n}\n","import { TransactionType } from '@msafe/sui3-utils';\nimport { SuiClient } from '@mysten/sui/client';\nimport { Transaction } from '@mysten/sui/transactions';\nimport { WalletAccount } from '@mysten/wallet-standard';\n\nimport { BaseIntention } from '@/apps/interface/sui';\nimport { SuiNetworks } from '@/types';\n\nimport { getFarmingHarvest } from '../api/farming';\nimport { CetusIntentionData, TransactionSubType } from '../types';\n\nexport class FarmingHarvestIntention extends BaseIntention<CetusIntentionData> {\n txType = TransactionType.Other;\n\n txSubType = TransactionSubType.FarmingHarvest;\n\n constructor(public readonly data: CetusIntentionData) {\n super(data);\n }\n\n async build(input: { suiClient: SuiClient; account: WalletAccount; network: SuiNetworks }): Promise<Transaction> {\n const { account, network } = input;\n const { txbParams } = this.data;\n const txb = await getFarmingHarvest(txbParams, account, network);\n return txb;\n }\n\n static fromData(data: CetusIntentionData) {\n return new FarmingHarvestIntention(data);\n }\n}\n","import { TransactionType } from '@msafe/sui3-utils';\nimport { SuiClient } from '@mysten/sui/client';\nimport { Transaction } from '@mysten/sui/transactions';\nimport { WalletAccount } from '@mysten/wallet-standard';\n\nimport { BaseIntention } from '@/apps/interface/sui';\nimport { SuiNetworks } from '@/types';\n\nimport { getFarmingIncreaseLiquidityTxb } from '../api/farming';\nimport { CetusIntentionData, TransactionSubType } from '../types';\n\nexport class FarmingIncreaseLiquidityIntention extends BaseIntention<CetusIntentionData> {\n txType = TransactionType.Other;\n\n txSubType = TransactionSubType.FarmingIncreaseLiquidity;\n\n constructor(public readonly data: CetusIntentionData) {\n super(data);\n }\n\n async build(input: { suiClient: SuiClient; account: WalletAccount; network: SuiNetworks }): Promise<Transaction> {\n const { account, network } = input;\n const { txbParams } = this.data;\n const txb = await getFarmingIncreaseLiquidityTxb(txbParams, account, network);\n return txb;\n }\n\n static fromData(data: CetusIntentionData) {\n return new FarmingIncreaseLiquidityIntention(data);\n }\n}\n","import { TransactionType } from '@msafe/sui3-utils';\nimport { SuiClient } from '@mysten/sui/client';\nimport { Transaction } from '@mysten/sui/transactions';\nimport { WalletAccount } from '@mysten/wallet-standard';\n\nimport { BaseIntention } from '@/apps/interface/sui';\nimport { SuiNetworks } from '@/types';\n\nimport { getFarmingRemoveLiquidityTxb } from '../api/farming';\nimport { CetusIntentionData, TransactionSubType } from '../types';\n\nexport class FarmingRemoveLiquidityIntention extends BaseIntention<CetusIntentionData> {\n txType = TransactionType.Other;\n\n txSubType = TransactionSubType.FarmingRemoveLiquidity;\n\n constructor(public readonly data: CetusIntentionData) {\n super(data);\n }\n\n async build(input: { suiClient: SuiClient; account: WalletAccount; network: SuiNetworks }): Promise<Transaction> {\n const { account, network } = input;\n const { txbParams } = this.data;\n const txb = await getFarmingRemoveLiquidityTxb(txbParams, account, network);\n return txb;\n }\n\n static fromData(data: CetusIntentionData) {\n return new FarmingRemoveLiquidityIntention(data);\n }\n}\n","import { TransactionType } from '@msafe/sui3-utils';\nimport { SuiClient } from '@mysten/sui/client';\nimport { Transaction } from '@mysten/sui/transactions';\nimport { WalletAccount } from '@mysten/wallet-standard';\n\nimport { BaseIntention } from '@/apps/interface/sui';\nimport { SuiNetworks } from '@/types';\n\nimport { getFarmingStake } from '../api/farming';\nimport { CetusIntentionData, TransactionSubType } from '../types';\n\nexport class FarmingStakeIntention extends BaseIntention<CetusIntentionData> {\n txType = TransactionType.Other;\n\n txSubType = TransactionSubType.FarmingStake;\n\n constructor(public readonly data: CetusIntentionData) {\n super(data);\n }\n\n async build(input: { suiClient: SuiClient; account: WalletAccount; network: SuiNetworks }): Promise<Transaction> {\n const { account, network } = input;\n const { txbParams } = this.data;\n const txb = await getFarmingStake(txbParams, account, network);\n return txb;\n }\n\n static fromData(data: CetusIntentionData) {\n return new FarmingStakeIntention(data);\n }\n}\n","import { TransactionType } from '@msafe/sui3-utils';\nimport { SuiClient } from '@mysten/sui/client';\nimport { Transaction } from '@mysten/sui/transactions';\nimport { WalletAccount } from '@mysten/wallet-standard';\n\nimport { BaseIntention } from '@/apps/interface/sui';\nimport { SuiNetworks } from '@/types';\n\nimport { getFarmingUnstake } from '../api/farming';\nimport { CetusIntentionData, TransactionSubType } from '../types';\n\nexport class FarmingUnstakeIntention extends BaseIntention<CetusIntentionData> {\n txType = TransactionType.Other;\n\n txSubType = TransactionSubType.FarmingUnstake;\n\n constructor(public readonly data: CetusIntentionData) {\n super(data);\n }\n\n async build(input: { suiClient: SuiClient; account: WalletAccount; network: SuiNetworks }): Promise<Transaction> {\n const { account, network } = input;\n const { txbParams } = this.data;\n const txb = await getFarmingUnstake(txbParams, account, network);\n return txb;\n }\n\n static fromData(data: CetusIntentionData) {\n return new FarmingUnstakeIntention(data);\n }\n}\n","import { TransactionType } from '@msafe/sui3-utils';\nimport { SuiClient } from '@mysten/sui/client';\nimport { Transaction } from '@mysten/sui/transactions';\nimport { WalletAccount } from '@mysten/wallet-standard';\n\nimport { BaseIntention } from '@/apps/interface/sui';\nimport { SuiNetworks } from '@/types';\n\nimport { getIncreaseLiquidityTxb } from '../api/position';\nimport { CetusIntentionData, TransactionSubType } from '../types';\n\nexport class IncreaseLiquidityIntention extends BaseIntention<CetusIntentionData> {\n txType = TransactionType.Other;\n\n txSubType = TransactionSubType.IncreaseLiquidity;\n\n constructor(public readonly data: CetusIntentionData) {\n super(data);\n }\n\n async build(input: { suiClient: SuiClient; account: WalletAccount; network: SuiNetworks }): Promise<Transaction> {\n const { account, network } = input;\n const { txbParams } = this.data;\n const txb = await getIncreaseLiquidityTxb(txbParams, account, network);\n return txb;\n }\n\n static fromData(data: CetusIntentionData) {\n return new IncreaseLiquidityIntention(data);\n }\n}\n","import { TransactionType } from '@msafe/sui3-utils';\nimport { SuiClient } from '@mysten/sui/client';\nimport { Transaction } from '@mysten/sui/transactions';\nimport { WalletAccount } from '@mysten/wallet-standard';\n\nimport { BaseIntention } from '@/apps/interface/sui';\nimport { SuiNetworks } from '@/types';\n\nimport { getRemoveLiquidityTxb } from '../api/position';\nimport { CetusIntentionData, TransactionSubType } from '../types';\n\nexport class RemoveLiquidityIntention extends BaseIntention<CetusIntentionData> {\n txType = TransactionType.Other;\n\n txSubType = TransactionSubType.RemoveLiquidity;\n\n constructor(public readonly data: CetusIntentionData) {\n super(data);\n }\n\n async build(input: { suiClient: SuiClient; account: WalletAccount; network: SuiNetworks }): Promise<Transaction> {\n const { account, network } = input;\n const { txbParams } = this.data;\n const txb = await getRemoveLiquidityTxb(txbParams, account, network);\n return txb;\n }\n\n static fromData(data: CetusIntentionData) {\n return new RemoveLiquidityIntention(data);\n }\n}\n","import { TransactionType } from '@msafe/sui3-utils';\nimport { SuiClient } from '@mysten/sui/client';\nimport { Transaction } from '@mysten/sui/transactions';\nimport { WalletAccount } from '@mysten/wallet-standard';\n\nimport { BaseIntention } from '@/apps/interface/sui';\nimport { SuiNetworks } from '@/types';\n\nimport { getSwapRouterTxb } from '../api/swap';\nimport { CetusIntentionData, TransactionSubType } from '../types';\n\nexport class SwapIntention extends BaseIntention<CetusIntentionData> {\n txType = TransactionType.Other;\n\n txSubType = TransactionSubType.Swap;\n\n constructor(public readonly data: CetusIntentionData) {\n super(data);\n }\n\n async build(input: { suiClient: SuiClient; account: WalletAccount; network: SuiNetworks }): Promise<Transaction> {\n const { account, network } = input;\n const { txbParams } = this.data;\n const txb = await getSwapRouterTxb(txbParams, account, network);\n return txb;\n }\n\n static fromData(data: CetusIntentionData) {\n return new SwapIntention(data);\n }\n}\n","import { restituteMsafeFastRouterSwapParams } from '@cetusprotocol/aggregator-sdk';\nimport { Transaction } from '@mysten/sui/transactions';\nimport { WalletAccount } from '@mysten/wallet-standard';\n\nimport { SuiNetworks } from '@/types';\n\nimport { getAggregatorSdk } from './config';\n\nexport const getSwapRouterTxb = async (\n txbParams: any,\n account: WalletAccount,\n network: SuiNetworks,\n): Promise<Transaction> => {\n const aggregatorSdk = getAggregatorSdk(network, account);\n const txb = new Transaction();\n await aggregatorSdk.fastRouterSwap({\n ...txbParams,\n routers: restituteMsafeFastRouterSwapParams(txbParams.routers),\n txb,\n });\n return txb;\n};\n","import { TransactionType } from '@msafe/sui3-utils';\nimport { SuiClient } from '@mysten/sui/client';\nimport { Transaction } from '@mysten/sui/transactions';\nimport { WalletAccount } from '@mysten/wallet-standard';\n\nimport { BaseIntention } from '@/apps/interface/sui';\nimport { SuiNetworks } from '@/types';\n\nimport { getVestingRedeemTxb } from '../api/vesting';\nimport { CetusIntentionData, TransactionSubType } from '../types';\n\nexport class VestingRedeemIntention extends BaseIntention<CetusIntentionData> {\n txType = TransactionType.Other;\n\n txSubType = TransactionSubType.VestingRedeem;\n\n constructor(public readonly data: CetusIntentionData) {\n super(data);\n }\n\n async build(input: { suiClient: SuiClient; account: WalletAccount; network: SuiNetworks }): Promise<Transaction> {\n const { account, network } = input;\n const { txbParams } = this.data;\n const txb = await getVestingRedeemTxb(txbParams, account, network);\n return txb;\n }\n\n static fromData(data: CetusIntentionData) {\n return new VestingRedeemIntention(data);\n }\n}\n","import { Transaction } from '@mysten/sui/transactions';\nimport { WalletAccount } from '@mysten/wallet-standard';\n\nimport { SuiNetworks } from '@/types';\n\nconst VestingConfing = {\n package_id: '0x355714a1eeb7ab1d80902da6c92001170cda1212edf524c32aa308a3ac177c31',\n published_at: '0x355714a1eeb7ab1d80902da6c92001170cda1212edf524c32aa308a3ac177c31',\n cetus_coin_type: '0x06864a6f921804860930db6ddbe2e16acdf8504495ea7481637a1c8b9a8fe54b::cetus::CETUS',\n};\n\nexport const getVestingRedeemTxb = async (\n txbParams: any,\n account: WalletAccount,\n network: SuiNetworks,\n): Promise<Transaction> => {\n console.log('getVestingRedeemTxb txbParams: ', txbParams);\n console.log('getVestingRedeemTxb account: ', account);\n console.log('getVestingRedeemTxb network: ', network);\n const { pool, nftId, periods, CLOCK_ADDRESS } = txbParams;\n const txb = new Transaction();\n\n periods.forEach((period: any) => {\n txb.moveCall({\n target: `${VestingConfing.published_at}::router::redeem`,\n typeArguments: [VestingConfing.cetus_coin_type],\n arguments: [txb.object(pool), txb.object(nftId), txb.pure(period), txb.object(CLOCK_ADDRESS)],\n });\n });\n\n return txb;\n};\n","import { TransactionType } from '@msafe/sui3-utils';\nimport { SuiClient } from '@mysten/sui/client';\nimport { Transaction } from '@mysten/sui/transactions';\nimport { WalletAccount } from '@mysten/wallet-standard';\n\nimport { BaseIntention } from '@/apps/interface/sui';\nimport { SuiNetworks } from '@/types';\n\nimport { getXcetusCancelRedeemTxb } from '../api/xcetus';\nimport { CetusIntentionData, TransactionSubType } from '../types';\n\nexport class XcetusCancelIntention extends BaseIntention<CetusIntentionData> {\n txType = TransactionType.Other;\n\n txSubType = TransactionSubType.xCETUSCancelRedeem;\n\n constructor(public readonly data: CetusIntentionData) {\n super(data);\n }\n\n async build(input: { suiClient: SuiClient; account: WalletAccount; network: SuiNetworks }): Promise<Transaction> {\n const { account, network } = input;\n const { txbParams } = this.data;\n const txb = await getXcetusCancelRedeemTxb(txbParams, account, network);\n return txb;\n }\n\n static fromData(data: CetusIntentionData) {\n return new XcetusCancelIntention(data);\n }\n}\n","// eslint-disable-next-line import/no-extraneous-dependencies\nimport { Transaction } from '@mysten/sui/transactions';\nimport { WalletAccount } from '@mysten/wallet-standard';\n\nimport { SuiNetworks } from '@/types';\n\nimport { getPeripherySdk } from './config';\n\nexport const getXcetusConvertTxb = async (\n txbParams: any,\n account: WalletAccount,\n network: SuiNetworks,\n): Promise<Transaction> => {\n const peripherySdk = getPeripherySdk(network, account);\n const tx = new Transaction();\n const txb: Transaction = await peripherySdk.XCetusModule.convertPayload(txbParams, tx);\n return txb;\n};\n\nexport const getXcetusRedeemLockTxb = async (\n txbParams: any,\n account: WalletAccount,\n network: SuiNetworks,\n): Promise<Transaction> => {\n const peripherySdk = getPeripherySdk(network, account);\n const txb: Transaction = await peripherySdk.XCetusModule.redeemLockPayload(txbParams);\n return txb;\n};\n\nexport const getXcetusClaimingStakeRewardsTxb = async (\n txbParams: any,\n account: WalletAccount,\n network: SuiNetworks,\n): Promise<Transaction> => {\n const peripherySdk = getPeripherySdk(network, account);\n const txb: Transaction = await peripherySdk.XCetusModule.redeemDividendV3Payload(\n txbParams.phases,\n txbParams.venft_id,\n txbParams.bonus_types,\n txbParams.bonus_types_v2,\n txbParams.xTokenType,\n );\n return txb;\n};\n\nexport const getXcetusCancelRedeemTxb = async (\n txbParams: any,\n account: WalletAccount,\n network: SuiNetworks,\n): Promise<Transaction> => {\n const peripherySdk = getPeripherySdk(network, account);\n const txb: Transaction = await peripherySdk.XCetusModule.cancelRedeemPayload(txbParams);\n return txb;\n};\n\nexport const getXcetusRedeemTxb = async (\n txbParams: any,\n account: WalletAccount,\n network: SuiNetworks,\n): Promise<Transaction> => {\n const peripherySdk = getPeripherySdk(network, account);\n const txb: Transaction = await peripherySdk.XCetusModule.redeemPayload(txbParams);\n return txb;\n};\n","import { TransactionType } from '@msafe/sui3-utils';\nimport { SuiClient } from '@mysten/sui/client';\nimport { Transaction } from '@mysten/sui/transactions';\nimport { WalletAccount } from '@mysten/wallet-standard';\n\nimport { BaseIntention } from '@/apps/interface/sui';\nimport { SuiNetworks } from '@/types';\n\nimport { getXcetusClaimingStakeRewardsTxb } from '../api/xcetus';\nimport { CetusIntentionData, TransactionSubType } from '../types';\n\nexport class XcetusClaimingStakeRewardsIntention extends BaseIntention<CetusIntentionData> {\n txType = TransactionType.Other;\n\n txSubType = TransactionSubType.xCETUSClaimStakingRwewards;\n\n constructor(public readonly data: CetusIntentionData) {\n super(data);\n }\n\n async build(input: { suiClient: SuiClient; account: WalletAccount; network: SuiNetworks }): Promise<Transaction> {\n const { account, network } = input;\n const { txbParams } = this.data;\n const txb = await getXcetusClaimingStakeRewardsTxb(txbParams, account, network);\n return txb;\n }\n\n static fromData(data: CetusIntentionData) {\n return new XcetusClaimingStakeRewardsIntention(data);\n }\n}\n","import { TransactionType } from '@msafe/sui3-utils';\nimport { SuiClient } from '@mysten/sui/client';\nimport { Transaction } from '@mysten/sui/transactions';\nimport { WalletAccount } from '@mysten/wallet-standard';\n\nimport { BaseIntention } from '@/apps/interface/sui';\nimport { SuiNetworks } from '@/types';\n\nimport { getXcetusConvertTxb } from '../api/xcetus';\nimport { CetusIntentionData, TransactionSubType } from '../types';\n\nexport class XcetusConvertIntention extends BaseIntention<CetusIntentionData> {\n txType = TransactionType.Other;\n\n txSubType = TransactionSubType.xCETUSConvert;\n\n constructor(public readonly data: CetusIntentionData) {\n super(data);\n }\n\n async build(input: { suiClient: SuiClient; account: WalletAccount; network: SuiNetworks }): Promise<Transaction> {\n const { account, network } = input;\n const { txbParams } = this.data;\n const txb = await getXcetusConvertTxb(txbParams, account, network);\n return txb;\n }\n\n static fromData(data: CetusIntentionData) {\n return new XcetusConvertIntention(data);\n }\n}\n","import { TransactionType } from '@msafe/sui3-utils';\nimport { SuiClient } from '@mysten/sui/client';\nimport { Transaction } from '@mysten/sui/transactions';\nimport { WalletAccount } from '@mysten/wallet-standard';\n\nimport { BaseIntention } from '@/apps/interface/sui';\nimport { SuiNetworks } from '@/types';\n\nimport { getXcetusRedeemTxb } from '../api/xcetus';\nimport { CetusIntentionData, TransactionSubType } from '../types';\n\nexport class XcetusRedeemIntention extends BaseIntention<CetusIntentionData> {\n txType = TransactionType.Other;\n\n txSubType = TransactionSubType.xCETUSRedeem;\n\n constructor(public readonly data: CetusIntentionData) {\n super(data);\n }\n\n async build(input: { suiClient: SuiClient; account: WalletAccount; network: SuiNetworks }): Promise<Transaction> {\n const { account, network } = input;\n const { txbParams } = this.data;\n const txb = await getXcetusRedeemTxb(txbParams, account, network);\n return txb;\n }\n\n static fromData(data: CetusIntentionData) {\n return new XcetusRedeemIntention(data);\n }\n}\n","import { TransactionType } from '@msafe/sui3-utils';\nimport { SuiClient } from '@mysten/sui/client';\nimport { Transaction } from '@mysten/sui/transactions';\nimport { WalletAccount } from '@mysten/wallet-standard';\n\nimport { BaseIntention } from '@/apps/interface/sui';\nimport { SuiNetworks } from '@/types';\n\nimport { getXcetusRedeemLockTxb } from '../api/xcetus';\nimport { CetusIntentionData, TransactionSubType } from '../types';\n\nexport class XcetusRedeemLockIntention extends BaseIntention<CetusIntentionData> {\n txType = TransactionType.Other;\n\n txSubType = TransactionSubType.xCETUSRedeemLock;\n\n constructor(public readonly data: CetusIntentionData) {\n super(data);\n }\n\n async build(input: { suiClient: SuiClient; account: WalletAccount; network: SuiNetworks }): Promise<Transaction> {\n const { account, network } = input;\n const { txbParams } = this.data;\n const txb = await getXcetusRedeemLockTxb(txbParams, account, network);\n return txb;\n }\n\n static fromData(data: CetusIntentionData) {\n return new XcetusRedeemLockIntention(data);\n }\n}\n","import { CancelStreamIntentionData, TransactionType } from '@msafe/sui3-utils';\nimport { SuiClient } from '@mysten/sui.js/client';\nimport { TransactionBlock } from '@mysten/sui.js/transactions';\nimport { WalletAccount } from '@mysten/wallet-standard';\n\nimport { SuiNetworks } from '@/types';\n\nimport { StreamIntention } from './intention';\nimport { StreamTransactionType } from './types/decode';\n\nexport class CancelStreamIntention extends StreamIntention<CancelStreamIntentionData> {\n txType = TransactionType.Stream;\n\n txSubType = StreamTransactionType.CANCEL;\n\n constructor(public readonly data: CancelStreamIntentionData) {\n super(data);\n }\n\n async build(input: {\n network: SuiNetworks;\n suiClient: SuiClient;\n account: WalletAccount;\n }): Promise<TransactionBlock> {\n const { network, account } = input;\n const mpayClient = this.getClient(network, account);\n const stream = await mpayClient.getStream(this.data.streamId);\n return stream.cancel();\n }\n}\n","import { TransactionType } from '@msafe/sui3-utils';\nimport { SuiClient } from '@mysten/sui.js/client';\nimport { TransactionBlock } from '@mysten/sui.js/transactions';\nimport { SuiSignTransactionBlockInput, WalletAccount } from '@mysten/wallet-standard';\nimport sortKeys from 'sort-keys-recursive';\n\nimport { SuiNetworks } from '@/types';\n\nexport interface IAppHelperInternalLegacy<T> {\n application: string;\n supportSDK: '@mysten/sui.js';\n\n deserialize(\n input: SuiSignTransactionBlockInput & {\n network: SuiNetworks;\n suiClient: SuiClient;\n account: WalletAccount;\n },\n ): Promise<{\n txType: TransactionType;\n txSubType: string;\n intentionData: T;\n }>;\n\n build(input: {\n network: SuiNetworks;\n txType: TransactionType;\n txSubType: string;\n intentionData: T;\n suiClient: SuiClient;\n account: WalletAccount;\n }): Promise<TransactionBlock>;\n}\n\nexport interface TransactionIntentionLegacy<D> {\n txType: TransactionType;\n txSubType: string;\n data: D;\n\n serialize(): string;\n\n build(input: { suiClient: SuiClient; account: WalletAccount; network: SuiNetworks }): Promise<TransactionBlock>;\n}\n\nexport abstract class BaseIntentionLegacy<D> implements TransactionIntentionLegacy<D> {\n abstract txType: TransactionType;\n\n abstract txSubType: string;\n\n protected constructor(public readonly data: D) {}\n\n serialize() {\n return JSON.stringify(sortKeys(this.data));\n }\n\n abstract build(input: {\n suiClient: SuiClient;\n account: WalletAccount;\n network: SuiNetworks;\n }): Promise<TransactionBlock>;\n}\n","import { getFullnodeUrl } from '@mysten/sui.js/client';\n\nimport * as devContractConfig from '../config/dev.json';\nimport * as prodContractConfig from '../config/prod.json';\n\nexport enum Env {\n dev = 'dev',\n stg = 'stg',\n prev = 'prev',\n prod = 'prod',\n}\n\nexport interface EnvConfig {\n env: Env;\n rpc: SuiConfig;\n backend: BackendConfig;\n contract: ContractConfig;\n}\n\nexport interface EnvConfigOptions {\n rpc?: SuiConfig;\n backend?: BackendConfig;\n contract?: ContractConfig;\n}\n\nexport interface BackendConfig {\n url: string;\n}\n\nexport interface SuiConfig {\n url: string;\n}\n\nexport interface ContractConfig {\n contractId: string;\n roleObjId: string;\n vaultObjId: string;\n feeObjId: string;\n}\n\nexport const DEV_RPC_ENDPOINT = getFullnodeUrl('testnet');\nexport const STG_RPC_ENDPOINT = getFullnodeUrl('testnet');\nexport const PREV_RPC_ENDPOINT = getFullnodeUrl('mainnet');\nexport const PROD_RPC_ENDPOINT = getFullnodeUrl('mainnet');\n\nexport const DEV_BE_API = 'https://bc3p6l5unl.execute-api.us-west-1.amazonaws.com/prod';\nexport const STG_BE_API = 'https://rolsbkota7.execute-api.us-west-1.amazonaws.com/prod';\nexport const PREV_BE_API = 'https://6p6mkx33ne.execute-api.us-west-1.amazonaws.com/prod';\nexport const PROD_BE_API = 'https://xrae3mrjv5.execute-api.us-west-1.amazonaws.com/prod';\n\nexport const CONTRACT_DEV: ContractConfig = devContractConfig;\nexport const CONTRACT_PROD: ContractConfig = prodContractConfig;\n\nconst ENV_CONFIG: Map<Env, EnvConfig> = new Map([\n [\n Env.dev,\n {\n env: Env.dev,\n rpc: {\n url: DEV_RPC_ENDPOINT,\n },\n backend: {\n url: DEV_BE_API,\n },\n contract: CONTRACT_DEV,\n },\n ],\n [\n Env.stg,\n {\n env: Env.stg,\n rpc: {\n url: STG_RPC_ENDPOINT,\n },\n backend: {\n url: STG_BE_API,\n },\n contract: CONTRACT_DEV,\n },\n ],\n [\n Env.prev,\n {\n env: Env.prev,\n rpc: {\n url: PREV_RPC_ENDPOINT,\n },\n backend: {\n url: PREV_BE_API,\n },\n contract: CONTRACT_PROD,\n },\n ],\n [\n Env.prod,\n {\n env: Env.prod,\n rpc: {\n url: PROD_RPC_ENDPOINT,\n },\n backend: {\n url: PROD_BE_API,\n },\n contract: CONTRACT_PROD,\n },\n ],\n]);\n\nexport function getConfig(env: Env, options?: EnvConfigOptions): EnvConfig {\n const ec = ENV_CONFIG.get(env);\n if (!ec) {\n throw new Error(`Env not supported: ${env}`);\n }\n if (options && options.rpc) {\n ec.rpc = options.rpc;\n }\n if (options && options.backend) {\n ec.backend = options.backend;\n }\n if (options && options.contract) {\n ec.contract = options.contract;\n }\n return ec;\n}\n","{\n \"transaction\": \"DiBZq4UmVVYiRL6ZJmFKYoHcxtxqrhsCXSkFyT7wUr3j\",\n \"status\": \"success\",\n \"contractId\": \"0x81c960dc653975fbd0072deca8afb92d322898c911622898ba1b2e3ad0c4bd8d\",\n \"roleObjId\": \"0xc6ec0bdee0bb59a72077e9acd2f42457043cf47080b3d3fad4d39abf28bba63a\",\n \"vaultObjId\": \"0xbc4021387fbac149119fd24e92be9e58f745774292f3a2a12e2ac6daf5363e1d\",\n \"feeObjId\": \"0x4178f63970fe2daeb256dc5730ad172e82b3e8eb45f31b33e0daae72cd35e1e1\",\n \"upgradeCapObjId\": \"0xe1e9aa7d222d151bfe6dd83358b0d7fdcb11260f710800cfaf7ccc1b1e245115\"\n}","{\n \"transaction\": \"855FNDV8o8Z3fWULPnQo9qdhLJpsg7wZrkCpNyfw9KfB\",\n \"status\": \"success\",\n \"contractId\": \"0xc357c3985e8fb875d6b37141497af660779aa1bab0ec489b2213efd74067d1fa\",\n \"roleObjId\": \"0x5ab49bdf9fd1413e328ef242b3f8d83dde791b38a0b627bfc87fb25c010d34f1\",\n \"vaultObjId\": \"0xb483558770d8eb26007f193b75db40f0a45f2e36863a687625885d4de6993378\",\n \"feeObjId\": \"0x48453fc4d7cde3fe35aad89e5dfb496608a6a55ea529a1c0274681a808627f94\",\n \"upgradeCapObjId\": \"0x34279779a0d0d36bd5044b04830d607fa1b0ecf316548c8ac3a44151e4f1a42a\"\n}","import { SuiClient } from '@mysten/sui.js/client';\n\nimport { EnvConfig, Env, EnvConfigOptions, getConfig } from './env';\nimport { NoBackendError } from '../error/NoBackendError';\nimport { WalletNotConnectedError } from '../error/WalletNotConnectedError';\nimport { Backend } from '../stream/backend';\nimport { IBackend } from '../types/backend';\nimport { IWallet, WalletType } from '../types/wallet';\n\nexport class Globals {\n public signer: IWallet | undefined;\n\n public readonly suiClient: SuiClient;\n\n public readonly envConfig: EnvConfig;\n\n public _backend?: IBackend;\n\n constructor(envConfig: EnvConfig) {\n this.envConfig = envConfig;\n this.suiClient = new SuiClient({ url: envConfig.rpc.url });\n if (envConfig.backend) {\n this._backend = new Backend(envConfig.backend.url);\n }\n }\n\n static new(env: Env, options?: EnvConfigOptions) {\n const ec = getConfig(env, options);\n return new Globals(ec);\n }\n\n get walletType(): WalletType | 'disconnected' {\n if (!this.wallet) {\n return 'disconnected';\n }\n return this.wallet.type;\n }\n\n get backend(): IBackend {\n if (!this._backend) {\n throw new NoBackendError();\n }\n return this._backend;\n }\n\n // Used for test cases\n set backend(b: IBackend) {\n this._backend = b;\n }\n\n connectWallet(wallet: IWallet) {\n this.signer = wallet;\n }\n\n disconnect() {\n this.signer = undefined;\n }\n\n get wallet(): IWallet {\n if (!this.signer) {\n throw new WalletNotConnectedError();\n }\n return this.signer;\n }\n\n async walletAddress() {\n return this.wallet.address();\n }\n}\n","export enum MPayErrorCode {\n sanity,\n walletNotConnected,\n InvalidInput,\n InvalidRpcResult,\n NotEnoughBalance,\n StreamNotFound,\n RpcError,\n NotCreator,\n NotRecipient,\n InvalidStreamGroup,\n BackendError,\n NoBackend,\n TransactionFailed,\n}\n\nexport type JsonObject =\n | string\n | number\n | bigint\n | boolean\n | null\n | undefined\n | readonly JsonObject[]\n | { readonly [key: string]: JsonObject }\n | { toJSON(): JsonObject };\n\nexport class MPayError extends Error {\n public readonly mpayErrorCode: number;\n\n public readonly context?: JsonObject;\n\n constructor(mpayErrorCode: number, msg: string, options: { cause?: unknown; context?: JsonObject } = {}) {\n const { cause, context } = options;\n if (cause) {\n super(`[MPay] ${msg}: ${cause}`);\n } else {\n super(`[MPay] ${msg}`);\n }\n this.mpayErrorCode = mpayErrorCode;\n this.context = context;\n }\n}\n","import { MPayError, MPayErrorCode } from './base';\n\nexport class NoBackendError extends MPayError {\n constructor() {\n super(MPayErrorCode.NoBackend, 'Backend is not specified');\n }\n}\n","import { MPayError, MPayErrorCode } from './base';\n\nexport class WalletNotConnectedError extends MPayError {\n constructor() {\n super(MPayErrorCode.walletNotConnected, 'Wallet not connected');\n }\n}\n","import axios, { AxiosError, AxiosResponse } from 'axios';\n\nimport { BackendError } from '../error/BackendError';\nimport {\n IBackend,\n BackendIncomingStreamFilterOptions,\n StreamRef,\n BackendOutgoingStreamFilterOptions,\n StreamFilterStatus,\n} from '../types/backend';\nimport { StreamEvent } from '../types/events';\nimport { PaginationOptions, Paginated } from '../types/pagination';\n\nexport class Backend implements IBackend {\n constructor(private apiURL: string) {}\n\n private static parseResponseData(response: AxiosError | AxiosResponse) {\n if (response instanceof AxiosError) {\n throw new BackendError(response.response?.statusText as string);\n }\n if (response.status === 200) {\n if (response.data.success) {\n return response.data.data;\n }\n throw new BackendError(response.data.code);\n }\n throw new BackendError(response.status.toString());\n }\n\n async getIncomingStreams(recipient: string, options?: BackendIncomingStreamFilterOptions): Promise<StreamRef[]> {\n const res = await axios.post(`${this.apiURL}/stream`, {\n recipient,\n ...options,\n });\n return Backend.parseResponseData(res) as StreamRef[];\n }\n\n async getOutgoingStreams(sender: string, options?: BackendOutgoingStreamFilterOptions): Promise<StreamRef[]> {\n const res = await axios.post(`${this.apiURL}/stream`, {\n sender,\n ...options,\n });\n return Backend.parseResponseData(res);\n }\n\n async getStreamHistory(query: {\n streamId?: string;\n groupId?: string;\n pagination?: PaginationOptions;\n }): Promise<Paginated<StreamEvent>> {\n const res = await axios.post(`${this.apiURL}/stream-events`, query);\n const paginatedData = Backend.parseResponseData(res);\n paginatedData.data.forEach((event: StreamEvent) => {\n const formalizedEvent = event;\n if (formalizedEvent.data.type === 'create_stream') {\n formalizedEvent.data.balance = BigInt(formalizedEvent.data.balance);\n } else if (formalizedEvent.data.type === 'cancel_stream') {\n formalizedEvent.data.withdrawAmount = BigInt(formalizedEvent.data.withdrawAmount);\n } else if (formalizedEvent.data.type === 'claim' || formalizedEvent.data.type === 'auto_claim') {\n formalizedEvent.data.claimAmount = BigInt(formalizedEvent.data.claimAmount);\n } else if (formalizedEvent.data.type === 'set_auto_claim') {\n formalizedEvent.data.enabled = !!formalizedEvent.data.enabled;\n }\n formalizedEvent.createdAt = new Date(formalizedEvent.createdAt);\n return formalizedEvent;\n });\n\n return paginatedData;\n }\n\n async getAllCoinTypes(address: string): Promise<string[]> {\n const res = await axios.post(`${this.apiURL}/stream-info`, { address });\n return Backend.parseResponseData(res);\n }\n\n async getAllRecipients(sender: string, options?: StreamFilterStatus): Promise<string[]> {\n const res = await axios.post(`${this.apiURL}/stream-info`, { sender, status: options });\n return Backend.parseResponseData(res);\n }\n\n async getAllSenders(recipient: string, options?: StreamFilterStatus): Promise<string[]> {\n const res = await axios.post(`${this.apiURL}/stream-info`, { recipient, status: options });\n return Backend.parseResponseData(res);\n }\n}\n","import { JsonObject, MPayError, MPayErrorCode } from './base';\n\nexport class BackendError extends MPayError {\n constructor(msg: string, context?: JsonObject) {\n super(MPayErrorCode.BackendError, msg, { context });\n }\n}\n","import { SuiClient } from '@mysten/sui.js/client';\nimport { TransactionBlock } from '@mysten/sui.js/transactions';\nimport { SUI_TYPE_ARG, normalizeStructTag, normalizeSuiAddress } from '@mysten/sui.js/utils';\nimport { WalletAccount } from '@mysten/wallet-standard';\n\nimport { MPayBuilder } from '../builder/MPayBuilder';\nimport { Env, EnvConfigOptions, Globals } from '../common';\nimport { InvalidInputError } from '../error/InvalidInputError';\nimport { SanityError } from '../error/SanityError';\nimport { getCoinsWithAmount } from '../sui/iterator/coin';\nimport { isSameCoinType } from '../sui/utils';\nimport { StreamFilterStatus } from '../types/backend';\nimport {\n CreateStreamInfo,\n IMPayClient,\n IPagedStreamListIterator,\n IncomingStreamQuery,\n OutgoingStreamQuery,\n} from '../types/client';\nimport {\n CoinRequest,\n CoinRequestResponse,\n GAS_OBJECT_SPEC,\n IMSafeAccount,\n ISingleWallet,\n IWallet,\n WalletType,\n} from '../types/wallet';\nimport { Stream } from './Stream';\nimport { MPayHelper } from './helper';\nimport { PagedStreamListIterator } from './query';\n\nexport class MSafeAccountAdapter implements IWallet {\n constructor(private readonly msafe: IMSafeAccount) {}\n\n get type() {\n return WalletType.msafe;\n }\n\n async address() {\n return this.msafe.address();\n }\n\n async requestCoins(reqs: CoinRequest[]): Promise<CoinRequestResponse[]> {\n return this.msafe.requestCoins(reqs);\n }\n}\n\nexport class MSafeSingleWallet {\n constructor(private account: WalletAccount) {}\n\n async address(): Promise<string> {\n return this.account.address;\n }\n}\n\nexport class SingleWalletAdapter implements IWallet {\n constructor(\n private readonly singleWallet: ISingleWallet,\n private readonly suiClient: SuiClient,\n ) {}\n\n get type() {\n return WalletType.single;\n }\n\n async address() {\n return this.singleWallet.address();\n }\n\n async requestCoins(reqs: CoinRequest[]): Promise<CoinRequestResponse[]> {\n return Promise.all(reqs.map((req) => this.requestCoin(req)));\n }\n\n async requestCoin(req: CoinRequest): Promise<CoinRequestResponse> {\n if (isSameCoinType(req.coinType, SUI_TYPE_ARG)) {\n return {\n primaryCoin: GAS_OBJECT_SPEC,\n };\n }\n if (req.amount <= 0) {\n throw new InvalidInputError('Invalid coin request', 'coinAmount', req.amount);\n }\n const coins = await getCoinsWithAmount(this.suiClient, await this.address(), req.amount, req.coinType);\n if (coins.length === 0) {\n throw new SanityError('no coins available');\n }\n return {\n primaryCoin: coins[0].coinObjectId,\n mergedCoins: coins.slice(1).map((coin) => coin.coinObjectId),\n };\n }\n}\n\nexport class MPayClient implements IMPayClient {\n public readonly globals: Globals;\n\n public readonly helper: MPayHelper;\n\n constructor(env: Env, options?: EnvConfigOptions) {\n this.globals = Globals.new(env, options);\n this.helper = new MPayHelper(this.globals);\n }\n\n connectSingleWallet(wallet: ISingleWallet) {\n const adapter = new SingleWalletAdapter(wallet, this.globals.suiClient);\n this.globals.connectWallet(adapter);\n }\n\n connectMSafeAccount(msafe: IMSafeAccount) {\n const adapter = new MSafeAccountAdapter(msafe);\n this.globals.connectWallet(adapter);\n }\n\n async createStream(info: CreateStreamInfo): Promise<TransactionBlock> {\n return this.builder().createStreams(info);\n }\n\n async getStream(streamId: string) {\n return Stream.new(this.globals, streamId);\n }\n\n async getIncomingStreams(query?: IncomingStreamQuery, pageSize = 10): Promise<IPagedStreamListIterator> {\n return PagedStreamListIterator.newIncoming({\n globals: this.globals,\n query,\n pageSize,\n });\n }\n\n async getOutgoingStreams(query?: OutgoingStreamQuery, pageSize = 10): Promise<IPagedStreamListIterator> {\n return PagedStreamListIterator.newOutgoing({\n globals: this.globals,\n query,\n pageSize,\n });\n }\n\n async getCoinTypesForStreamFilter(): Promise<string[]> {\n const address = await this.wallet.address();\n const coinTypes = await this.globals.backend.getAllCoinTypes(address);\n return coinTypes.map((coinType) => normalizeStructTag(coinType));\n }\n\n async getRecipientsForStreamFilter(options?: StreamFilterStatus): Promise<string[]> {\n const address = await this.wallet.address();\n const recipients = await this.globals.backend.getAllRecipients(address, options);\n return recipients.map((recipient) => normalizeSuiAddress(recipient));\n }\n\n async getCreatorsForStreamFilter(options?: StreamFilterStatus): Promise<string[]> {\n const address = await this.wallet.address();\n const creators = await this.globals.backend.getAllSenders(address, options);\n return creators.map((creator) => normalizeSuiAddress(creator));\n }\n\n get wallet() {\n return this.globals.wallet;\n }\n\n private builder() {\n return new MPayBuilder(this.globals);\n }\n}\n","import { TransactionBlock } from '@mysten/sui.js/transactions';\n\nimport { CreateStreamHelper } from './CreateStreamHelper';\nimport { Globals } from '../common';\nimport { FeeContract } from '../contract/FeeContract';\nimport { StreamContract } from '../contract/StreamContract';\nimport { CreateStreamInfo } from '../types/client';\n\n// TODO: add vault and admin control related code.\nexport class MPayBuilder {\n private readonly feeContract: FeeContract;\n\n private readonly streamContract: StreamContract;\n\n constructor(public readonly globals: Globals) {\n const config = globals.envConfig.contract;\n this.feeContract = new FeeContract(config, globals);\n this.streamContract = new StreamContract(config, globals);\n }\n\n async createStreams(info: CreateStreamInfo) {\n const infoInternal = CreateStreamHelper.convertCreateStreamInfoToInternal(info);\n return this.createStreamHelper().buildCreateStreamTransactionBlock(infoInternal);\n }\n\n createStreamHelper() {\n return new CreateStreamHelper(this.globals, this.feeContract, this.streamContract);\n }\n\n setAutoClaim(streamId: string, enabled: boolean, coinType: string) {\n const txb = new TransactionBlock();\n return this.streamContract.setAutoClaim(txb, {\n streamId,\n enabled,\n coinType,\n });\n }\n\n claimStream(streamId: string, coinType: string) {\n const txb = new TransactionBlock();\n return this.streamContract.claimStream(txb, {\n streamId,\n coinType,\n });\n }\n\n claimStreamByProxy(streamId: string, coinType: string) {\n const txb = new TransactionBlock();\n return this.streamContract.claimStreamByProxy(txb, {\n streamId,\n coinType,\n });\n }\n\n cancelStream(streamId: string, coinType: string) {\n const txb = new TransactionBlock();\n this.streamContract.cancelStream(txb, {\n streamId,\n coinType,\n });\n return txb;\n }\n}\n","import { TransactionArgument, TransactionBlock, TransactionObjectArgument } from '@mysten/sui.js/transactions';\nimport { SUI_TYPE_ARG, normalizeStructTag } from '@mysten/sui.js/utils';\n\nimport { CLAIM_FEE_NUMERATOR, FEE_DENOMINATOR, FEE_NUMERATOR, FLAT_FEE_SUI } from './const';\nimport { Globals } from '../common';\nimport { ResultRef } from '../common/transaction';\nimport { FeeContract } from '../contract/FeeContract';\nimport { InspectViewer } from '../contract/InspectViewer';\nimport { StreamContract } from '../contract/StreamContract';\nimport { encodeMetadata } from '../stream/metadata';\nimport { isSameCoinType } from '../sui/utils';\nimport {\n CreateStreamInfo,\n CreateStreamInfoInternal,\n MPayFees,\n PaymentWithFee,\n RecipientInfoInternal,\n} from '../types/client';\nimport { CoinRequest, CoinRequestResponse, GAS_OBJECT_SPEC } from '../types/wallet';\nimport { generateGroupId } from '../utils/random';\n\nexport class CreateStreamHelper {\n constructor(\n public readonly globals: Globals,\n private readonly feeContract: FeeContract,\n private readonly streamContract: StreamContract,\n ) {}\n\n static convertCreateStreamInfoToInternal(info: CreateStreamInfo): CreateStreamInfoInternal {\n return {\n metadata: encodeMetadata({\n name: info.name,\n groupId: generateGroupId(),\n }),\n coinType: normalizeStructTag(info.coinType),\n recipients: info.recipients.map((recipient) => ({\n address: recipient.address,\n cliffAmount: recipient.cliffAmount,\n amountPerEpoch: recipient.amountPerStep,\n })),\n epochInterval: info.interval,\n numberEpoch: info.steps,\n startTime: info.startTimeMs,\n cancelable: info.cancelable,\n };\n }\n\n async buildCreateStreamTransactionBlock(info: CreateStreamInfoInternal): Promise<TransactionBlock> {\n const txb = new TransactionBlock();\n const paymentWithFee = this.calculateFeesInternal(info);\n const coinReqs = this.getCreateStreamCoinRequests(info, paymentWithFee);\n const coinResp = await this.wallet.requestCoins(coinReqs);\n\n const paymentMergedObject = await this.addMergeCoins(txb, coinResp[0]);\n let flatFeeMergedObject: TransactionArgument;\n if (coinReqs.length > 1) {\n flatFeeMergedObject = await this.addMergeCoins(txb, coinResp[1]);\n } else {\n flatFeeMergedObject = paymentMergedObject;\n }\n\n // Create streams\n for (let i = 0; i < info.recipients.length; i++) {\n const recipient = info.recipients[i];\n const paymentAmount = this.amountForRecipient(recipient, info.numberEpoch);\n const feeAmount = this.getStreamFeeLocal(paymentAmount);\n const [paymentCoin] = txb.splitCoins(paymentMergedObject, [txb.pure(paymentAmount + feeAmount, 'u64')]);\n const [flatFeeCoin] = txb.splitCoins(flatFeeMergedObject, [txb.pure(this.flatSuiFee, 'u64')]);\n this.streamContract.createStream(txb, {\n paymentCoin: new ResultRef(paymentCoin as TransactionArgument & TransactionArgument[]),\n flatFeeCoin: new ResultRef(flatFeeCoin as TransactionArgument & TransactionArgument[]),\n metadata: info.metadata,\n recipient: recipient.address,\n timeStart: info.startTime,\n cliff: recipient.cliffAmount,\n epochInterval: info.epochInterval,\n numEpoch: info.numberEpoch,\n amountPerEpoch: recipient.amountPerEpoch,\n cancelable: info.cancelable,\n coinType: info.coinType,\n });\n }\n return txb;\n }\n\n calculateCreateStreamFees(createInfo: CreateStreamInfo) {\n const infoInternal = CreateStreamHelper.convertCreateStreamInfoToInternal(createInfo);\n return this.calculateFeesInternal(infoInternal);\n }\n\n feeParams(): MPayFees {\n return {\n createFeePercent: {\n numerator: FEE_NUMERATOR,\n denominator: FEE_DENOMINATOR,\n },\n claimFeePercent: {\n numerator: CLAIM_FEE_NUMERATOR,\n denominator: FEE_DENOMINATOR,\n },\n flatFeePerStream: FLAT_FEE_SUI,\n };\n }\n\n private async addMergeCoins(txb: TransactionBlock, coins: CoinRequestResponse): Promise<TransactionObjectArgument> {\n let mergedCoin: TransactionObjectArgument;\n if (coins.mergedCoins && coins.mergedCoins.length) {\n txb.mergeCoins(\n txb.object(coins.primaryCoin),\n coins.mergedCoins.map((coinId) => txb.object(coinId)),\n );\n mergedCoin = txb.object(coins.primaryCoin);\n } else if (coins.primaryCoin === GAS_OBJECT_SPEC) {\n mergedCoin = txb.gas;\n } else {\n mergedCoin = txb.object(coins.primaryCoin);\n }\n return mergedCoin;\n }\n\n getCreateStreamCoinRequests(info: CreateStreamInfoInternal, payment: PaymentWithFee): CoinRequest[] {\n const streamCoinType = info.coinType;\n\n if (isSameCoinType(streamCoinType, SUI_TYPE_ARG)) {\n return [\n {\n coinType: streamCoinType,\n amount: payment.totalAmount + payment.streamFeeAmount + payment.flatFeeAmount,\n },\n ];\n }\n return [\n {\n coinType: streamCoinType,\n amount: payment.totalAmount + payment.streamFeeAmount,\n },\n {\n coinType: SUI_TYPE_ARG,\n amount: payment.flatFeeAmount,\n },\n ];\n }\n\n calculateFeesInternal(info: CreateStreamInfoInternal): PaymentWithFee {\n const streamPayment = info.recipients.reduce(\n (sum, recipient) => {\n const totalAmount = this.amountForRecipient(recipient, info.numberEpoch);\n const fee = this.getStreamFeeLocal(totalAmount);\n return {\n totalAmount: sum.totalAmount + totalAmount,\n streamFeeAmount: sum.streamFeeAmount + fee,\n };\n },\n {\n totalAmount: 0n,\n streamFeeAmount: 0n,\n },\n );\n const flatFeeAmount = BigInt(info.recipients.length) * this.flatSuiFee;\n return {\n flatFeeAmount,\n ...streamPayment,\n };\n }\n\n private amountForRecipient(recipient: RecipientInfoInternal, numEpoch: bigint) {\n return BigInt(recipient.amountPerEpoch) * BigInt(numEpoch) + BigInt(recipient.cliffAmount);\n }\n\n get flatSuiFee() {\n return FLAT_FEE_SUI;\n }\n\n getStreamFeeLocal(streamAmount: bigint) {\n return (streamAmount * FEE_NUMERATOR) / FEE_DENOMINATOR;\n }\n\n async getStreamFeeRemote(streamAmount: bigint) {\n const txb = this.feeContract.streamingFee(new TransactionBlock(), streamAmount);\n const res = await this.globals.suiClient.devInspectTransactionBlock({\n sender: await this.globals.walletAddress(),\n transactionBlock: txb,\n });\n const iv = new InspectViewer(res);\n return iv.getU64();\n }\n\n get wallet() {\n return this.globals.wallet;\n }\n}\n","export const FEE_NUMERATOR = 50n;\nexport const FEE_DENOMINATOR = 10000n;\nexport const CLAIM_FEE_NUMERATOR = 25n;\nexport const FLAT_FEE_SUI = 100000000n;\n","import { TransactionArgument, TransactionBlock } from '@mysten/sui.js/transactions';\n\nexport type MoveNumber = bigint | string | number;\nexport type Ref<T> = T | ResultRef;\nexport type ObjectId = string;\n\nexport class MoveObject {\n constructor(public readonly object: string) {}\n\n moveArg(txb: TransactionBlock) {\n return txb.object(this.object);\n }\n}\n\nexport class ObjectVector {\n constructor(public readonly objects: string[]) {}\n\n moveArgs(txb: TransactionBlock) {\n return txb.makeMoveVec({ objects: this.objects.map((o) => txb.object(o)) });\n }\n}\n\nexport class ResultRef {\n constructor(public readonly result: TransactionArgument & TransactionArgument[]) {\n // eslint-disable-next-line no-constructor-return\n return new Proxy(this, {\n set() {\n throw new Error('The transaction result is a proxy, and does not support setting properties directly');\n },\n get(target, property) {\n // This allows this transaction argument to be used in the singular form:\n if (property in target) {\n return Reflect.get(target, property);\n }\n\n const nestedResultFor = (resultIndex: number) => new ResultRef(target.result[resultIndex] as any);\n\n // Support destructuring:\n if (property === Symbol.iterator) {\n return function* () {\n let i = 0;\n while (true) {\n yield nestedResultFor(i);\n i++;\n }\n };\n }\n\n if (typeof property === 'symbol') {\n // eslint-disable-next-line consistent-return\n return;\n }\n\n const resultIndex = parseInt(property, 10);\n if (Number.isNaN(resultIndex) || resultIndex < 0) {\n // eslint-disable-next-line consistent-return\n return;\n }\n return nestedResultFor(resultIndex);\n },\n });\n }\n\n moveArg() {\n return this.result;\n }\n}\n","import { Buffer } from 'buffer';\n\nimport { DevInspectResults, SuiExecutionResult } from '@mysten/sui.js/client';\nimport { normalizeSuiAddress } from '@mysten/sui.js/utils';\n\nimport { InvalidRpcResultError } from '../error/InvalidRpcResultError';\n\nexport class InspectViewer {\n constructor(readonly results: DevInspectResults) {}\n\n callResult(index: number) {\n return this.results.results![index];\n }\n\n returnValue(returned: SuiExecutionResult, index: number) {\n return returned.returnValues![index];\n }\n\n getValue(callIndex = 0, returnIndex = 0) {\n const callResult = this.callResult(callIndex);\n return this.returnValue(callResult, returnIndex);\n }\n\n getAddress(callIndex = 0, returnIndex = 0) {\n const [value, type] = this.getValue(callIndex, returnIndex);\n if (type !== 'address') {\n throw new InvalidRpcResultError('Invalid contract return type.', {\n ctx: {\n expectType: 'address',\n gotType: type,\n },\n });\n }\n return normalizeSuiAddress(Buffer.from(value).toString('hex'));\n }\n\n getU64(callIndex = 0, returnIndex = 0) {\n const [value, type] = this.getValue(callIndex, returnIndex);\n if (type !== 'u64') {\n throw new InvalidRpcResultError('Invalid contract return type.', {\n ctx: {\n expectType: 'u64',\n gotType: type,\n },\n });\n }\n return Buffer.from(value).readBigInt64LE();\n }\n}\n","import { MPayError, JsonObject, MPayErrorCode } from './base';\n\nexport class InvalidRpcResultError extends MPayError {\n constructor(msg: string, ctx?: JsonObject) {\n super(MPayErrorCode.InvalidRpcResult, msg, { context: ctx });\n }\n}\n","import { bcs } from '@mysten/sui.js/bcs';\n\nimport { InvalidInputError } from '../error/InvalidInputError';\nimport { StreamMetadata } from '../types/stream';\n\nexport const metadataBcsType = {\n groupId: 'string',\n name: 'string',\n};\n\nconst MAX_NAME_SIZE = 64;\n\nexport function encodeMetadata(metadata: StreamMetadata) {\n validateMetadata(metadata);\n return bcs.ser(metadataBcsType, metadata).toString('base64');\n}\n\nexport function decodeMetadata(metaStr: string) {\n const metadata = bcs.de(metadataBcsType, metaStr, 'base64') as StreamMetadata;\n validateMetadata(metadata);\n return metadata;\n}\n\nexport function validateMetadata(metadata: StreamMetadata) {\n if (!isAsciiString(metadata.name)) {\n throw new InvalidInputError('Invalid metadata: Name contains unknown character');\n }\n if (!isAsciiString(metadata.groupId)) {\n throw new InvalidInputError('Invalid metadata: Group ID contains unknown character');\n }\n if (metadata.name.length > MAX_NAME_SIZE) {\n throw new InvalidInputError('Invalid metadata: Name exceed max length 64');\n }\n}\n\nfunction isAsciiString(str: string) {\n // eslint-disable-next-line no-control-regex\n const asciiPattern = /^[\\x00-\\x7F]+$/;\n return asciiPattern.test(str);\n}\n","import { MPayError, MPayErrorCode } from './base';\n\nexport class InvalidInputError extends MPayError {\n constructor(msg: string, fieldKey?: string, fieldValue?: any) {\n super(MPayErrorCode.InvalidInput, `Invalid input: ${msg}`, {\n context: {\n fieldKey,\n fieldValue,\n },\n });\n }\n}\n","import { normalizeStructTag } from '@mysten/sui.js/utils';\n\nexport function isSameCoinType(type1: string, type2: string) {\n return normalizeStructTag(type1) === normalizeStructTag(type2);\n}\n\nexport function isSameTarget(target1: string, target2: string): boolean {\n return normalizeStructTag(target1) === normalizeStructTag(target2);\n}\n","export enum WalletType {\n single = 'single',\n msafe = 'msafe',\n}\n\nexport const GAS_OBJECT_SPEC = 'txn.gas';\n\n/**\n * IWallet is the adapted interface of wallet. Supports both single wallet and msafe.\n */\nexport interface IWallet {\n type: WalletType;\n\n address(): Promise<string>;\n\n requestCoins(reqs: CoinRequest[]): Promise<CoinRequestResponse[]>;\n}\n\n/**\n * ISingleWallet is the raw interface of msafe account.\n * Need to adapt to IWallet interface\n */\nexport interface IMSafeAccount {\n address(): Promise<string>;\n\n // return coin objects by amount.\n requestCoins(reqs: CoinRequest[]): Promise<CoinRequestResponse[]>;\n}\n\n/**\n * ISingleWallet is the raw interface of single signer wallet.\n * Need to adapt to IWallet interface\n */\nexport interface ISingleWallet {\n address(): Promise<string>;\n}\n\nexport interface CoinRequest {\n coinType: string;\n amount: bigint;\n}\n\nexport interface CoinRequestResponse {\n primaryCoin: string;\n mergedCoins?: string[];\n}\n","import { nanoid } from 'nanoid';\n\nexport function generateGroupId() {\n return nanoid();\n}\n","import { TransactionBlock, Transactions } from '@mysten/sui.js/transactions';\n\nimport { ContractConfig, Globals } from '../common';\nimport { ObjectVector, MoveObject, ResultRef, Ref, ObjectId } from '../common/transaction';\nimport { CLOCK_ID } from '../const';\n\nexport class BaseContract {\n constructor(\n public readonly moduleName: string,\n public readonly config: ContractConfig,\n public readonly globals: Globals,\n ) {}\n\n addContractCall(txb: TransactionBlock, input: { method: string; arguments: any[]; typeArgs?: string[] }) {\n const target =\n `${this.config.contractId}::${this.moduleName}::${input.method}` as `${string}::${string}::${string}`;\n txb.add(\n Transactions.MoveCall({\n target,\n arguments: input.arguments.map((arg) => {\n if (arg instanceof ObjectVector) {\n return arg.moveArgs(txb);\n }\n if (arg instanceof MoveObject) {\n return arg.moveArg(txb);\n }\n if (arg instanceof ResultRef) {\n return arg.moveArg();\n }\n return txb.pure(arg);\n }),\n typeArguments: input.typeArgs,\n }),\n );\n return txb;\n }\n\n private addTransactionBlock(txb: TransactionBlock, target: string, callArgs: any[] = [], typeArgs: string[] = []) {\n txb.add(\n Transactions.MoveCall({\n target: target as `${string}::${string}::${string}`,\n arguments: callArgs.map((arg) => {\n if (arg instanceof ObjectVector) {\n return arg.moveArgs(txb);\n }\n if (arg instanceof MoveObject) {\n return arg.moveArg(txb);\n }\n if (arg instanceof ResultRef) {\n return arg.moveArg();\n }\n return txb.pure(arg);\n }),\n typeArguments: typeArgs,\n }),\n );\n }\n\n makeObject(object: Ref<ObjectId>) {\n return typeof object === 'string' ? new MoveObject(object) : object;\n }\n\n vaultObject() {\n return new MoveObject(this.config.vaultObjId);\n }\n\n roleObject() {\n return new MoveObject(this.config.roleObjId);\n }\n\n feeObject() {\n return new MoveObject(this.config.feeObjId);\n }\n\n clockObject() {\n return new MoveObject(CLOCK_ID);\n }\n}\n","export const CLOCK_ID = '0x0000000000000000000000000000000000000000000000000000000000000006';\n","import { TransactionBlock } from '@mysten/sui.js/transactions';\n\nimport { BaseContract } from './BaseContract';\nimport { ContractConfig, Globals } from '../common';\nimport { MoveNumber } from '../common/transaction';\n\nexport class FeeContract extends BaseContract {\n static ModuleName = 'fee_module';\n\n static MethodName = {\n set_streaming_fee: 'set_streaming_fee',\n set_claim_fee: 'set_claim_fee',\n set_streaming_flat_fee: 'set_streaming_flat_fee',\n streaming_flat_fee: 'streaming_flat_fee',\n streaming_fee: 'streaming_fee',\n claim_fee: 'claim_fee',\n fee_denominator: 'fee_denominator',\n } as const;\n\n constructor(\n public readonly config: ContractConfig,\n public readonly globals: Globals,\n ) {\n super(FeeContract.ModuleName, config, globals);\n }\n\n setStreamingFee(txb: TransactionBlock, createFeeNumerator: MoveNumber) {\n const roleObject = this.roleObject();\n const feeObject = this.feeObject();\n return this.addContractCall(txb, {\n method: FeeContract.MethodName.set_streaming_fee,\n arguments: [roleObject, feeObject, createFeeNumerator],\n typeArgs: [],\n });\n }\n\n setStreamingFlatFee(txb: TransactionBlock, flatFee: MoveNumber) {\n const roleObject = this.roleObject();\n const feeObject = this.feeObject();\n return this.addContractCall(txb, {\n method: FeeContract.MethodName.set_streaming_flat_fee,\n arguments: [roleObject, feeObject, flatFee],\n typeArgs: [],\n });\n }\n\n setClaimFee(txb: TransactionBlock, claimFee: MoveNumber) {\n const roleObject = this.roleObject();\n const feeObject = this.feeObject();\n return this.addContractCall(txb, {\n method: FeeContract.MethodName.set_claim_fee,\n arguments: [roleObject, feeObject, claimFee],\n typeArgs: [],\n });\n }\n\n streamingFee(txb: TransactionBlock, amount: MoveNumber) {\n const feeObject = this.feeObject();\n return this.addContractCall(txb, {\n method: FeeContract.MethodName.streaming_fee,\n arguments: [feeObject, amount],\n typeArgs: [],\n });\n }\n\n claimFee(txb: TransactionBlock, amount: MoveNumber) {\n return this.addContractCall(txb, {\n method: FeeContract.MethodName.claim_fee,\n arguments: [this.feeObject(), amount],\n typeArgs: [],\n });\n }\n\n feeDenominator(txb: TransactionBlock) {\n return this.addContractCall(txb, {\n method: FeeContract.MethodName.fee_denominator,\n arguments: [this.feeObject()],\n typeArgs: [],\n });\n }\n}\n","import { TransactionBlock } from '@mysten/sui.js/transactions';\n\nimport { BaseContract } from './BaseContract';\nimport { ContractConfig, Globals } from '../common';\nimport { Ref, ObjectId, MoveNumber } from '../common/transaction';\n\nexport class StreamContract extends BaseContract {\n static ModuleName = 'stream';\n\n static MethodName = {\n create_stream: 'create_stream',\n set_auto_claim: 'set_auto_claim',\n cancel_stream: 'cancel_stream',\n claim_stream: 'claim_stream',\n claim_stream_by_proxy: 'claim_stream_by_proxy',\n stream_current_epoch: 'stream_current_epoch',\n now_milli_seconds: 'now_milli_seconds',\n } as const;\n\n constructor(\n public readonly config: ContractConfig,\n public readonly globals: Globals,\n ) {\n super(StreamContract.ModuleName, config, globals);\n }\n\n createStream(\n txb: TransactionBlock,\n input: {\n paymentCoin: Ref<ObjectId>;\n flatFeeCoin: Ref<ObjectId>;\n metadata: string;\n recipient: string;\n timeStart: Ref<MoveNumber>;\n cliff: Ref<MoveNumber>;\n epochInterval: Ref<MoveNumber>;\n numEpoch: Ref<MoveNumber>;\n amountPerEpoch: Ref<MoveNumber>;\n cancelable: boolean;\n coinType: string;\n },\n ) {\n const feeObject = this.feeObject();\n const vaultObject = this.vaultObject();\n const paymentCoinObject = this.makeObject(input.paymentCoin);\n const flatFeeObject = this.makeObject(input.flatFeeCoin);\n const clockObject = this.clockObject();\n return this.addContractCall(txb, {\n method: StreamContract.MethodName.create_stream,\n arguments: [\n feeObject,\n vaultObject,\n paymentCoinObject,\n flatFeeObject,\n input.metadata,\n input.recipient,\n input.timeStart,\n input.cliff,\n input.epochInterval,\n input.numEpoch,\n input.amountPerEpoch,\n input.cancelable,\n clockObject,\n ],\n typeArgs: [input.coinType],\n });\n }\n\n setAutoClaim(\n txb: TransactionBlock,\n input: {\n streamId: Ref<ObjectId>;\n enabled: boolean;\n coinType: string;\n },\n ) {\n const streamObject = this.makeObject(input.streamId);\n return this.addContractCall(txb, {\n method: StreamContract.MethodName.set_auto_claim,\n arguments: [streamObject, input.enabled],\n typeArgs: [input.coinType],\n });\n }\n\n cancelStream(\n txb: TransactionBlock,\n input: {\n streamId: Ref<ObjectId>;\n coinType: string;\n },\n ) {\n const streamObject = this.makeObject(input.streamId);\n const clockObject = this.clockObject();\n return this.addContractCall(txb, {\n method: StreamContract.MethodName.cancel_stream,\n arguments: [streamObject, clockObject],\n typeArgs: [input.coinType],\n });\n }\n\n claimStream(\n txb: TransactionBlock,\n input: {\n streamId: Ref<ObjectId>;\n coinType: string;\n },\n ) {\n const streamObject = this.makeObject(input.streamId);\n const clockObject = this.clockObject();\n return this.addContractCall(txb, {\n method: StreamContract.MethodName.claim_stream,\n arguments: [streamObject, clockObject],\n typeArgs: [input.coinType],\n });\n }\n\n claimStreamByProxy(\n txb: TransactionBlock,\n input: {\n streamId: Ref<ObjectId>;\n coinType: string;\n },\n ) {\n const streamObject = this.makeObject(input.streamId);\n const vaultObject = this.vaultObject();\n const feeObject = this.feeObject();\n const clockObject = this.clockObject();\n return this.addContractCall(txb, {\n method: StreamContract.MethodName.claim_stream_by_proxy,\n arguments: [streamObject, vaultObject, feeObject, clockObject],\n typeArgs: [input.coinType],\n });\n }\n\n get createStreamTarget() {\n return `${this.config.contractId}::${StreamContract.ModuleName}::${StreamContract.MethodName.create_stream}`;\n }\n\n get setAutoClaimTarget() {\n return `${this.config.contractId}::${StreamContract.ModuleName}::${StreamContract.MethodName.set_auto_claim}`;\n }\n\n get cancelStreamTarget() {\n return `${this.config.contractId}::${StreamContract.ModuleName}::${StreamContract.MethodName.cancel_stream}`;\n }\n\n get claimStreamTarget() {\n return `${this.config.contractId}::${StreamContract.ModuleName}::${StreamContract.MethodName.claim_stream}`;\n }\n\n get claimStreamByProxyTarget() {\n return `${this.config.contractId}::${StreamContract.ModuleName}::${StreamContract.MethodName.claim_stream_by_proxy}`;\n }\n}\n","import { MPayError, JsonObject, MPayErrorCode } from './base';\n\n/**\n * SanityError is the error reported because of error in code.\n * For normal user process, the sanity error shall never be thrown.\n */\nexport class SanityError extends MPayError {\n constructor(msg: string, options: { cause?: unknown; context?: JsonObject } = {}) {\n super(MPayErrorCode.sanity, msg, options);\n }\n}\n","import { PagedData, Requester } from './requester';\n\nexport const REQUEST_PAGE_SIZE = 25;\n\nexport interface SuiIterator<T> {\n next: () => Promise<T | undefined>;\n hasNext: () => Promise<boolean>;\n}\n\nexport async function getAllFromIterator<T>(it: SuiIterator<T>): Promise<(T | undefined) | (T | undefined)[]> {\n const res: (T | undefined)[] = [];\n while (await it.hasNext()) {\n const val = await it.next();\n res.push(val);\n }\n if (res && Array.isArray(res[0])) {\n return res.flat(1) as T;\n }\n return res;\n}\n\nexport class PagedIterator<T> implements SuiIterator<(T | undefined)[]> {\n private curPage: PagedData<T> | undefined;\n\n private init: boolean;\n\n constructor(public readonly requester: Requester<T>) {\n this.curPage = undefined;\n this.init = true;\n }\n\n async hasNext(): Promise<boolean> {\n if (this.init) {\n if (!this.curPage) {\n this.curPage = await this.requester.doNextRequest();\n }\n return !!this.curPage.data?.length || this.curPage.hasNext;\n }\n if (!this.curPage) {\n throw new Error('invalid implementation of iterator');\n }\n return this.curPage.hasNext;\n }\n\n async next(): Promise<(T | undefined)[]> {\n if (this.init) {\n this.init = false;\n if (!this.curPage) {\n this.curPage = await this.requester.doNextRequest();\n }\n return this.curPage.data;\n }\n this.curPage = await this.requester.doNextRequest();\n return this.curPage.data;\n }\n}\n\nexport class EntryIterator<T> implements SuiIterator<T> {\n cursor: number;\n\n pager: PagedIterator<T>;\n\n curData: (T | undefined)[];\n\n constructor(public readonly requester: Requester<T>) {\n this.pager = new PagedIterator<T>(requester);\n this.curData = [];\n this.cursor = 0;\n }\n\n async hasNext(): Promise<boolean> {\n if (this.cursor < this.curData.length - 1) {\n return true;\n }\n return this.pager.hasNext();\n }\n\n async next(): Promise<T | undefined> {\n this.cursor += 1;\n while (this.cursor >= this.curData.length) {\n if (!(await this.pager.hasNext())) {\n throw new Error('not more data'); // Shall not happen for legit data source.\n } else {\n this.curData = await this.pager.next();\n this.cursor = 0;\n }\n }\n return this.curData[this.cursor];\n }\n}\n","import { MPayError, MPayErrorCode } from './base';\n\nexport class NotEnoughBalanceError extends MPayError {\n constructor(\n public readonly coinType: string,\n public readonly requestAmount: bigint,\n public readonly gotAmount: bigint,\n ) {\n super(MPayErrorCode.NotEnoughBalance, `Not enough balance: ${coinType}`, {\n context: {\n coinType,\n requestAmount,\n gotAmount,\n },\n });\n }\n}\n","import { SuiClient, CoinStruct } from '@mysten/sui.js/client';\n\nimport { getAllFromIterator, EntryIterator } from './iterator';\nimport { Requester, PagedData } from './requester';\nimport { NotEnoughBalanceError } from '../../error/NotEnoughBalanceError';\nimport { SanityError } from '../../error/SanityError';\n\nconst DEF_REQ_PAGE_SIZE = 25;\n\nexport async function getCoinsWithAmount(\n suiClient: SuiClient,\n owner: string,\n requestAmount: bigint,\n coinType = '0x2::sui::SUI',\n pageSize: number = DEF_REQ_PAGE_SIZE,\n) {\n const it = new OwnedCoinIterator(suiClient, owner, coinType, pageSize);\n let totalAmount = BigInt(0);\n const res: CoinStruct[] = [];\n while ((await it.hasNext()) && totalAmount < requestAmount) {\n const val = await it.next();\n if (!val) {\n continue;\n }\n res.push(val);\n totalAmount += BigInt(val.balance);\n }\n if (totalAmount < requestAmount) {\n throw new NotEnoughBalanceError(coinType, requestAmount, totalAmount);\n }\n return res;\n}\n\nexport async function getAllOwnedCoins(\n suiClient: SuiClient,\n owner: string,\n coinType = '0x2::sui::SUI',\n pageSize: number = DEF_REQ_PAGE_SIZE,\n) {\n const iter = new OwnedCoinIterator(suiClient, owner, coinType, pageSize);\n return (await getAllFromIterator(iter)) as CoinStruct[];\n}\n\nexport class OwnedCoinIterator extends EntryIterator<CoinStruct> {\n constructor(\n private readonly suiClient: SuiClient,\n private readonly owner: string,\n private readonly coinType: string,\n private readonly reqPageSize: number,\n ) {\n super(new OwnedCoinRequester(suiClient, owner, coinType, reqPageSize));\n }\n}\n\nexport class OwnedCoinRequester implements Requester<CoinStruct> {\n nextCursor: string | null | undefined;\n\n constructor(\n private readonly suiClient: SuiClient,\n private readonly owner: string,\n private readonly coinType: string,\n private readonly reqPageSize: number,\n ) {\n if (reqPageSize <= 0) {\n throw new SanityError('Invalid reqPageSize');\n }\n }\n\n async doNextRequest(): Promise<PagedData<CoinStruct>> {\n const res = await this.suiClient.getCoins({\n owner: this.owner,\n coinType: this.coinType,\n cursor: this.nextCursor,\n limit: this.reqPageSize,\n });\n this.nextCursor = res.nextCursor;\n return {\n data: res.data,\n hasNext: res.hasNextPage,\n };\n }\n}\n","import { SuiObjectData, SuiObjectResponse, SuiParsedData } from '@mysten/sui.js/client';\nimport { TransactionBlock } from '@mysten/sui.js/transactions';\nimport { normalizeStructTag, parseStructTag } from '@mysten/sui.js/utils';\nimport { DateTime, Duration } from 'luxon';\n\nimport { decodeMetadata } from './metadata';\nimport { Globals } from '../common';\nimport { StreamContract } from '../contract/StreamContract';\nimport { NotCreatorError } from '../error/NotCreatorError';\nimport { NotRecipientError } from '../error/NotRecipientError';\nimport { RpcError } from '../error/RpcError';\nimport { SanityError } from '../error/SanityError';\nimport { StreamNotFoundError } from '../error/StreamNotFoundError';\nimport { RawStreamData, RawStreamStatusEnum } from '../types/data';\nimport { StreamEvent } from '../types/events';\nimport { PaginationOptions, Paginated } from '../types/pagination';\nimport { IStream, StreamInfo, StreamGroupCommonInfo, StreamProgress, StreamStatus } from '../types/stream';\nimport { MAX_U64, roundDateTime, roundDuration } from '../utils/utils';\n\nexport class Stream implements IStream {\n private readonly streamContract: StreamContract;\n\n public readonly type = 'Stream';\n\n constructor(\n public readonly globals: Globals,\n public readonly streamId: string,\n public rawData: RawStreamData,\n ) {\n this.streamContract = new StreamContract(globals.envConfig.contract, globals);\n }\n\n static async new(globals: Globals, streamId: string) {\n const rawData = await Stream.fetchStreamData(globals, streamId);\n return new Stream(globals, streamId, rawData);\n }\n\n static fromObjectData(globals: Globals, streamId: string, data: SuiObjectResponse) {\n const rawData = Stream.parseRawStreamData(streamId, data);\n return new Stream(globals, streamId, rawData);\n }\n\n get info(): StreamInfo {\n return {\n name: this.name,\n creator: this.creator,\n coinType: this.coinType,\n totalAmount: this.totalAmount,\n start: this.timeStart,\n end: this.timeEnd,\n cancelable: this.cancelable,\n cliffAmount: this.cliff,\n duration: this.duration,\n interval: this.interval,\n steps: this.totalSteps,\n nextReleaseDate: this.nextReleaseDate,\n nextReleaseAmount: this.nextReleaseAmount,\n\n groupId: this.groupId,\n streamId: this.streamId,\n recipient: this.recipient,\n progress: this.progress,\n autoClaim: this.autoClaim,\n };\n }\n\n get groupCommonInfo(): StreamGroupCommonInfo {\n return {\n name: this.name,\n groupId: this.groupId,\n creator: this.creator,\n start: this.timeStart,\n interval: this.interval,\n steps: this.totalSteps,\n cancelable: this.cancelable,\n };\n }\n\n async refresh() {\n this.rawData = await Stream.fetchStreamData(this.globals, this.streamId);\n }\n\n refreshWithData(data: SuiObjectResponse) {\n if (data.data?.objectId !== this.streamId) {\n throw new SanityError('Object Id does not align');\n }\n this.rawData = Stream.parseRawStreamData(this.streamId, data);\n }\n\n async historyEvents(pagination?: PaginationOptions): Promise<Paginated<StreamEvent>> {\n return this.globals.backend.getStreamHistory({\n streamId: this.streamId,\n pagination,\n });\n }\n\n async cancel() {\n if ((await this.globals.walletAddress()) !== this.creator) {\n throw new NotCreatorError();\n }\n const txb = new TransactionBlock();\n this.streamContract.cancelStream(txb, {\n streamId: this.streamId,\n coinType: this.coinType,\n });\n return txb;\n }\n\n async claim() {\n if ((await this.globals.walletAddress()) !== this.recipient) {\n throw new NotRecipientError();\n }\n const txb = new TransactionBlock();\n this.streamContract.claimStream(txb, {\n streamId: this.streamId,\n coinType: this.coinType,\n });\n return txb;\n }\n\n async setAutoClaim(enabled: boolean) {\n if ((await this.globals.walletAddress()) !== this.recipient) {\n throw new NotRecipientError();\n }\n const txb = new TransactionBlock();\n this.streamContract.setAutoClaim(txb, {\n streamId: this.streamId,\n coinType: this.coinType,\n enabled,\n });\n return txb;\n }\n\n async claimByProxy() {\n const txb = new TransactionBlock();\n this.streamContract.claimStreamByProxy(txb, {\n streamId: this.streamId,\n coinType: this.coinType,\n });\n return txb;\n }\n\n get wallet() {\n return this.globals.wallet;\n }\n\n get client() {\n return this.globals.suiClient;\n }\n\n get coinType() {\n return normalizeStructTag(this.rawData.coinType);\n }\n\n get progress(): StreamProgress {\n return {\n status: this.streamStatus,\n total: this.totalAmount,\n streamed: this.streamedAmount,\n claimed: this.claimedAmount,\n claimable: this.claimable,\n canceled: this.canceledAmount,\n };\n }\n\n get balance() {\n return this.rawData.balance;\n }\n\n get autoClaim() {\n return this.rawData.autoClaim;\n }\n\n get amountPerEpoch() {\n return this.rawData.config.amountPerEpoch;\n }\n\n get cancelable() {\n return this.rawData.config.cancelable;\n }\n\n get cliff() {\n return this.rawData.config.cliff;\n }\n\n get creator() {\n return this.rawData.config.creator;\n }\n\n get interval(): Duration {\n return roundDuration(this.rawData.config.epochInterval);\n }\n\n get groupId() {\n const { metadata } = this.rawData.config;\n const md = decodeMetadata(metadata);\n return md.groupId;\n }\n\n get name() {\n const { metadata } = this.rawData.config;\n const md = decodeMetadata(metadata);\n return md.name;\n }\n\n get recipient() {\n return this.rawData.config.recipient;\n }\n\n get timeStart(): DateTime {\n return roundDateTime(this.rawData.config.timeStart);\n }\n\n get duration(): Duration {\n const rawConfig = this.rawData.config;\n const duration = rawConfig.epochInterval * rawConfig.totalEpoch;\n return roundDuration(duration);\n }\n\n get timeEnd(): DateTime {\n return this.timeStart.plus(this.duration);\n }\n\n get totalSteps(): bigint {\n return this.rawData.config.totalEpoch;\n }\n\n get claimable(): bigint {\n return this.streamedAmount - this.claimedAmount;\n }\n\n get nextReleaseDate(): DateTime | null {\n if (this.currentEpoch === -1n) {\n return this.timeStart;\n }\n if (this.currentEpoch >= this.totalSteps || this.isCanceled) {\n return null;\n }\n return roundDateTime((this.currentEpoch + 1n) * this.rawData.config.epochInterval + this.rawData.config.timeStart);\n }\n\n get nextReleaseAmount(): bigint | null {\n if (this.currentEpoch === -1n) {\n return this.cliff;\n }\n if (this.currentEpoch >= this.totalSteps || this.isCanceled) {\n return null;\n }\n return this.amountPerEpoch;\n }\n\n get streamStatus(): StreamStatus {\n const rawStatus = this.rawData.status.status;\n if (rawStatus === RawStreamStatusEnum.CANCELED) {\n return StreamStatus.CANCELED;\n }\n if (rawStatus === RawStreamStatusEnum.CANCELED_COMPLETED) {\n return StreamStatus.SETTLED;\n }\n if (rawStatus === RawStreamStatusEnum.COMPLETED) {\n return StreamStatus.COMPLETED;\n }\n if (this.currentEpoch >= this.totalSteps) {\n return StreamStatus.STREAMED;\n }\n return StreamStatus.STREAMING;\n }\n\n get streamedAmount() {\n if (this.currentEpoch === -1n) {\n return 0n;\n }\n if (this.isCanceled) {\n return this.rawData.status.epochCanceled * this.amountPerEpoch + this.cliff;\n }\n return this.currentEpoch * this.amountPerEpoch + this.cliff;\n }\n\n get claimedAmount() {\n if (this.rawData.status.epochClaimed === MAX_U64) {\n return 0n;\n }\n return this.rawData.status.epochClaimed * this.amountPerEpoch + this.cliff;\n }\n\n get currentEpoch() {\n const timeNowMs = DateTime.now().toMillis();\n const timeStartMs = this.timeStart.toMillis();\n if (timeNowMs < timeStartMs) {\n return -1n;\n }\n const epoch = Math.floor((timeNowMs - timeStartMs) / Number(this.rawData.config.epochInterval));\n return BigInt(epoch) > Number(this.rawData.config.totalEpoch) ? this.rawData.config.totalEpoch : BigInt(epoch);\n }\n\n get totalAmount() {\n const rawConfig = this.rawData.config;\n return rawConfig.amountPerEpoch * rawConfig.totalEpoch + rawConfig.cliff;\n }\n\n get isCanceled() {\n const rawStatus = this.rawData.status.status;\n return rawStatus === RawStreamStatusEnum.CANCELED || rawStatus === RawStreamStatusEnum.CANCELED_COMPLETED;\n }\n\n get canceledAmount() {\n return this.isCanceled ? this.totalAmount - this.streamedAmount : 0n;\n }\n\n private static async fetchStreamData(globals: Globals, streamId: string) {\n const res = await globals.suiClient.getObject({\n id: streamId,\n options: {\n showContent: true,\n showType: true,\n },\n });\n return Stream.parseRawStreamData(streamId, res);\n }\n\n static parseRawStreamData(streamId: string, res: SuiObjectResponse): RawStreamData {\n if (res.error) {\n if (res.error.code === 'notExists') {\n throw new StreamNotFoundError(streamId);\n }\n throw new RpcError(`get stream data: ${res.error.code}`, {\n streamId,\n ...res.error,\n });\n }\n const content = (res.data as SuiObjectData).content as SuiParsedData;\n if (content.dataType !== 'moveObject') {\n throw new RpcError('Unexpected object type', {\n gotType: content.dataType,\n });\n }\n const { typeParams } = parseStructTag(content.type);\n const coinType = normalizeStructTag(typeParams[0]);\n\n const dataFields = content.fields as any;\n const config = dataFields.config.fields as any;\n const status = dataFields.status.fields as any;\n\n return {\n coinType,\n autoClaim: dataFields.auto_claim as boolean,\n balance: BigInt(dataFields.balance.fields.balance),\n config: {\n amountPerEpoch: BigInt(config.amount_per_epoch),\n cancelable: config.cancelable,\n cliff: BigInt(config.cliff),\n creator: config.creator,\n epochInterval: BigInt(config.epoch_interval),\n metadata: config.metadata,\n recipient: config.recipient,\n timeStart: BigInt(config.time_start),\n totalEpoch: BigInt(config.total_epoch),\n },\n status: {\n status: status.status as RawStreamStatusEnum,\n epochCanceled: BigInt(status.epoch_canceled),\n epochClaimed: BigInt(status.epoch_claimed),\n },\n };\n }\n}\n","import { MPayError, MPayErrorCode } from './base';\n\nexport class NotCreatorError extends MPayError {\n constructor() {\n super(MPayErrorCode.NotCreator, 'Connected wallet is not creator');\n }\n}\n","import { MPayError, MPayErrorCode } from './base';\n\nexport class NotRecipientError extends MPayError {\n constructor() {\n super(MPayErrorCode.NotRecipient, 'Connected wallet is not recipient');\n }\n}\n","import { MPayError, JsonObject, MPayErrorCode } from './base';\n\nexport class RpcError extends MPayError {\n constructor(msg: string, context?: JsonObject) {\n super(MPayErrorCode.RpcError, msg, {\n context,\n });\n }\n}\n","import { MPayError, MPayErrorCode } from './base';\n\nexport class StreamNotFoundError extends MPayError {\n constructor(streamId: string) {\n super(MPayErrorCode.StreamNotFound, 'Stream not found', {\n context: {\n streamId,\n },\n });\n }\n}\n","// eslint-disable-next-line no-bitwise\nimport { DateTime, Duration } from 'luxon';\n\n// eslint-disable-next-line no-bitwise\nexport const MAX_U64 = (1n << 64n) - 1n;\n\nexport const TIME_ROUND_UNIT = 1000;\n\n// roundTime round date to seconds\nexport function roundDateTime(date: DateTime | number | bigint) {\n let dateMs: number;\n if (typeof date === 'number') {\n dateMs = date;\n } else if (typeof date === 'bigint') {\n dateMs = Number(date);\n } else {\n dateMs = date.toMillis();\n }\n const roundMs = Math.round(dateMs / TIME_ROUND_UNIT);\n return DateTime.fromMillis(roundMs * TIME_ROUND_UNIT);\n}\n\nexport function roundDuration(duration: Duration | number | bigint) {\n let durationMs: number;\n if (typeof duration === 'number') {\n durationMs = duration;\n } else if (typeof duration === 'bigint') {\n durationMs = Number(duration);\n } else {\n durationMs = duration.toMillis();\n }\n const roundMs = Math.round(durationMs / TIME_ROUND_UNIT);\n return Duration.fromMillis(roundMs * TIME_ROUND_UNIT);\n}\n","import {\n CoinMetadata,\n SuiClient,\n SuiObjectChangeCreated,\n SuiTransactionBlockResponse,\n DevInspectResults,\n} from '@mysten/sui.js/client';\nimport { TransactionBlock } from '@mysten/sui.js/transactions';\nimport { normalizeStructTag, SUI_TYPE_ARG } from '@mysten/sui.js/utils';\nimport { DateTime, Duration } from 'luxon';\n\nimport { CreateStreamHelper } from '../builder/CreateStreamHelper';\nimport { MPayBuilder } from '../builder/MPayBuilder';\nimport { Globals } from '../common';\nimport { InvalidInputError } from '../error/InvalidInputError';\nimport { TransactionFailedError } from '../error/TransactionFailedError';\nimport {\n IMPayHelper,\n CreateStreamInfo,\n PaymentWithFee,\n MPayFees,\n Fraction,\n CalculatedStreamAmount,\n CalculatedTimeline,\n} from '../types/client';\n\n// Minimum time interval is 1 second\nexport const MIN_INTERVAL_MS = 1000;\n\nexport class MPayHelper implements IMPayHelper {\n private readonly coinMetaHelper: CoinMetaHelper;\n\n private readonly createStreamHelper: CreateStreamHelper;\n\n constructor(public readonly globals: Globals) {\n this.coinMetaHelper = new CoinMetaHelper(globals.suiClient);\n this.createStreamHelper = new MPayBuilder(globals).createStreamHelper();\n }\n\n getStreamIdsFromCreateStreamResponse(res: SuiTransactionBlockResponse) {\n if (res.effects?.status.status !== 'success') {\n throw new TransactionFailedError(res.effects?.status.status, res.effects?.status.error);\n }\n return res\n .objectChanges!.filter(\n (change) =>\n change.type === 'created' &&\n change.objectType.startsWith(`${this.globals.envConfig.contract.contractId}::stream::Stream`),\n )\n .map((change) => (change as SuiObjectChangeCreated).objectId);\n }\n\n calculateCreateStreamFees(info: CreateStreamInfo): PaymentWithFee {\n return this.createStreamHelper.calculateCreateStreamFees(info);\n }\n\n feeParams(): MPayFees {\n return this.createStreamHelper.feeParams();\n }\n\n calculateStreamAmount(input: { totalAmount: bigint; steps: bigint; cliff?: Fraction }): CalculatedStreamAmount {\n if (input.steps === 0n) {\n throw new InvalidInputError('Invalid stream steps: 0');\n }\n const cliffFraction = input.cliff\n ? input.cliff\n : {\n numerator: 0n,\n denominator: 100n,\n };\n const cliffAmount = (input.totalAmount * cliffFraction.numerator) / cliffFraction.denominator;\n const amountPerStep = (input.totalAmount - cliffAmount) / input.steps;\n const realTotalAmount = amountPerStep * input.steps + cliffAmount;\n\n const res = {\n realTotalAmount,\n cliffAmount,\n amountPerStep,\n };\n this.validateStreamAmount(res, input.totalAmount);\n return res;\n }\n\n calculateTimelineByInterval(input: { timeStart: DateTime; interval: Duration; steps: bigint }): CalculatedTimeline {\n if (input.steps === 0n) {\n throw new InvalidInputError('Invalid stream steps: 0');\n }\n const timeEnd = input.timeStart.plus(input.interval.toMillis() * Number(input.steps));\n\n const res = {\n timeStart: input.timeStart,\n timeEnd,\n interval: input.interval,\n steps: input.steps,\n };\n this.validateTimeline(res);\n return res;\n }\n\n calculateTimelineByTotalDuration(input: { timeStart: DateTime; total: Duration; steps: bigint }): CalculatedTimeline {\n if (input.steps === 0n) {\n throw new InvalidInputError('Invalid stream steps: 0');\n }\n const intervalMilli = BigInt(input.total.toMillis()) / input.steps;\n const timeEnd = input.timeStart.plus(Duration.fromMillis(Number(intervalMilli * input.steps)));\n const res = {\n timeStart: input.timeStart,\n timeEnd,\n interval: Duration.fromMillis(Number(intervalMilli)),\n steps: input.steps,\n };\n this.validateTimeline(res);\n return res;\n }\n\n async getBalance(address: string, coinType?: string | null) {\n const balance = await this.globals.suiClient.getBalance({\n owner: address,\n coinType,\n });\n const coinMeta = await this.getCoinMeta(coinType);\n return {\n ...balance,\n coinType: normalizeStructTag(balance.coinType),\n coinMeta,\n };\n }\n\n async getAllBalance(address: string) {\n const allBalance = await this.globals.suiClient.getAllBalances({\n owner: address,\n });\n const coinMetas = await Promise.all(allBalance.map((bal) => this.getCoinMeta(bal.coinType)));\n return allBalance.map((bal, i) => ({\n ...bal,\n coinType: normalizeStructTag(bal.coinType),\n coinMeta: coinMetas[i],\n }));\n }\n\n async getCoinMeta(coinType: string | null | undefined) {\n return this.coinMetaHelper.getCoinMeta(coinType);\n }\n\n async simulateTransactionBlock(txb: TransactionBlock): Promise<DevInspectResults> {\n return this.globals.suiClient.devInspectTransactionBlock({\n transactionBlock: txb,\n sender: await this.globals.wallet.address(),\n });\n }\n\n private validateStreamAmount(val: CalculatedStreamAmount, originTotalAmount: bigint) {\n if (val.amountPerStep === 0n) {\n throw new InvalidInputError('Stream amount too small', 'totalAmount', originTotalAmount);\n }\n if (val.cliffAmount > val.realTotalAmount) {\n throw new InvalidInputError('Invalid cliff settings');\n }\n }\n\n private validateTimeline(val: CalculatedTimeline) {\n if (val.interval.toMillis() < MIN_INTERVAL_MS) {\n throw new InvalidInputError('Interval shall be at least 1 second', 'interval', val.interval);\n }\n }\n}\n\nexport class CoinMetaHelper {\n private coinMetaReg: Map<string, CoinMetadata>;\n\n constructor(private readonly suiClient: SuiClient) {\n this.coinMetaReg = new Map();\n }\n\n async getCoinMeta(coinType: string | null | undefined): Promise<CoinMetadata | undefined> {\n const normalized = normalizeStructTag(coinType || SUI_TYPE_ARG);\n if (this.coinMetaReg.has(normalized)) {\n return this.coinMetaReg.get(normalized);\n }\n const meta = await this.queryCoinMeta(normalized);\n if (meta) {\n this.coinMetaReg.set(normalized, meta);\n }\n return meta;\n }\n\n private async queryCoinMeta(coinType: string): Promise<CoinMetadata | undefined> {\n const res = await this.suiClient.getCoinMetadata({ coinType });\n return res || undefined;\n }\n}\n","import { MPayError, MPayErrorCode } from './base';\n\nexport class TransactionFailedError extends MPayError {\n constructor(status: string | undefined, msg: string | undefined) {\n super(MPayErrorCode.TransactionFailed, `Transaction failed: ${msg}`, {\n context: {\n status,\n msg,\n },\n });\n }\n}\n","import { SuiObjectResponse } from '@mysten/sui.js/client';\nimport { normalizeStructTag, normalizeSuiAddress } from '@mysten/sui.js/utils';\nimport { DateTime } from 'luxon';\n\nimport { Stream } from './Stream';\nimport { StreamGroup } from './StreamGroup';\nimport { Globals } from '../common';\nimport { InvalidInputError } from '../error/InvalidInputError';\nimport { SanityError } from '../error/SanityError';\nimport { SuiIterator } from '../sui/iterator/iterator';\nimport { ObjectBatchIterator, ListOidIterator } from '../sui/iterator/object';\nimport {\n StreamRef,\n BackendIncomingStreamFilterOptions,\n BackendOutgoingStreamFilterOptions,\n StreamFilterStatus,\n} from '../types/backend';\nimport { IPagedStreamListIterator, IncomingStreamQuery, OutgoingStreamQuery } from '../types/client';\nimport { IStream, IStreamGroup, StreamStatus } from '../types/stream';\n\nexport class PagedStreamListIterator implements IPagedStreamListIterator {\n private constructor(\n public readonly it: StreamListIterator,\n public readonly pageSize: number,\n ) {}\n\n static async newIncoming(input: {\n globals: Globals;\n query?: IncomingStreamQuery;\n pageSize: number;\n }): Promise<PagedStreamListIterator> {\n const it = await StreamListIterator.newIncoming(input);\n return new PagedStreamListIterator(it, input.pageSize);\n }\n\n static async newOutgoing(input: {\n globals: Globals;\n query?: OutgoingStreamQuery;\n pageSize: number;\n }): Promise<PagedStreamListIterator> {\n const it = await StreamListIterator.newOutgoing(input);\n return new PagedStreamListIterator(it, input.pageSize);\n }\n\n async hasNext() {\n return this.it.hasNext();\n }\n\n async next(): Promise<(IStream | IStreamGroup)[]> {\n const res: (IStream | IStreamGroup)[] = [];\n while (res.length < this.pageSize && (await this.it.hasNext())) {\n res.push(await this.it.next());\n }\n return res;\n }\n}\n\nexport class StreamListIterator implements SuiIterator<IStream | IStreamGroup> {\n cachedNext: IStream | IStreamGroup | undefined | null;\n\n private constructor(private readonly requester: StreamListRequester) {}\n\n static async newIncoming(input: { globals: Globals; query?: IncomingStreamQuery }) {\n const requester = await StreamListRequester.newIncomingQuery(input);\n return new StreamListIterator(requester);\n }\n\n static async newOutgoing(input: { globals: Globals; query?: OutgoingStreamQuery }) {\n const requester = await StreamListRequester.newOutgoingQuery(input);\n return new StreamListIterator(requester);\n }\n\n async hasNext(): Promise<boolean> {\n if (this.cachedNext === undefined) {\n this.cachedNext = await this.requester.doNextRequest();\n }\n return this.cachedNext !== null;\n }\n\n async next(): Promise<IStream | IStreamGroup> {\n if (this.cachedNext === undefined) {\n const res = await this.requester.doNextRequest();\n if (res === null) {\n throw new SanityError('No more results');\n }\n return res;\n }\n const res = this.cachedNext;\n this.cachedNext = undefined;\n if (res === null) {\n throw new SanityError('No more results');\n }\n return res as IStream | IStreamGroup;\n }\n}\n\nexport class StreamListRequester {\n public current = 0;\n\n public objectIter: ObjectBatchIterator;\n\n private constructor(\n public readonly globals: Globals,\n public readonly recipient: string,\n public readonly groupRefs: StreamRef[][],\n public readonly query?: IncomingStreamQuery | OutgoingStreamQuery,\n ) {\n this.current = 0;\n const oidIter = new ListOidIterator(groupRefs.flat().map((ref) => ref.streamId));\n this.objectIter = new ObjectBatchIterator(globals.suiClient, oidIter);\n }\n\n static async newIncomingQuery(input: { globals: Globals; query?: IncomingStreamQuery }) {\n const backendQuery = convertToIncomingBackendQuery(input.query);\n const recipient = await input.globals.walletAddress();\n const refs = await input.globals.backend.getIncomingStreams(recipient, backendQuery);\n const filtered = refs.filter((ref: any) => normalizeSuiAddress(ref.recipient) === normalizeSuiAddress(recipient));\n const groupedRefs = groupAndSortRefs(filtered);\n\n return new StreamListRequester(input.globals, recipient, groupedRefs, input.query);\n }\n\n static async newOutgoingQuery(input: { globals: Globals; query?: OutgoingStreamQuery }) {\n const backendQuery = convertToOutgoingBackendQuery(input.query);\n const sender = await input.globals.walletAddress();\n const refs = await input.globals.backend.getOutgoingStreams(sender, backendQuery);\n const groupedRefs = groupAndSortRefs(refs);\n return new StreamListRequester(input.globals, sender, groupedRefs, input.query);\n }\n\n async doNextRequest(): Promise<IStream | IStreamGroup | null> {\n if (this.current >= this.groupRefs.length) {\n return null;\n }\n const stRefs = this.groupRefs[this.current];\n if (stRefs.length === 1) {\n const stream = await getStreamFromIterator(this.globals, stRefs[0].streamId, this.objectIter);\n this.current++;\n return isStreamOfQuery(stream, this.query) ? stream : this.doNextRequest();\n }\n if (stRefs.length > 1) {\n const sg = await getStreamGroupFromIterator(\n this.globals,\n stRefs.map((ref) => ref.streamId),\n this.objectIter,\n );\n this.current++;\n return isStreamGroupOfQuery(sg, this.query) ? sg : this.doNextRequest();\n }\n throw new SanityError('Stream group with no stream');\n }\n}\n\nexport function groupAndSortRefs(refs: StreamRef[]) {\n const m = new Map<string, StreamRef[]>();\n refs.forEach((ref) => {\n const groupList = m.get(ref.groupId);\n if (groupList) {\n groupList.push(ref);\n m.set(ref.groupId, groupList);\n } else {\n m.set(ref.groupId, [ref]);\n }\n });\n return Array.from(m.values()).sort(\n (gl1, gl2) => DateTime.fromISO(gl2[0].createDate).toMillis() - DateTime.fromISO(gl1[0].createDate).toMillis(),\n );\n}\n\nfunction isStreamOfQuery(stream: IStream, query: IncomingStreamQuery | OutgoingStreamQuery | undefined) {\n if (query === undefined) {\n return true;\n }\n const isStatus = isStreamOfStatus(stream, query.status);\n if (query && 'claimable' in query && query.claimable !== undefined) {\n const isClaimable = query.claimable ? stream.progress.claimable !== 0n : stream.progress.claimable === 0n;\n return isStatus && isClaimable;\n }\n return isStatus;\n}\n\nfunction isStreamOfStatus(stream: IStream, filter: StreamStatus | StreamStatus[] | undefined): boolean {\n if (filter === undefined) {\n return true;\n }\n if (!Array.isArray(filter)) {\n return stream.progress.status === filter;\n }\n return filter.includes(stream.progress.status);\n}\n\nfunction isStreamGroupOfQuery(sg: IStreamGroup, query: IncomingStreamQuery | OutgoingStreamQuery | undefined): boolean {\n if (!query) {\n return true;\n }\n let isStatus = false;\n sg.streams.forEach((stream) => {\n if (isStreamOfQuery(stream, query)) {\n isStatus = true;\n }\n });\n return isStatus;\n}\n\nasync function getStreamFromIterator(globals: Globals, streamId: string, it: ObjectBatchIterator) {\n const data = await getStreamObjectResponseFromIter(it, streamId);\n return Stream.fromObjectData(globals, streamId, data);\n}\n\nasync function getStreamGroupFromIterator(globals: Globals, streamIds: string[], it: ObjectBatchIterator) {\n const objResponses: SuiObjectResponse[] = [];\n while (objResponses.length < streamIds.length) {\n const data = await getStreamObjectResponseFromIter(it, streamIds[objResponses.length]);\n objResponses.push(data);\n }\n return StreamGroup.newFromObjectResponse(globals, streamIds, objResponses);\n}\n\nasync function getStreamObjectResponseFromIter(it: ObjectBatchIterator, streamId: string) {\n if (!(await it.hasNext())) {\n throw new SanityError('object iterator has been consumed');\n }\n const data = await it.next();\n if (!data || data.error || data.data === undefined || data.data === null) {\n throw new SanityError(`object iterator undefined response`, {\n cause: data?.error,\n });\n }\n if (data?.data?.objectId !== streamId) {\n throw new SanityError('stream id not aligned');\n }\n return data;\n}\n\n// Convert IncomingStreamQuery to BackendIncomingStreamFilterOptions\nfunction convertToIncomingBackendQuery(query?: IncomingStreamQuery): BackendIncomingStreamFilterOptions {\n return {\n status: convertStreamStatus(query?.status),\n coinType: normalizeCoinTypeFilter(query?.coinType),\n sender: normalizeAddressFilter(query?.sender),\n };\n}\n\nfunction convertToOutgoingBackendQuery(query?: OutgoingStreamQuery): BackendOutgoingStreamFilterOptions {\n return {\n status: convertStreamStatus(query?.status),\n coinType: normalizeCoinTypeFilter(query?.coinType),\n recipient: normalizeAddressFilter(query?.recipient),\n };\n}\n\nexport function convertStreamStatus(status: undefined | StreamStatus | StreamStatus[]): StreamFilterStatus {\n if (status === undefined || status.length === 0) {\n return 'all';\n }\n if (!Array.isArray(status)) {\n return convertStreamStatusSingle(status);\n }\n return status.reduce((res: StreamFilterStatus | undefined, st) => {\n const sts = convertStreamStatus(st);\n if (!res) {\n return sts;\n }\n if (res === sts) {\n return sts;\n }\n return 'all';\n }, undefined) as StreamFilterStatus;\n}\n\nfunction convertStreamStatusSingle(status: StreamStatus): StreamFilterStatus {\n switch (status) {\n case 'STREAMING':\n case 'STREAMED':\n case 'CANCELED':\n return 'active';\n case 'COMPLETED':\n case 'SETTLED':\n return 'inactive';\n default:\n throw new InvalidInputError('Unknown stream filtered status');\n }\n}\n\nfunction normalizeCoinTypeFilter(coinType: string | string[] | undefined) {\n if (!coinType) {\n return undefined;\n }\n if (!Array.isArray(coinType)) {\n return normalizeStructTag(coinType);\n }\n return coinType.length !== 0 ? coinType.map((ct) => normalizeStructTag(ct)) : undefined;\n}\n\nfunction normalizeAddressFilter(address: string | string[] | undefined) {\n if (!address) {\n return undefined;\n }\n if (!Array.isArray(address)) {\n return normalizeSuiAddress(address);\n }\n return address.length !== 0 ? address.map((addr) => normalizeSuiAddress(addr)) : undefined;\n}\n","import { MPayError, JsonObject, MPayErrorCode } from './base';\n\nexport class InvalidStreamGroupError extends MPayError {\n constructor(msg: string, context?: JsonObject) {\n super(MPayErrorCode.InvalidStreamGroup, `Invalid stream group: ${msg}`, { context });\n }\n}\n","import { SuiClient, SuiObjectDataOptions, SuiObjectResponse } from '@mysten/sui.js/client';\n\nimport { SuiIterator, getAllFromIterator, EntryIterator } from './iterator';\nimport { Requester, PagedData } from './requester';\n\nexport type ObjectFilter = (objRes: SuiObjectResponse) => boolean;\n\nexport const REQUEST_PAGE_SIZE = 25;\n\n// OidIter is the iterator to give the list of object ids\nexport type OidIter = SuiIterator<string>;\nexport interface BatchObjectOptions {\n filter?: ObjectFilter;\n pageSize?: number;\n objectOptions?: SuiObjectDataOptions;\n}\n\n// getObjectsById get the list of objects by id.\n// Compared with the multiGetObject method defined by SUI, this method will do the pagination\n// for get object requests.\nexport async function getObjectsById(\n suiClient: SuiClient,\n ids: string[],\n options?: BatchObjectOptions,\n): Promise<(SuiObjectResponse | undefined)[]> {\n const oidIter = new ListOidIterator(ids);\n const iter = new ObjectBatchIterator(suiClient, oidIter, options);\n return (await getAllFromIterator(iter)) as SuiObjectResponse[];\n}\n\n// ListOidIterator is the iterator that iterate through a list of ids.\n// This iterator shall be used when the number requested objects is big\n// which is inappropriate to fit the requested objects into a single\n// request.\nexport class ListOidIterator implements OidIter {\n cursor: number;\n\n constructor(public readonly ids: string[]) {\n this.cursor = -1;\n }\n\n async hasNext(): Promise<boolean> {\n return this.cursor < this.ids.length - 1;\n }\n\n async next(): Promise<string> {\n this.cursor += 1;\n if (this.cursor >= this.ids.length) {\n throw new Error('invalid iterator implementation'); // Shall be unreachable\n }\n return this.ids[this.cursor];\n }\n}\n\nexport class ObjectBatchIterator extends EntryIterator<SuiObjectResponse> {\n constructor(\n public readonly suiClient: SuiClient,\n public readonly idIter: OidIter,\n public readonly options?: BatchObjectOptions,\n ) {\n super(new ObjectBatchRequester(suiClient, idIter, options));\n }\n}\n\n// TODO: Unit test this class\nexport class ObjectBatchRequester implements Requester<SuiObjectResponse> {\n filter: ObjectFilter | undefined;\n\n pageSize: number;\n\n objectOptions: SuiObjectDataOptions;\n\n constructor(\n public readonly suiClient: SuiClient,\n public readonly stringIter: OidIter,\n public options?: BatchObjectOptions,\n ) {\n this.filter = options?.filter;\n this.pageSize = options?.pageSize || REQUEST_PAGE_SIZE;\n this.objectOptions = options?.objectOptions || {\n showType: true,\n showContent: true,\n };\n }\n\n async doNextRequest(): Promise<PagedData<SuiObjectResponse>> {\n const requestPage: string[] = [];\n while (requestPage.length < this.pageSize) {\n const hasNext = await this.stringIter.hasNext();\n if (!hasNext) {\n break;\n }\n const objId = await this.stringIter.next();\n if (objId) {\n requestPage.push(objId);\n }\n }\n const res = await this.suiClient.multiGetObjects({\n ids: requestPage,\n options: this.objectOptions,\n });\n let filtered: SuiObjectResponse[];\n if (this.filter) {\n const { filter } = this;\n filtered = res.filter((r: SuiObjectResponse) => filter?.(r));\n } else {\n filtered = res;\n }\n return {\n data: filtered,\n hasNext: await this.stringIter.hasNext(),\n };\n }\n}\n","import { SuiObjectResponse } from '@mysten/sui.js/client';\n\nimport { Stream } from './Stream';\nimport { Globals } from '../common';\nimport { InvalidInputError } from '../error/InvalidInputError';\nimport { InvalidStreamGroupError } from '../error/InvalidStreamGroupError';\nimport { SanityError } from '../error/SanityError';\nimport { getObjectsById } from '../sui/iterator/object';\nimport { StreamEvent } from '../types/events';\nimport { PaginationOptions, Paginated } from '../types/pagination';\nimport { IStreamGroup, StreamGroupInfo, StreamGroupProgress, StreamGroupCommonInfo } from '../types/stream';\n\nexport class StreamGroup implements IStreamGroup {\n public readonly type = 'StreamGroup';\n\n constructor(\n public readonly globals: Globals,\n public readonly streams: Stream[],\n ) {\n if (streams.length === 0) {\n throw new InvalidStreamGroupError('stream size 0');\n }\n const gids = streams.map((st) => st.groupId);\n const set = new Set(gids);\n if (set.size !== 1) {\n throw new InvalidInputError('Stream does not have same group ID');\n }\n }\n\n static async new(globals: Globals, ids: string[]) {\n const streamObjs = await getObjectsById(globals.suiClient, ids);\n streamObjs.forEach((obj) => {\n if (!obj) {\n throw new SanityError('stream group object data undefined');\n }\n });\n return StreamGroup.newFromObjectResponse(globals, ids, streamObjs as SuiObjectResponse[]);\n }\n\n static async newFromObjectResponse(globals: Globals, ids: string[], responses: SuiObjectResponse[]) {\n const streams = await StreamGroup.parseGroupStreams(globals, ids, responses);\n return new StreamGroup(globals, streams);\n }\n\n static checkStreamGroup(streams: Stream[]) {\n const commonInfos = streams.map((stream) => stream.groupCommonInfo);\n const expInfo = commonInfos[0];\n let isEqual = true;\n commonInfos.forEach((info) => {\n if (!isEqualStreamGroupCommonInfo(expInfo, info)) {\n isEqual = false;\n }\n });\n return isEqual;\n }\n\n async refresh() {\n const streamObjs = await getObjectsById(\n this.globals.suiClient,\n this.streams.map((stream) => stream.streamId),\n );\n this.streams.forEach((stream, i) => {\n stream.refreshWithData(streamObjs[i] as SuiObjectResponse);\n });\n }\n\n get groupId() {\n return this.streams[0].groupId;\n }\n\n get creator() {\n return this.streams[0].creator;\n }\n\n get info(): StreamGroupInfo {\n return {\n groupId: this.groupId,\n streamIds: this.streams.map((st) => st.streamId),\n progress: this.progress,\n\n name: this.streams[0].name,\n creator: this.creator,\n coinType: this.streams[0].coinType,\n totalAmount: this.streams.reduce((sum, st) => sum + st.totalAmount, 0n),\n start: this.streams[0].timeStart,\n end: this.streams[0].timeEnd,\n cancelable: this.streams[0].cancelable,\n cliffAmount: this.streams.reduce((sum, st) => sum + st.cliff, 0n),\n duration: this.streams[0].duration,\n interval: this.streams[0].interval,\n steps: this.streams[0].totalSteps,\n nextReleaseAmount: this.streams.reduce((sum, st) => {\n if (st.nextReleaseAmount === null) {\n return sum;\n }\n return sum + st.nextReleaseAmount;\n }, 0n),\n nextReleaseDate: this.streams[0].nextReleaseDate,\n };\n }\n\n get progress(): StreamGroupProgress {\n return {\n total: this.streams.reduce((sum, st) => sum + st.totalAmount, 0n),\n streamed: this.streams.reduce((sum, st) => sum + st.streamedAmount, 0n),\n claimed: this.streams.reduce((sum, st) => sum + st.claimedAmount, 0n),\n claimable: this.streams.reduce((sum, st) => sum + st.claimable, 0n),\n canceled: this.streams.reduce((sum, st) => sum + st.canceledAmount, 0n),\n };\n }\n\n async historyEvents(pagination?: PaginationOptions): Promise<Paginated<StreamEvent>> {\n return this.globals.backend.getStreamHistory({\n groupId: this.groupId,\n pagination,\n });\n }\n\n private static async parseGroupStreams(globals: Globals, ids: string[], responses: SuiObjectResponse[]) {\n const streams = responses\n .map((obj, i) => Stream.fromObjectData(globals, ids[i], obj))\n .filter((stream) => !!stream) as Stream[];\n\n if (new Set(streams.map((st) => st.groupId)).size !== 1) {\n throw new InvalidStreamGroupError('Not same group ID');\n }\n if (!this.checkStreamGroup(streams)) {\n throw new InvalidStreamGroupError('Not same stream settings');\n }\n return streams;\n }\n}\n\nfunction isEqualStreamGroupCommonInfo(info1: StreamGroupCommonInfo, info2: StreamGroupCommonInfo): boolean {\n return (\n info1.name === info2.name &&\n info1.groupId === info2.groupId &&\n info1.creator === info2.creator &&\n info1.start.toMillis() === info2.start.toMillis() &&\n info1.interval.toMillis() === info2.interval.toMillis() &&\n info1.steps === info2.steps &&\n info1.cancelable === info2.cancelable\n );\n}\n","import { WalletAccount } from '@mysten/wallet-standard';\n\nimport { BaseIntentionLegacy } from '@/apps/interface/sui-js';\nimport { SuiNetworks } from '@/types';\n\nimport { Env } from './common';\nimport { MPayClient, MSafeSingleWallet } from './stream/client';\n\nexport abstract class StreamIntention<T> extends BaseIntentionLegacy<T> {\n public application = 'mpay';\n\n getClient(network: SuiNetworks, account: WalletAccount): MPayClient {\n const mpayClient = new MPayClient(network === 'sui:mainnet' ? Env.prod : Env.dev);\n mpayClient.connectSingleWallet(new MSafeSingleWallet(account));\n return mpayClient;\n }\n}\n","import { ClaimByProxyStreamIntentionData, TransactionType } from '@msafe/sui3-utils';\nimport { SuiClient } from '@mysten/sui.js/client';\nimport { TransactionBlock } from '@mysten/sui.js/transactions';\nimport { WalletAccount } from '@mysten/wallet-standard';\n\nimport { SuiNetworks } from '@/types';\n\nimport { StreamIntention } from './intention';\nimport { StreamTransactionType } from './types/decode';\n\nexport class ClaimByProxyStreamIntention extends StreamIntention<ClaimByProxyStreamIntentionData> {\n txType = TransactionType.Stream;\n\n txSubType = StreamTransactionType.CLAIM_BY_PROXY;\n\n constructor(public readonly data: ClaimByProxyStreamIntentionData) {\n super(data);\n }\n\n async build(input: {\n network: SuiNetworks;\n suiClient: SuiClient;\n account: WalletAccount;\n }): Promise<TransactionBlock> {\n const { network, account } = input;\n const mpayClient = this.getClient(network, account);\n const stream = await mpayClient.getStream(this.data.streamId);\n return stream.claimByProxy();\n }\n}\n","import { ClaimStreamIntentionData, TransactionType } from '@msafe/sui3-utils';\nimport { SuiClient } from '@mysten/sui.js/client';\nimport { TransactionBlock } from '@mysten/sui.js/transactions';\nimport { WalletAccount } from '@mysten/wallet-standard';\n\nimport { SuiNetworks } from '@/types';\n\nimport { StreamIntention } from './intention';\nimport { StreamTransactionType } from './types/decode';\n\nexport class ClaimStreamIntention extends StreamIntention<ClaimStreamIntentionData> {\n txType = TransactionType.Stream;\n\n txSubType = StreamTransactionType.CLAIM;\n\n constructor(public readonly data: ClaimStreamIntentionData) {\n super(data);\n }\n\n async build(input: {\n network: SuiNetworks;\n suiClient: SuiClient;\n account: WalletAccount;\n }): Promise<TransactionBlock> {\n const { network, account } = input;\n const mpayClient = this.getClient(network, account);\n const stream = await mpayClient.getStream(this.data.streamId);\n return stream.claim();\n }\n}\n","import { CreateStreamIntentionData, TransactionType } from '@msafe/sui3-utils';\nimport { SuiClient } from '@mysten/sui.js/client';\nimport { TransactionBlock } from '@mysten/sui.js/transactions';\nimport { WalletAccount } from '@mysten/wallet-standard';\n\nimport { SuiNetworks } from '@/types';\n\nimport { StreamIntention } from './intention';\nimport { StreamTransactionType } from './types/decode';\n\nexport class CreateStreamIntention extends StreamIntention<CreateStreamIntentionData> {\n txType = TransactionType.Stream;\n\n txSubType = StreamTransactionType.CREATE_STREAM;\n\n constructor(public readonly data: CreateStreamIntentionData) {\n super(data);\n }\n\n async build(input: {\n network: SuiNetworks;\n suiClient: SuiClient;\n account: WalletAccount;\n }): Promise<TransactionBlock> {\n const { network, account } = input;\n const mpayClient = this.getClient(network, account);\n return mpayClient.createStream(this.data);\n }\n}\n","// Helper class to decode move call\nimport { bcs } from '@mysten/sui.js/bcs';\nimport { MoveCallTransaction } from '@mysten/sui.js/dist/cjs/transactions';\nimport { TransactionBlock, TransactionBlockInput } from '@mysten/sui.js/transactions';\nimport { normalizeStructTag, normalizeSuiAddress } from '@mysten/sui.js/utils';\n\nexport class MoveCallHelper {\n constructor(\n public readonly moveCall: MoveCallTransaction,\n public readonly txb: TransactionBlock,\n ) {}\n\n decodeSharedObjectId(argIndex: number) {\n const input = this.getInputParam(argIndex);\n return MoveCallHelper.getSharedObjectId(input);\n }\n\n decodeOwnedObjectId(argIndex: number) {\n const input = this.getInputParam(argIndex);\n return MoveCallHelper.getOwnedObjectId(input);\n }\n\n decodeInputU64(argIndex: number) {\n const strVal = this.decodePureArg<string>(argIndex, 'u64');\n return BigInt(strVal);\n }\n\n decodeInputAddress(argIndex: number) {\n const input = this.decodePureArg<string>(argIndex, 'address');\n return normalizeSuiAddress(input);\n }\n\n decodeInputString(argIndex: number) {\n return this.decodePureArg<string>(argIndex, 'string');\n }\n\n decodeInputBool(argIndex: number) {\n return this.decodePureArg<boolean>(argIndex, 'bool');\n }\n\n decodePureArg<T>(argIndex: number, bcsType: string) {\n const input = this.getInputParam(argIndex);\n return MoveCallHelper.getPureInputValue<T>(input, bcsType);\n }\n\n getInputParam(argIndex: number) {\n const arg = this.moveCall.arguments[argIndex];\n if (arg.kind !== 'Input') {\n throw new Error('not input type');\n }\n return this.txb.blockData.inputs[arg.index];\n }\n\n static getPureInputValue<T>(input: TransactionBlockInput, bcsType: string) {\n if (input.type !== 'pure') {\n throw new Error('not pure argument');\n }\n if (typeof input.value === 'object' && 'Pure' in input.value) {\n const bcsNums = input.value.Pure;\n return bcs.de(bcsType, new Uint8Array(bcsNums)) as T;\n }\n return input.value as T;\n }\n\n static getOwnedObjectId(input: TransactionBlockInput) {\n if (input.type !== 'object') {\n throw new Error(`not object argument: ${JSON.stringify(input)}`);\n }\n if (typeof input.value === 'object') {\n if (!('Object' in input.value) || !('ImmOrOwned' in input.value.Object)) {\n throw new Error('not ImmOrOwned');\n }\n return normalizeSuiAddress(input.value.Object.ImmOrOwned.objectId as string);\n }\n return normalizeSuiAddress(input.value as string);\n }\n\n static getSharedObjectId(input: TransactionBlockInput) {\n if (input.type !== 'object') {\n throw new Error(`not object argument: ${JSON.stringify(input)}`);\n }\n if (typeof input.value !== 'object') {\n return normalizeSuiAddress(input.value as string);\n }\n if (!('Object' in input.value) || !('Shared' in input.value.Object)) {\n throw new Error('not Shared');\n }\n return normalizeSuiAddress(input.value.Object.Shared.objectId as string);\n }\n\n static getPureInput<T>(input: TransactionBlockInput, bcsType: string) {\n if (input.type !== 'pure') {\n throw new Error('not pure argument');\n }\n if (typeof input.value !== 'object') {\n return input.value as T;\n }\n if (!('Pure' in input.value)) {\n throw new Error('Pure not in value');\n }\n const bcsVal = input.value.Pure;\n return bcs.de(bcsType, new Uint8Array(bcsVal)) as T;\n }\n\n typeArg(index: number) {\n return normalizeStructTag(this.moveCall.typeArguments[index]);\n }\n\n txArg(index: number) {\n return this.moveCall.arguments[index];\n }\n}\n","import { MoveCallTransaction } from '@mysten/sui.js/dist/cjs/transactions';\nimport { TransactionArgument, TransactionBlock } from '@mysten/sui.js/transactions';\n\nimport { CreateStreamHelper } from '../builder/CreateStreamHelper';\nimport { Globals } from '../common';\nimport { FeeContract } from '../contract/FeeContract';\nimport { StreamContract } from '../contract/StreamContract';\nimport { InvalidInputError } from '../error/InvalidInputError';\nimport { SanityError } from '../error/SanityError';\nimport { decodeMetadata } from '../stream/metadata';\nimport { isSameTarget } from '../sui/utils';\nimport { CreateStreamInfo, RecipientWithAmount } from '../types/client';\nimport { DecodedCreateStream, StreamTransactionType } from '../types/decode';\nimport { MoveCallHelper } from './moveCall';\n\nexport class CreateStreamDecodeHelper {\n constructor(\n public readonly globals: Globals,\n public readonly txb: TransactionBlock,\n ) {}\n\n decode(): DecodedCreateStream {\n const streamInfo = this.decodeCreateStreamInfo();\n const fees = this.createStreamHelper().calculateCreateStreamFees(streamInfo);\n return {\n type: StreamTransactionType.CREATE_STREAM,\n info: streamInfo,\n fees,\n };\n }\n\n private decodeCreateStreamInfo(): CreateStreamInfo {\n const moveCalls = this.createStreamTransactions();\n const infos = moveCalls.map((moveCall) => this.getCreationInfoFromMoveCall(moveCall));\n return this.aggregateGroupStreamInfo(infos);\n }\n\n private createStreamTransactions(): MoveCallHelper[] {\n const txs = this.transactions.filter(\n (tx) => tx.kind === 'MoveCall' && isSameTarget(tx.target, this.contract.createStreamTarget),\n ) as MoveCallTransaction[];\n if (txs.length === 0) {\n throw new SanityError('No create stream transactions');\n }\n return txs.map((tx) => new MoveCallHelper(tx, this.txb));\n }\n\n private getCreationInfoFromMoveCall(moveCall: MoveCallHelper): SingleStreamCreationInfo {\n const metadata = moveCall.decodeInputString(4);\n const { name, groupId } = decodeMetadata(metadata);\n\n const recipient = moveCall.decodeInputAddress(5);\n const timeStart = moveCall.decodeInputU64(6);\n const cliff = moveCall.decodeInputU64(7);\n const epochInterval = moveCall.decodeInputU64(8);\n const totalEpoch = moveCall.decodeInputU64(9);\n const amountPerEpoch = moveCall.decodeInputU64(10);\n const cancelable = moveCall.decodeInputBool(11);\n const coinType = moveCall.typeArg(0);\n\n return {\n name,\n groupId,\n recipient,\n timeStart,\n cliff,\n epochInterval,\n totalEpoch,\n amountPerEpoch,\n cancelable,\n coinType,\n };\n }\n\n private aggregateGroupStreamInfo(infos: SingleStreamCreationInfo[]): CreateStreamInfo {\n const commonInfoSet = new Set(\n infos.map((info) =>\n JSON.stringify({\n name: info.name,\n groupId: info.groupId,\n timeStart: String(info.timeStart),\n epochInterval: String(info.epochInterval),\n totalEpoch: String(info.totalEpoch),\n cancelable: info.cancelable,\n coinType: info.coinType,\n }),\n ),\n );\n if (commonInfoSet.size !== 1) {\n throw new InvalidInputError('Stream group not have common info');\n }\n const recipients: RecipientWithAmount[] = infos.map((info) => ({\n address: info.recipient,\n amountPerStep: info.amountPerEpoch,\n cliffAmount: info.cliff,\n }));\n return {\n name: infos[0].name,\n coinType: infos[0].coinType,\n recipients,\n interval: infos[0].epochInterval,\n steps: infos[0].totalEpoch,\n startTimeMs: infos[0].timeStart,\n cancelable: infos[0].cancelable,\n };\n }\n\n private mergeCoinTransactions() {\n return this.transactions.filter((tx) => tx.kind === 'MergeCoins');\n }\n\n private get transactions() {\n return this.txb.blockData.transactions;\n }\n\n private get contract() {\n return new StreamContract(this.globals.envConfig.contract, this.globals);\n }\n\n private get feeContract() {\n return new FeeContract(this.globals.envConfig.contract, this.globals);\n }\n\n private createStreamHelper() {\n return new CreateStreamHelper(this.globals, this.feeContract, this.contract);\n }\n\n private getInputArg(arg: TransactionArgument) {\n if (arg.kind !== 'Input') {\n throw new Error('not input type');\n }\n return 'value' in arg ? arg : this.txb.blockData.inputs[arg.index];\n }\n}\n\ninterface SingleStreamCreationInfo {\n name: string;\n groupId: string;\n recipient: string;\n timeStart: bigint;\n cliff: bigint;\n epochInterval: bigint;\n totalEpoch: bigint;\n amountPerEpoch: bigint;\n cancelable: boolean;\n coinType: string;\n}\n","import { MoveCallTransaction } from '@mysten/sui.js/dist/cjs/transactions';\nimport { TransactionBlock } from '@mysten/sui.js/transactions';\n\nimport { CreateStreamDecodeHelper } from './create';\nimport { MoveCallHelper } from './moveCall';\nimport { Globals } from '../common';\nimport { StreamContract } from '../contract/StreamContract';\nimport { isSameTarget } from '../sui/utils';\nimport {\n DecodedCancelStream,\n DecodedClaimByProxy,\n DecodedClaimStream,\n DecodedCreateStream,\n DecodedSetAutoClaim,\n StreamDecodedTransaction,\n StreamTransactionType,\n} from '../types/decode';\n\nexport class StreamTransactionDecoder {\n static decodeTransaction(globals: Globals, txb: TransactionBlock): StreamDecodedTransaction {\n const helper = new DecodeHelper(globals, txb);\n return helper.decode();\n }\n}\n\nexport class DecodeHelper {\n private readonly contract: StreamContract;\n\n constructor(\n public readonly globals: Globals,\n public readonly txb: TransactionBlock,\n ) {\n this.contract = new StreamContract(globals.envConfig.contract, globals);\n }\n\n decode(): StreamDecodedTransaction {\n if (this.isCreateStreamTransaction()) {\n return this.decodeCreateStreamTransaction();\n }\n if (this.isClaimByProxyTransaction()) {\n return this.decodeClaimByProxyTransaction();\n }\n if (this.isSetAutoClaimTransaction()) {\n return this.decodeSetAutoClaimTransaction();\n }\n if (this.isCancelStreamTransaction()) {\n return this.decodeCancelStreamTransaction();\n }\n if (this.isClaimStreamTransaction()) {\n return this.decodeClaimTransaction();\n }\n throw new Error('Unknown stream transaction type');\n }\n\n private get transactions() {\n return this.txb.blockData.transactions;\n }\n\n private isCreateStreamTransaction() {\n const createStreamIndex = this.transactions.findIndex(\n (tx) => tx.kind === 'MoveCall' && isSameTarget(tx.target, this.contract.createStreamTarget),\n );\n return createStreamIndex !== -1;\n }\n\n private isSetAutoClaimTransaction() {\n return (\n this.transactions.length === 1 &&\n this.transactions[0].kind === 'MoveCall' &&\n isSameTarget(this.transactions[0].target, this.contract.setAutoClaimTarget)\n );\n }\n\n private isCancelStreamTransaction() {\n return (\n this.transactions.length === 1 &&\n this.transactions[0].kind === 'MoveCall' &&\n isSameTarget(this.transactions[0].target, this.contract.cancelStreamTarget)\n );\n }\n\n private isClaimStreamTransaction(): boolean {\n return (\n this.transactions.length === 1 &&\n this.transactions[0].kind === 'MoveCall' &&\n isSameTarget(this.transactions[0].target, this.contract.claimStreamTarget)\n );\n }\n\n private isClaimByProxyTransaction(): boolean {\n return (\n this.transactions.length === 1 &&\n this.transactions[0].kind === 'MoveCall' &&\n isSameTarget(this.transactions[0].target, this.contract.claimStreamByProxyTarget)\n );\n }\n\n private decodeCreateStreamTransaction(): DecodedCreateStream {\n const helper = new CreateStreamDecodeHelper(this.globals, this.txb);\n return helper.decode();\n }\n\n private decodeSetAutoClaimTransaction(): DecodedSetAutoClaim {\n const streamId = this.helper.decodeSharedObjectId(0);\n const enabled = this.helper.decodeInputBool(1);\n return {\n type: StreamTransactionType.SET_AUTO_CLAIM,\n streamId,\n enabled,\n };\n }\n\n private decodeClaimTransaction(): DecodedClaimStream {\n const streamId = this.helper.decodeSharedObjectId(0);\n return {\n type: StreamTransactionType.CLAIM,\n streamId,\n };\n }\n\n private decodeClaimByProxyTransaction(): DecodedClaimByProxy {\n const streamId = this.helper.decodeSharedObjectId(0);\n return {\n type: StreamTransactionType.CLAIM_BY_PROXY,\n streamId,\n };\n }\n\n private decodeCancelStreamTransaction(): DecodedCancelStream {\n const streamId = this.helper.decodeSharedObjectId(0);\n return {\n type: StreamTransactionType.CANCEL,\n streamId,\n };\n }\n\n private get helper() {\n const moveCall = this.transactions[0] as MoveCallTransaction;\n return new MoveCallHelper(moveCall, this.txb);\n }\n}\n","import { SetAutoClaimIntentionData, TransactionType } from '@msafe/sui3-utils';\nimport { SuiClient } from '@mysten/sui.js/client';\nimport { TransactionBlock } from '@mysten/sui.js/transactions';\nimport { WalletAccount } from '@mysten/wallet-standard';\n\nimport { SuiNetworks } from '@/types';\n\nimport { StreamIntention } from './intention';\nimport { StreamTransactionType } from './types/decode';\n\nexport class SetAutoClaimStreamIntention extends StreamIntention<SetAutoClaimIntentionData> {\n txType = TransactionType.Stream;\n\n txSubType = StreamTransactionType.SET_AUTO_CLAIM;\n\n constructor(public readonly data: SetAutoClaimIntentionData) {\n super(data);\n }\n\n async build(input: {\n network: SuiNetworks;\n suiClient: SuiClient;\n account: WalletAccount;\n }): Promise<TransactionBlock> {\n const { network, account } = input;\n const mpayClient = this.getClient(network, account);\n const stream = await mpayClient.getStream(this.data.streamId);\n return stream.setAutoClaim(this.data.enabled);\n }\n}\n","import {\n CancelStreamIntentionData,\n ClaimByProxyStreamIntentionData,\n ClaimStreamIntentionData,\n CreateStreamIntentionData,\n SetAutoClaimIntentionData,\n TransactionType,\n} from '@msafe/sui3-utils';\nimport { SuiClient } from '@mysten/sui.js/client';\nimport { TransactionBlock } from '@mysten/sui.js/transactions';\nimport { SuiSignTransactionBlockInput, WalletAccount } from '@mysten/wallet-standard';\n\nimport { IAppHelperInternalLegacy } from '@/apps/interface/sui-js';\nimport { SuiNetworks } from '@/types';\n\nimport { CancelStreamIntention } from './cancel-stream';\nimport { ClaimByProxyStreamIntention } from './claim-by-proxy-stream';\nimport { ClaimStreamIntention } from './claim-stream';\nimport { Env, Globals } from './common';\nimport { CreateStreamIntention } from './create-stream';\nimport { DecodeHelper } from './decoder/decoder';\nimport { SetAutoClaimStreamIntention } from './set-auto-claim-stream';\nimport { StreamTransactionType } from './types/decode';\n\nexport type MPayIntention =\n | CreateStreamIntention\n | SetAutoClaimStreamIntention\n | ClaimStreamIntention\n | CancelStreamIntention\n | ClaimByProxyStreamIntention;\n\nexport type MPayIntentionData =\n | CreateStreamIntentionData\n | SetAutoClaimIntentionData\n | ClaimStreamIntentionData\n | ClaimByProxyStreamIntentionData\n | CancelStreamIntentionData;\n\nexport class MPayAppHelper implements IAppHelperInternalLegacy<MPayIntentionData> {\n application = 'mpay';\n\n supportSDK = '@mysten/sui.js' as const;\n\n async deserialize(\n input: SuiSignTransactionBlockInput & { network: SuiNetworks; suiClient: SuiClient; account: WalletAccount },\n ): Promise<{ txType: TransactionType; txSubType: string; intentionData: MPayIntentionData }> {\n const { network, transactionBlock } = input;\n const globals = Globals.new(network === 'sui:mainnet' ? Env.prod : Env.dev);\n const decoder = new DecodeHelper(globals, transactionBlock);\n const result = decoder.decode();\n\n let intention: MPayIntention;\n\n switch (result.type) {\n case StreamTransactionType.CREATE_STREAM:\n intention = new CreateStreamIntention(result.info);\n break;\n case StreamTransactionType.SET_AUTO_CLAIM:\n intention = new SetAutoClaimStreamIntention({ streamId: result.streamId, enabled: result.enabled });\n break;\n case StreamTransactionType.CLAIM:\n intention = new ClaimStreamIntention({ streamId: result.streamId });\n break;\n case StreamTransactionType.CLAIM_BY_PROXY:\n intention = new ClaimByProxyStreamIntention({ streamId: result.streamId });\n break;\n case StreamTransactionType.CANCEL:\n intention = new CancelStreamIntention({ streamId: result.streamId });\n break;\n default:\n throw new Error(`Unknown transaction type: ${result}`);\n }\n\n return {\n txType: intention.txType,\n txSubType: intention.txSubType,\n intentionData: intention.data,\n };\n }\n\n async build(input: {\n intentionData: MPayIntentionData;\n txType: TransactionType;\n txSubType: string;\n suiClient: SuiClient;\n account: WalletAccount;\n network: SuiNetworks;\n }): Promise<TransactionBlock> {\n const { intentionData } = input;\n let intention: MPayIntention;\n switch (input.txSubType as StreamTransactionType) {\n case StreamTransactionType.CREATE_STREAM:\n intention = new CreateStreamIntention(intentionData as CreateStreamIntentionData);\n break;\n case StreamTransactionType.CLAIM:\n intention = new ClaimStreamIntention(intentionData as ClaimStreamIntentionData);\n break;\n case StreamTransactionType.CLAIM_BY_PROXY:\n intention = new ClaimByProxyStreamIntention(intentionData as ClaimByProxyStreamIntentionData);\n break;\n case StreamTransactionType.SET_AUTO_CLAIM:\n intention = new SetAutoClaimStreamIntention(intentionData as SetAutoClaimIntentionData);\n break;\n case StreamTransactionType.CANCEL:\n intention = new CancelStreamIntention(intentionData as CancelStreamIntentionData);\n break;\n default:\n throw new Error('not implemented');\n }\n return intention.build({ ...input });\n }\n}\n","import { TransactionDefaultApplication, TransactionSubTypes, TransactionType } from '@msafe/sui3-utils';\nimport { SuiClient } from '@mysten/sui.js/client';\nimport { TransactionBlock } from '@mysten/sui.js/transactions';\nimport { WalletAccount } from '@mysten/wallet-standard';\n\nimport { IAppHelperInternalLegacy } from '@/apps/interface/sui-js';\nimport { CoinTransferIntention, CoinTransferIntentionData } from '@/apps/msafe-core/coin-transfer';\n\nimport { ObjectTransferIntention, ObjectTransferIntentionData } from './object-transfer';\nimport { PlainPayloadIntention, PlainPayloadIntentionData } from './plain-payload';\n\nexport type CoreIntention = CoinTransferIntention | ObjectTransferIntention | PlainPayloadIntention;\n\nexport type CoreIntentionData = CoinTransferIntentionData | ObjectTransferIntentionData | PlainPayloadIntentionData;\n\nexport class CoreHelper implements IAppHelperInternalLegacy<CoreIntentionData> {\n application = 'msafe-core';\n\n supportSDK = '@mysten/sui.js' as const;\n\n constructor() {\n this.application = TransactionDefaultApplication;\n }\n\n deserialize(): Promise<{ txType: TransactionType; txSubType: string; intentionData: CoreIntentionData }> {\n throw new Error('MSafe core transaction intention should be build from API');\n }\n\n async build(input: {\n intentionData: CoreIntentionData;\n txType: TransactionType;\n txSubType: string;\n suiClient: SuiClient;\n account: WalletAccount;\n }): Promise<TransactionBlock> {\n const { suiClient, account } = input;\n let intention: CoreIntention;\n switch (input.txSubType) {\n case TransactionSubTypes.assets.coin.send:\n intention = CoinTransferIntention.fromData(input.intentionData as CoinTransferIntentionData);\n break;\n case TransactionSubTypes.assets.object.send:\n intention = ObjectTransferIntention.fromData(input.intentionData as ObjectTransferIntentionData);\n break;\n case TransactionSubTypes.others.plain:\n intention = PlainPayloadIntention.fromData(input.intentionData as PlainPayloadIntentionData);\n break;\n default:\n throw new Error('not implemented');\n }\n return intention.build({ suiClient, account });\n }\n}\n","import { TransactionType, buildCoinTransferTxb } from '@msafe/sui3-utils';\nimport { SuiClient } from '@mysten/sui.js/client';\nimport { TransactionBlock } from '@mysten/sui.js/transactions';\nimport { WalletAccount } from '@mysten/wallet-standard';\n\nimport { BaseIntentionLegacy } from '@/apps/interface/sui-js';\n\nexport interface CoinTransferIntentionData {\n recipient: string;\n coinType: string;\n amount: string;\n}\n\nexport class CoinTransferIntention extends BaseIntentionLegacy<CoinTransferIntentionData> {\n txType: TransactionType.Assets;\n\n txSubType: 'SendCoin';\n\n constructor(public readonly data: CoinTransferIntentionData) {\n super(data);\n }\n\n async build(input: { suiClient: SuiClient; account: WalletAccount }): Promise<TransactionBlock> {\n const { suiClient, account } = input;\n return buildCoinTransferTxb(suiClient, this.data, account.address);\n }\n\n static fromData(data: CoinTransferIntentionData) {\n return new CoinTransferIntention(data);\n }\n}\n","import { TransactionType, buildObjectTransferTxb } from '@msafe/sui3-utils';\nimport { SuiClient } from '@mysten/sui.js/client';\nimport { TransactionBlock } from '@mysten/sui.js/transactions';\nimport { WalletAccount } from '@mysten/wallet-standard';\n\nimport { BaseIntentionLegacy } from '@/apps/interface/sui-js';\n\nexport interface ObjectTransferIntentionData {\n receiver: string;\n objectType: string;\n objectId: string;\n}\n\nexport class ObjectTransferIntention extends BaseIntentionLegacy<ObjectTransferIntentionData> {\n txType: TransactionType.Assets;\n\n txSubType: 'SendObject';\n\n constructor(public readonly data: ObjectTransferIntentionData) {\n super(data);\n }\n\n async build(input: { suiClient: SuiClient; account: WalletAccount }): Promise<TransactionBlock> {\n const { suiClient, account } = input;\n return buildObjectTransferTxb(suiClient, this.data, account.address);\n }\n\n static fromData(data: ObjectTransferIntentionData) {\n return new ObjectTransferIntention(data);\n }\n}\n","import { TransactionType, isSameAddress } from '@msafe/sui3-utils';\nimport { SuiClient } from '@mysten/sui.js/client';\nimport { TransactionBlock } from '@mysten/sui.js/transactions';\nimport { WalletAccount } from '@mysten/wallet-standard';\n\nimport { BaseIntentionLegacy } from '@/apps/interface/sui-js';\n\nexport interface PlainPayloadIntentionData {\n content: string;\n}\n\nexport class PlainPayloadIntention extends BaseIntentionLegacy<PlainPayloadIntentionData> {\n txType: TransactionType.Other;\n\n txSubType: 'PlainPayload';\n\n constructor(public readonly data: PlainPayloadIntentionData) {\n super(data);\n }\n\n async build(input: { suiClient: SuiClient; account: WalletAccount }): Promise<TransactionBlock> {\n const { account } = input;\n const tb = TransactionBlock.from(this.data.content);\n\n if (!isSameAddress(tb.blockData.sender, account.address)) {\n throw new Error('Invalid sender address');\n }\n\n return tb;\n }\n\n static fromData(data: PlainPayloadIntentionData) {\n return new PlainPayloadIntention(data);\n }\n}\n","import { TransactionType } from '@msafe/sui3-utils';\nimport { SuiClient } from '@mysten/sui.js/client';\nimport { TransactionBlock } from '@mysten/sui.js/transactions';\nimport { WalletAccount, SuiSignTransactionBlockInput } from '@mysten/wallet-standard';\n\nimport { IAppHelperInternalLegacy } from '@/apps/interface/sui-js';\nimport { SuiNetworks } from '@/types';\n\nimport { updatePackageId } from './config';\nimport { Decoder } from './decoder';\nimport { ClaimRewardIntention, ClaimRewardIntentionData } from './intentions/claim-reward';\nimport { EntryBorrowIntention, EntryBorrowIntentionData } from './intentions/entry-borrow';\nimport { EntryDepositIntention, EntryDepositIntentionData } from './intentions/entry-deposit';\nimport { EntryRepayIntention, EntryRepayIntentionData } from './intentions/entry-repay';\nimport { EntryWithdrawIntention, EntryWithdrawIntentionData } from './intentions/entry-withdraw';\nimport { TransactionSubType } from './types';\n\nexport type NAVIIntention =\n | EntryDepositIntention\n | EntryBorrowIntention\n | EntryRepayIntention\n | EntryWithdrawIntention\n | ClaimRewardIntention;\n\nexport type NAVIIntentionData =\n | EntryDepositIntentionData\n | EntryBorrowIntentionData\n | EntryRepayIntentionData\n | EntryWithdrawIntentionData\n | ClaimRewardIntentionData;\n\nexport class NAVIAppHelper implements IAppHelperInternalLegacy<NAVIIntentionData> {\n application = 'navi';\n\n supportSDK = '@mysten/sui.js' as const;\n\n async deserialize(\n input: SuiSignTransactionBlockInput & { network: SuiNetworks; suiClient: SuiClient; account: WalletAccount },\n ): Promise<{ txType: TransactionType; txSubType: TransactionSubType; intentionData: NAVIIntentionData }> {\n await updatePackageId();\n const { transactionBlock } = input;\n const decoder = new Decoder(transactionBlock);\n const result = decoder.decode();\n return {\n txType: TransactionType.Other,\n txSubType: result.type,\n intentionData: result.intentionData,\n };\n }\n\n async build(input: {\n intentionData: NAVIIntentionData;\n txType: TransactionType;\n txSubType: string;\n suiClient: SuiClient;\n account: WalletAccount;\n }): Promise<TransactionBlock> {\n const { suiClient, account } = input;\n let intention: NAVIIntention;\n await updatePackageId();\n switch (input.txSubType) {\n case TransactionSubType.EntryDeposit:\n intention = EntryDepositIntention.fromData(input.intentionData as EntryDepositIntentionData);\n break;\n case TransactionSubType.EntryBorrow:\n intention = EntryBorrowIntention.fromData(input.intentionData as EntryBorrowIntentionData);\n break;\n case TransactionSubType.EntryRepay:\n intention = EntryRepayIntention.fromData(input.intentionData as EntryRepayIntentionData);\n break;\n case TransactionSubType.EntryWithdraw:\n intention = EntryWithdrawIntention.fromData(input.intentionData as EntryWithdrawIntentionData);\n break;\n case TransactionSubType.ClaimReward:\n intention = ClaimRewardIntention.fromData(input.intentionData as ClaimRewardIntentionData);\n break;\n default:\n throw new Error('not implemented');\n }\n return intention.build({ suiClient, account });\n }\n}\n","import { CoinType, type Pool } from './types';\n\nlet updated = false;\n\nconst config = {\n ProtocolPackage: '0xc6374c7da60746002bfee93014aeb607e023b2d6b25c9e55a152b826dbc8c1ce',\n StorageId: '0xbb4e2f4b6205c2e2a2db47aeb4f830796ec7c005f88537ee775986639bc442fe',\n Incentive: '0xaaf735bf83ff564e1b219a0d644de894ef5bdc4b2250b126b2a46dd002331821',\n IncentiveV2: '0xf87a8acb8b81d14307894d12595541a73f19933f88e1326d5be349c7a6f7559c', // The new incentive version: V2\n gasBudget: 50_000_000,\n PriceOracle: '0x1568865ed9a0b5ec414220e8f79b3d04c77acc82358f6e5ae4635687392ffbef',\n ReserveParentId: '0xe6d4c6610b86ce7735ea754596d71d72d10c7980b5052fc3c8cdf8d09fea9b4b', // get it from storage object id. storage.reserves\n pool: {\n sui: {\n name: 'SUI',\n assetId: 0,\n poolId: '0x96df0fce3c471489f4debaaa762cf960b3d97820bd1f3f025ff8190730e958c5',\n fondPoolId: '0xf975bc2d4cca10e3ace8887e20afd77b46c383b4465eac694c4688344955dea4',\n type: '0x2::sui::SUI',\n coinType: CoinType.sui,\n reserveObjectId: '0xab644b5fd11aa11e930d1c7bc903ef609a9feaf9ffe1b23532ad8441854fbfaf',\n borrowBalanceParentId: '0xe7ff0daa9d090727210abe6a8b6c0c5cd483f3692a10610386e4dc9c57871ba7',\n supplyBalanceParentId: '0x589c83af4b035a3bc64c40d9011397b539b97ea47edf7be8f33d643606bf96f8',\n },\n wusdc: {\n name: 'wUSDC',\n assetId: 1,\n coinType: CoinType.wusdc,\n poolId: '0xa02a98f9c88db51c6f5efaaf2261c81f34dd56d86073387e0ef1805ca22e39c8',\n type: '0x5d4b302506645c37ff133b98c4b50a5ae14841659738d6d733d59d0d217a93bf::coin::COIN',\n reserveObjectId: '0xeb3903f7748ace73429bd52a70fff278aac1725d3b58afa781f25ce3450ac203',\n borrowBalanceParentId: '0x8a3aaa817a811131c624658f6e77cba04ab5829293d2c49c1a9cce8ac9c8dec4',\n supplyBalanceParentId: '0x8d0a4467806458052d577c8cd2be6031e972f2b8f5f77fce98aa12cd85330da9',\n },\n usdt: {\n name: 'USDT',\n coinType: CoinType.usdt,\n assetId: 2,\n poolId: '0x0e060c3b5b8de00fb50511b7a45188c8e34b6995c01f69d98ea5a466fe10d103',\n type: '0xc060006111016b8a020ad5b33834984a437aaa7d3c74c18e09a95d48aceab08c::coin::COIN',\n reserveObjectId: '0xb8c5eab02a0202f638958cc79a69a2d30055565caad1684b3c8bbca3bddcb322',\n borrowBalanceParentId: '0xc14d8292a7d69ae31164bafab7ca8a5bfda11f998540fe976a674ed0673e448f',\n supplyBalanceParentId: '0x7e2a49ff9d2edd875f82b76a9b21e2a5a098e7130abfd510a203b6ea08ab9257',\n },\n weth: {\n name: 'WETH',\n coinType: CoinType.weth,\n assetId: 3,\n poolId: '0x71b9f6e822c48ce827bceadce82201d6a7559f7b0350ed1daa1dc2ba3ac41b56',\n type: '0xaf8cd5edc19c4512f4259f0bee101a40d41ebed738ade5874359610ef8eeced5::coin::COIN',\n reserveObjectId: '0xafecf4b57899d377cc8c9de75854c68925d9f512d0c47150ca52a0d3a442b735',\n borrowBalanceParentId: '0x7568d06a1b6ffc416a36c82791e3daf0e621cf19d4a2724fc6f74842661b6323',\n supplyBalanceParentId: '0xa668905b1ad445a3159b4d29b1181c4a62d864861b463dd9106cc0d97ffe8f7f',\n },\n cetus: {\n name: 'CETUS',\n coinType: CoinType.cetus,\n assetId: 4,\n poolId: '0x3c376f857ec4247b8ee456c1db19e9c74e0154d4876915e54221b5052d5b1e2e',\n type: '0x06864a6f921804860930db6ddbe2e16acdf8504495ea7481637a1c8b9a8fe54b::cetus::CETUS',\n reserveObjectId: '0x66a807c06212537fe46aa6719a00e4fa1e85a932d0b53ce7c4b1041983645133',\n borrowBalanceParentId: '0x4c3da45ffff6432b4592a39cdb3ce12f4a28034cbcb804bb071facc81fdd923d',\n supplyBalanceParentId: '0x6adc72faf2a9a15a583c9fb04f457c6a5f0b456bc9b4832413a131dfd4faddae',\n },\n voloSui: {\n name: 'VoloSui',\n coinType: CoinType.voloSui,\n assetId: 5,\n poolId: '0x9790c2c272e15b6bf9b341eb531ef16bcc8ed2b20dfda25d060bf47f5dd88d01',\n fondPoolId: '0xe2b5ada45273676e0da8ae10f8fe079a7cec3d0f59187d3d20b1549c275b07ea',\n type: '0x549e8b69270defbfafd4f94e17ec44cdbdd99820b33bda2278dea3b9a32d3f55::cert::CERT',\n reserveObjectId: '0xd4fd7e094af9819b06ea3136c13a6ae8da184016b78cf19773ac26d2095793e2',\n borrowBalanceParentId: '0x8fa5eccbca2c4ba9aae3b87fd44aa75aa5f5b41ea2d9be4d5321379384974984',\n supplyBalanceParentId: '0xe6457d247b6661b1cac123351998f88f3e724ff6e9ea542127b5dcb3176b3841',\n },\n haSui: {\n name: 'HaedalSui',\n coinType: CoinType.haSui,\n assetId: 6,\n poolId: '0x6fd9cb6ebd76bc80340a9443d72ea0ae282ee20e2fd7544f6ffcd2c070d9557a',\n fondPoolId: '0xa20e18085ce04be8aa722fbe85423f1ad6b1ae3b1be81ffac00a30f1d6d6ab51',\n type: '0xbde4ba4c2e274a60ce15c1cfff9e5c42e41654ac8b6d906a57efa4bd3c29f47d::hasui::HASUI',\n reserveObjectId: '0x0c9f7a6ca561dc566bd75744bcc71a6af1dc3caf7bd32c099cd640bb5f3bb0e3',\n borrowBalanceParentId: '0x01f36898e020be6c3423e5c95d9f348868813cd4d0be39b0c8df9d8de4722b00',\n supplyBalanceParentId: '0x278b8e3d09c3548c60c51ed2f8eed281876ea58c392f71b7ff650cc9286d095b',\n },\n navx: {\n name: 'NAVX',\n coinType: CoinType.navx,\n assetId: 7,\n poolId: '0xc0e02e7a245e855dd365422faf76f87d9f5b2148a26d48dda6e8253c3fe9fa60',\n fondPoolId: '0x9dae0cf104a193217904f88a48ce2cf0221e8cd9073878edd05101d6b771fa09',\n type: '0xa99b8952d4f7d947ea77fe0ecdcc9e5fc0bcab2841d6e2a5aa00c3044e5544b5::navx::NAVX',\n reserveObjectId: '0x2e13b2f1f714c0c5fa72264f147ef7632b48ec2501f810c07df3ccb59d6fdc81',\n borrowBalanceParentId: '0xa5bf13075aa400cbdd4690a617c5f008e1fae0511dcd4f7121f09817df6c8d8b',\n supplyBalanceParentId: '0x59dedca8dc44e8df50b190f8b5fe673098c1273ac6168c0a4addf3613afcdee5',\n },\n wbtc: {\n name: 'WBTC',\n coinType: CoinType.wbtc,\n assetId: 8,\n poolId: '0xd162cbe40f8829ce71c9b3d3bf3a83859689a79fa220b23d70dc0300b777ae6e',\n type: '0x027792d9fed7f9844eb4839566001bb6f6cb4804f66aa2da6fe1ee242d896881::coin::COIN',\n reserveObjectId: '0x8b4d81f004e4e9faf4540951a896b6d96e42598a270e6375f598b99742db767e',\n borrowBalanceParentId: '0x55e1f3c9e6e5cf9fff563bdd61db07a3826458c56ef72c455e049ab3b1b0e99c',\n supplyBalanceParentId: '0x821e505a0091b089edba94deaa14c2f2230d026bbaa7b85680554441aad447e0',\n },\n ausd: {\n name: 'AUSD',\n coinType: CoinType.ausd,\n assetId: 9,\n poolId: '0xc9208c1e75f990b2c814fa3a45f1bf0e85bb78404cfdb2ae6bb97de58bb30932',\n type: '0x2053d08c1e2bd02791056171aab0fd12bd7cd7efad2ab8f6b9c8902f14df2ff2::ausd::AUSD',\n reserveObjectId: '0x918889c6a9d9b93108531d4d59a4ebb9cc4d41689798ffc1d4aed6e1ae816ec0',\n borrowBalanceParentId: '0x551300b9441c9a3a16ca1d7972c1dbb4715e15004ccd5f001b2c2eee22fd92c1',\n supplyBalanceParentId: '0xe151af690355de8be1c0281fbd0d483c099ea51920a57c4bf8c9666fd36808fd',\n },\n nusdc: {\n name: 'USDC',\n assetId: 10,\n coinType: CoinType.nusdc,\n poolId: '0xa3582097b4c57630046c0c49a88bfc6b202a3ec0a9db5597c31765f7563755a8',\n type: '0xdba34672e30cb065b1f93e3ab55318768fd6fef66c15942c9f7cb846e2f900e7::usdc::USDC',\n reserveObjectId: '0x4c8a2c72a22ae8da803a8519798d312c86e74a9e0d6ec0eec2bfcf7e4b3fef5e',\n borrowBalanceParentId: '0xb0b0c7470e96cabbb4f1e8d06bef2fbea65f4dbac52afae8635d9286b1ea9a09',\n supplyBalanceParentId: '0x08b5ce8574ac3bc9327e66ad5decd34d07ee798f724ad01058e8855ac9acb605',\n },\n eth: {\n name: 'ETH',\n assetId: 11,\n coinType: CoinType.eth,\n poolId: '0x78ba01c21d8301be15690d3c30dc9f111871e38cfb0b2dd4b70cc6052fba41bb',\n type: '0xd0e89b2af5e4910726fbcd8b8dd37bb79b29e5f83f7491bca830e94f7f226d29::eth::ETH',\n reserveObjectId: '0x376faea6dfbffab9ea808474cb751d91222b6d664f38c0f1d23de442a8edb1ce',\n borrowBalanceParentId: '0xf0c6ce5cfaee96073876a5fab7426043f3a798b79502c4caeb6d9772cd35af1f',\n supplyBalanceParentId: '0xc0a0cb43620eb8a84d5a4a50a85650e7fa7ba81e660f9cc2863404fd84591d4b',\n },\n usdy: {\n name: 'USDY',\n assetId: 12,\n coinType: CoinType.usdy,\n poolId: '0x4b6253a9f8cf7f5d31e6d04aed4046b9e325a1681d34e0eff11a8441525d4563',\n type: '0x960b531667636f39e85867775f52f6b1f220a058c4de786905bdf761e06a56bb::usdy::USDY',\n reserveObjectId: '',\n borrowBalanceParentId: '',\n supplyBalanceParentId: '',\n },\n } as Pool,\n borrowFee: 0.003,\n borrowFeeAddress: '0x70b9b10704263cf53392849e33b1f5fd16005869b4198ed5524836bad1234ea2',\n};\n\nexport async function updatePackageId() {\n if (updated) {\n return;\n }\n try {\n const data = await fetch('https://open-api.naviprotocol.io/api/msafe').then((res) => res.json());\n const { packageId, borrowFee, borrowFeeAddress, pool } = data;\n if (packageId) {\n config.ProtocolPackage = packageId;\n }\n if (borrowFee) {\n config.borrowFee = borrowFee;\n }\n if (borrowFeeAddress) {\n config.borrowFeeAddress = borrowFeeAddress;\n }\n if (pool) {\n config.pool = pool;\n }\n updated = true;\n } catch (e: any) {\n console.error(e.message);\n }\n}\n\nexport default config;\n","import { TransactionType } from '@msafe/sui3-utils';\nimport { bcs } from '@mysten/sui.js/bcs';\nimport { MoveCallTransaction } from '@mysten/sui.js/dist/cjs/transactions';\nimport { TransactionBlock, TransactionBlockInput } from '@mysten/sui.js/transactions';\nimport { normalizeStructTag, normalizeSuiAddress } from '@mysten/sui.js/utils';\n\nimport config from './config';\nimport { CoinType, TransactionSubType } from './types';\n\nexport function isSameCoinType(type1: string, type2: string) {\n return normalizeStructTag(type1) === normalizeStructTag(type2);\n}\n\nexport function isSameTarget(target1: string, target2: string): boolean {\n return normalizeStructTag(target1) === normalizeStructTag(target2);\n}\n\ntype DecodeResult = {\n txType: TransactionType;\n type: TransactionSubType;\n intentionData: any;\n};\n\nexport class Decoder {\n constructor(public readonly txb: TransactionBlock) {}\n\n decode() {\n console.log('txb', this.txb);\n if (this.isClaimRewardTransaction()) {\n return this.decodeClaimReward();\n }\n if (this.isEntryBorrowTransaction()) {\n return this.decodeEntryBorrow();\n }\n if (this.isEntryBorrowWithFeeTransaction()) {\n return this.decodeEntryBorrow();\n }\n if (this.isEntryDepositTransaction()) {\n return this.decodeEntryDeposit();\n }\n if (this.isEntryRepayTransaction()) {\n return this.decodeEntryRepay();\n }\n if (this.isEntryWithdrawTransaction()) {\n return this.decodeEntryWithdraw();\n }\n throw new Error(`Unknown transaction type`);\n }\n\n private get transactions() {\n return this.txb.blockData.transactions;\n }\n\n private getMoveCallTransaction(target: string) {\n return this.transactions.find((trans) => trans.kind === 'MoveCall' && trans.target === target);\n }\n\n private isClaimRewardTransaction() {\n return !!this.getMoveCallTransaction(`${config.ProtocolPackage}::incentive_v2::claim_reward`);\n }\n\n private isEntryBorrowTransaction() {\n return !!this.getMoveCallTransaction(`${config.ProtocolPackage}::incentive_v2::entry_borrow`);\n }\n\n private isEntryBorrowWithFeeTransaction() {\n return !!this.getMoveCallTransaction(`${config.ProtocolPackage}::incentive_v2::borrow`);\n }\n\n private isEntryDepositTransaction() {\n return !!this.getMoveCallTransaction(`${config.ProtocolPackage}::incentive_v2::entry_deposit`);\n }\n\n private isEntryRepayTransaction(): boolean {\n return !!this.getMoveCallTransaction(`${config.ProtocolPackage}::incentive_v2::entry_repay`);\n }\n\n private isEntryWithdrawTransaction(): boolean {\n return !!this.getMoveCallTransaction(`${config.ProtocolPackage}::incentive_v2::entry_withdraw`);\n }\n\n private findPoolByAssetId(assetId: number) {\n const findPool = Object.values(config.pool).find((pool) => pool.assetId === assetId);\n if (!findPool) {\n throw new Error('Pool not found');\n }\n return findPool;\n }\n\n private decodeClaimReward(): DecodeResult {\n const claims = [] as {\n coinType: CoinType;\n option: number;\n poolId: string;\n assetId: number;\n typeArguments: string[];\n }[];\n this.transactions.forEach((trans) => {\n if (trans.kind === 'MoveCall' && trans.target === `${config.ProtocolPackage}::incentive_v2::claim_reward`) {\n const helper = new MoveCallHelper(trans, this.txb);\n const assetId = helper.decodeInputU8(4);\n const optionId = helper.decodeInputU8(5);\n const poolId = helper.decodeSharedObjectId(2);\n const pool = this.findPoolByAssetId(assetId);\n const typeArguments = [...trans.typeArguments];\n claims.push({\n coinType: pool.coinType,\n option: optionId,\n typeArguments,\n assetId,\n poolId,\n });\n }\n });\n console.log('decode claims', claims);\n return {\n txType: TransactionType.Other,\n type: TransactionSubType.ClaimReward,\n intentionData: {\n claims,\n },\n };\n }\n\n private decodeEntryBorrow(): DecodeResult {\n const assetId = this.helper.decodeInputU8(4);\n const amount = this.helper.decodeInputU64(5);\n const pool = this.findPoolByAssetId(assetId);\n return {\n txType: TransactionType.Other,\n type: TransactionSubType.EntryBorrow,\n intentionData: {\n amount,\n coinType: pool.coinType,\n },\n };\n }\n\n private decodeEntryDeposit(): DecodeResult {\n const assetId = this.helper.decodeInputU8(3);\n const amount = this.helper.decodeInputU64(5);\n const pool = this.findPoolByAssetId(assetId);\n return {\n txType: TransactionType.Other,\n type: TransactionSubType.EntryDeposit,\n intentionData: {\n amount,\n coinType: pool.coinType,\n },\n };\n }\n\n private decodeEntryRepay(): DecodeResult {\n const assetId = this.helper.decodeInputU8(4);\n const amount = this.helper.decodeInputU64(6);\n const pool = this.findPoolByAssetId(assetId);\n return {\n txType: TransactionType.Other,\n type: TransactionSubType.EntryRepay,\n intentionData: {\n amount,\n coinType: pool.coinType,\n },\n };\n }\n\n private decodeEntryWithdraw(): DecodeResult {\n const assetId = this.helper.decodeInputU8(4);\n const amount = this.helper.decodeInputU64(5);\n const pool = this.findPoolByAssetId(assetId);\n return {\n txType: TransactionType.Other,\n type: TransactionSubType.EntryWithdraw,\n intentionData: {\n amount,\n coinType: pool.coinType,\n },\n };\n }\n\n private get helper() {\n const moveCall = this.transactions.find(\n (trans) => trans.kind === 'MoveCall' && trans.target.startsWith(config.ProtocolPackage),\n ) as MoveCallTransaction;\n return new MoveCallHelper(moveCall, this.txb);\n }\n}\n\nexport class MoveCallHelper {\n constructor(\n public readonly moveCall: MoveCallTransaction,\n public readonly txb: TransactionBlock,\n ) {}\n\n decodeSharedObjectId(argIndex: number) {\n const input = this.getInputParam(argIndex);\n return MoveCallHelper.getSharedObjectId(input);\n }\n\n decodeOwnedObjectId(argIndex: number) {\n const input = this.getInputParam(argIndex);\n return MoveCallHelper.getOwnedObjectId(input);\n }\n\n decodeInputU64(argIndex: number) {\n const strVal = this.decodePureArg<string>(argIndex, 'u64');\n return Number(strVal);\n }\n\n decodeInputU8(argIndex: number) {\n const strVal = this.decodePureArg<string>(argIndex, 'u8');\n return Number(strVal);\n }\n\n decodeInputAddress(argIndex: number) {\n const input = this.decodePureArg<string>(argIndex, 'address');\n return normalizeSuiAddress(input);\n }\n\n decodeInputString(argIndex: number) {\n return this.decodePureArg<string>(argIndex, 'string');\n }\n\n decodeInputBool(argIndex: number) {\n return this.decodePureArg<boolean>(argIndex, 'bool');\n }\n\n decodePureArg<T>(argIndex: number, bcsType: string) {\n const input = this.getInputParam(argIndex);\n return MoveCallHelper.getPureInputValue<T>(input, bcsType);\n }\n\n getInputParam(argIndex: number) {\n const arg = this.moveCall.arguments[argIndex];\n if (arg.kind !== 'Input') {\n throw new Error('not input type');\n }\n return this.txb.blockData.inputs[arg.index];\n }\n\n static getPureInputValue<T>(input: TransactionBlockInput, bcsType: string) {\n if (input.type !== 'pure') {\n throw new Error('not pure argument');\n }\n if (typeof input.value === 'object' && 'Pure' in input.value) {\n const bcsNums = input.value.Pure;\n return bcs.de(bcsType, new Uint8Array(bcsNums)) as T;\n }\n return input.value as T;\n }\n\n static getOwnedObjectId(input: TransactionBlockInput) {\n if (input.type !== 'object') {\n throw new Error(`not object argument: ${JSON.stringify(input)}`);\n }\n if (typeof input.value === 'object') {\n if (!('Object' in input.value) || !('ImmOrOwned' in input.value.Object)) {\n throw new Error('not ImmOrOwned');\n }\n return normalizeSuiAddress(input.value.Object.ImmOrOwned.objectId as string);\n }\n return normalizeSuiAddress(input.value as string);\n }\n\n static getSharedObjectId(input: TransactionBlockInput) {\n if (input.type !== 'object') {\n throw new Error(`not object argument: ${JSON.stringify(input)}`);\n }\n if (typeof input.value !== 'object') {\n return normalizeSuiAddress(input.value as string);\n }\n if (!('Object' in input.value) || !('Shared' in input.value.Object)) {\n throw new Error('not Shared');\n }\n return normalizeSuiAddress(input.value.Object.Shared.objectId as string);\n }\n\n static getPureInput<T>(input: TransactionBlockInput, bcsType: string) {\n if (input.type !== 'pure') {\n throw new Error('not pure argument');\n }\n if (typeof input.value !== 'object') {\n return input.value as T;\n }\n if (!('Pure' in input.value)) {\n throw new Error('Pure not in value');\n }\n const bcsVal = input.value.Pure;\n return bcs.de(bcsType, new Uint8Array(bcsVal)) as T;\n }\n\n typeArg(index: number) {\n return normalizeStructTag(this.moveCall.typeArguments[index]);\n }\n\n txArg(index: number) {\n return this.moveCall.arguments[index];\n }\n}\n","import { TransactionType } from '@msafe/sui3-utils';\nimport { TransactionBlock } from '@mysten/sui.js/transactions';\n\nimport { BaseIntentionLegacy } from '@/apps/interface/sui-js';\n\nimport { claimReward } from '../api/incentiveV2';\nimport { CoinType, TransactionSubType, OptionType } from '../types';\n\nexport interface ClaimRewardIntentionData {\n claims: {\n coinType: CoinType;\n option: OptionType;\n poolId: string;\n assetId: number;\n typeArguments: string[];\n }[];\n}\n\nexport class ClaimRewardIntention extends BaseIntentionLegacy<ClaimRewardIntentionData> {\n txType: TransactionType.Other;\n\n txSubType: TransactionSubType.ClaimReward;\n\n constructor(public readonly data: ClaimRewardIntentionData) {\n super(data);\n }\n\n async build(): Promise<TransactionBlock> {\n const { claims } = this.data;\n const tx = new TransactionBlock();\n\n claims.forEach((claim) => {\n const { assetId, poolId, option, typeArguments } = claim;\n\n claimReward(tx, assetId, poolId, option, typeArguments);\n });\n\n return tx;\n }\n\n static fromData(data: ClaimRewardIntentionData) {\n return new ClaimRewardIntention(data);\n }\n}\n","import { TransactionBlock } from '@mysten/sui.js/transactions';\n\nimport config from '../config';\nimport { OptionType, PoolConfig } from '../types';\n\nexport function depositToken(txb: TransactionBlock, pool: PoolConfig, coinObject: any, amount: number) {\n txb.moveCall({\n target: `${config.ProtocolPackage}::incentive_v2::entry_deposit`,\n arguments: [\n txb.object('0x06'),\n txb.object(config.StorageId),\n txb.object(pool.poolId),\n txb.pure(pool.assetId),\n coinObject,\n txb.pure(amount),\n txb.object(config.Incentive),\n txb.object(config.IncentiveV2),\n ],\n typeArguments: [pool.type],\n });\n return txb;\n}\n\nexport function withdrawToken(txb: TransactionBlock, pool: PoolConfig, amount: number) {\n txb.moveCall({\n target: `${config.ProtocolPackage}::incentive_v2::entry_withdraw`,\n arguments: [\n txb.object('0x06'),\n txb.object(config.PriceOracle),\n txb.object(config.StorageId),\n txb.object(pool.poolId),\n txb.pure(pool.assetId),\n txb.pure(amount),\n txb.object(config.Incentive),\n txb.object(config.IncentiveV2),\n ],\n typeArguments: [pool.type],\n });\n return txb;\n}\n\nexport function borrowToken(tx: TransactionBlock, pool: PoolConfig, amount: number, userAddress: string) {\n const borrowBalance = tx.moveCall({\n target: `${config.ProtocolPackage}::incentive_v2::borrow`,\n arguments: [\n tx.object('0x06'),\n tx.object(config.PriceOracle),\n tx.object(config.StorageId),\n tx.object(pool.poolId),\n tx.pure(pool.assetId),\n tx.pure(amount),\n tx.object(config.IncentiveV2),\n ],\n typeArguments: [pool.type],\n });\n\n const [borrowCoin] = tx.moveCall({\n target: `0x02::coin::from_balance`,\n typeArguments: [pool.type],\n arguments: [borrowBalance],\n });\n if (config.borrowFee > 0) {\n const [borrowFeeCoin] = tx.splitCoins(borrowCoin, [tx.pure(Math.floor(amount * config.borrowFee))]);\n tx.transferObjects([borrowCoin], tx.pure(userAddress));\n tx.transferObjects([borrowFeeCoin], tx.pure(config.borrowFeeAddress));\n } else {\n tx.transferObjects([borrowCoin], tx.pure(userAddress));\n }\n\n return tx;\n}\n\nexport function repayToken(txb: TransactionBlock, pool: PoolConfig, coinObject: any, amount: number) {\n txb.moveCall({\n target: `${config.ProtocolPackage}::incentive_v2::entry_repay`,\n arguments: [\n txb.object('0x06'),\n txb.object(config.PriceOracle),\n txb.object(config.StorageId),\n txb.object(pool.poolId),\n txb.pure(pool.assetId),\n coinObject,\n txb.pure(amount),\n txb.object(config.IncentiveV2),\n ],\n typeArguments: [pool.type],\n });\n return txb;\n}\n\nexport function claimReward(\n txb: TransactionBlock,\n assetId: number,\n poolId: string,\n option: OptionType,\n typeArguments: string[],\n) {\n txb.moveCall({\n target: `${config.ProtocolPackage}::incentive_v2::claim_reward`,\n arguments: [\n txb.object('0x06'),\n txb.object(config.IncentiveV2),\n txb.object(poolId),\n txb.object(config.StorageId),\n txb.pure(assetId),\n txb.pure(option),\n ],\n typeArguments,\n });\n return txb;\n}\n","import { TransactionType } from '@msafe/sui3-utils';\nimport { TransactionBlock } from '@mysten/sui.js/transactions';\nimport { WalletAccount } from '@mysten/wallet-standard';\n\nimport { BaseIntentionLegacy } from '@/apps/interface/sui-js';\n\nimport { borrowToken } from '../api/incentiveV2';\nimport config from '../config';\nimport { CoinType, TransactionSubType } from '../types';\n\nexport interface EntryBorrowIntentionData {\n amount: number;\n coinType: CoinType;\n}\n\nexport class EntryBorrowIntention extends BaseIntentionLegacy<EntryBorrowIntentionData> {\n txType: TransactionType.Other;\n\n txSubType: TransactionSubType.EntryBorrow;\n\n constructor(public readonly data: EntryBorrowIntentionData) {\n super(data);\n }\n\n async build(input: { account: WalletAccount }): Promise<TransactionBlock> {\n const { coinType, amount } = this.data;\n const tx = new TransactionBlock();\n console.log('build', this.data);\n\n const pool = config.pool[coinType];\n\n if (!pool) {\n throw new Error(`${coinType} not support, please use ${Object.keys(config.pool).join(', ')}.`);\n }\n\n return borrowToken(tx, pool, amount, input.account.address);\n }\n\n static fromData(data: EntryBorrowIntentionData) {\n return new EntryBorrowIntention(data);\n }\n}\n","import { TransactionType } from '@msafe/sui3-utils';\nimport { SuiClient } from '@mysten/sui.js/client';\nimport { TransactionBlock } from '@mysten/sui.js/transactions';\nimport { WalletAccount } from '@mysten/wallet-standard';\n\nimport { BaseIntentionLegacy } from '@/apps/interface/sui-js';\n\nimport { depositToken } from '../api/incentiveV2';\nimport config from '../config';\nimport { CoinType, TransactionSubType } from '../types';\nimport { getTokenObjs } from '../utils/token';\n\nexport interface EntryDepositIntentionData {\n amount: number;\n coinType: CoinType;\n}\n\nexport class EntryDepositIntention extends BaseIntentionLegacy<EntryDepositIntentionData> {\n txType: TransactionType.Other;\n\n txSubType: TransactionSubType.EntryDeposit;\n\n constructor(public readonly data: EntryDepositIntentionData) {\n super(data);\n }\n\n async build(input: { suiClient: SuiClient; account: WalletAccount }): Promise<TransactionBlock> {\n const { suiClient, account } = input;\n const { coinType, amount } = this.data;\n const tx = new TransactionBlock();\n console.log('build', this.data);\n\n if (coinType === 'sui') {\n const [toDeposit] = tx.splitCoins(tx.gas, [amount]);\n return depositToken(tx, config.pool.sui, toDeposit, amount);\n }\n\n const pool = config.pool[coinType];\n\n if (!pool) {\n throw new Error(`${coinType} not support, please use ${Object.keys(config.pool).join(', ')}.`);\n }\n\n const tokenInfo = await getTokenObjs(suiClient, account.address, pool.type);\n if (!tokenInfo.data[0]) {\n throw new Error(`Insufficient balance for ${pool.name} Token`);\n }\n\n const coinObj = tokenInfo.data[0].coinObjectId;\n\n if (tokenInfo.data.length >= 2) {\n let i = 1;\n while (i < tokenInfo.data.length) {\n tx.mergeCoins(coinObj, [tokenInfo.data[i].coinObjectId]);\n i++;\n }\n }\n\n return depositToken(tx, pool, tx.object(coinObj), amount);\n }\n\n static fromData(data: EntryDepositIntentionData) {\n return new EntryDepositIntention(data);\n }\n}\n","import { SuiClient } from '@mysten/sui.js/client';\n\nexport async function getTokenAmount(client: SuiClient, sender: string, coinType: string): Promise<number> {\n if (!sender) {\n throw new Error('Sender is undefined.');\n }\n if (!client) {\n throw new Error('Client is undefined.');\n }\n const coinInfo = await client.getBalance({\n owner: sender,\n coinType,\n });\n const tokenBalance = Number(coinInfo.totalBalance);\n return tokenBalance;\n}\n\nexport async function getTokenObjs(client: SuiClient, sender: string, coinType: string): Promise<any> {\n const result = await client.getCoins({\n owner: sender,\n coinType,\n });\n console.log('getTokenObjs', sender, result);\n return result;\n}\n","import { TransactionType } from '@msafe/sui3-utils';\nimport { SuiClient } from '@mysten/sui.js/client';\nimport { TransactionBlock } from '@mysten/sui.js/transactions';\nimport { WalletAccount } from '@mysten/wallet-standard';\n\nimport { BaseIntentionLegacy } from '@/apps/interface/sui-js';\n\nimport { repayToken } from '../api/incentiveV2';\nimport config from '../config';\nimport { CoinType, TransactionSubType } from '../types';\nimport { getTokenObjs } from '../utils/token';\n\nexport interface EntryRepayIntentionData {\n amount: number;\n coinType: CoinType;\n}\n\nexport class EntryRepayIntention extends BaseIntentionLegacy<EntryRepayIntentionData> {\n txType: TransactionType.Other;\n\n txSubType: TransactionSubType.EntryRepay;\n\n constructor(public readonly data: EntryRepayIntentionData) {\n super(data);\n }\n\n async build(input: { suiClient: SuiClient; account: WalletAccount }): Promise<TransactionBlock> {\n const { suiClient, account } = input;\n const { coinType, amount } = this.data;\n const tx = new TransactionBlock();\n console.log('build', this.data);\n\n if (coinType === 'sui') {\n const [toDeposit] = tx.splitCoins(tx.gas, [amount]);\n return repayToken(tx, config.pool.sui, toDeposit, amount);\n }\n\n const pool = config.pool[coinType];\n\n if (!pool) {\n throw new Error(`${coinType} not support, please use ${Object.keys(config.pool).join(', ')}.`);\n }\n\n const tokenInfo = await getTokenObjs(suiClient, account.address, pool.type);\n if (!tokenInfo.data[0]) {\n throw new Error(`Insufficient balance for ${pool.name} Token`);\n }\n\n const coinObj = tokenInfo.data[0].coinObjectId;\n\n if (tokenInfo.data.length >= 2) {\n let i = 1;\n while (i < tokenInfo.data.length) {\n tx.mergeCoins(coinObj, [tokenInfo.data[i].coinObjectId]);\n i++;\n }\n }\n\n return repayToken(tx, pool, tx.object(coinObj), amount);\n }\n\n static fromData(data: EntryRepayIntentionData) {\n return new EntryRepayIntention(data);\n }\n}\n","import { TransactionType } from '@msafe/sui3-utils';\nimport { TransactionBlock } from '@mysten/sui.js/transactions';\n\nimport { BaseIntentionLegacy } from '@/apps/interface/sui-js';\n\nimport { withdrawToken } from '../api/incentiveV2';\nimport config from '../config';\nimport { CoinType, TransactionSubType } from '../types';\n\nexport interface EntryWithdrawIntentionData {\n amount: number;\n coinType: CoinType;\n}\n\nexport class EntryWithdrawIntention extends BaseIntentionLegacy<EntryWithdrawIntentionData> {\n txType: TransactionType.Other;\n\n txSubType: TransactionSubType.EntryWithdraw;\n\n constructor(public readonly data: EntryWithdrawIntentionData) {\n super(data);\n }\n\n async build(): Promise<TransactionBlock> {\n const { coinType, amount } = this.data;\n const tx = new TransactionBlock();\n console.log('build', this.data);\n\n const pool = config.pool[coinType];\n\n if (!pool) {\n throw new Error(`${coinType} not support, please use ${Object.keys(config.pool).join(', ')}.`);\n }\n\n return withdrawToken(tx, pool, amount);\n }\n\n static fromData(data: EntryWithdrawIntentionData) {\n return new EntryWithdrawIntention(data);\n }\n}\n","import { TransactionSubTypes, TransactionType } from '@msafe/sui3-utils';\nimport { fromHEX, toHEX } from '@mysten/bcs';\nimport { SuiClient } from '@mysten/sui/client';\nimport { Transaction } from '@mysten/sui/transactions';\nimport { IdentifierString, WalletAccount } from '@mysten/wallet-standard';\nimport sortKeys from 'sort-keys-recursive';\n\nimport { IAppHelperInternal, TransactionIntention } from '@/apps/interface/sui';\nimport { SuiNetworks } from '@/types';\n\nexport type PlainTransactionData = {\n content: string;\n};\n\nexport const PlainTransactionApplication = 'msafe-plain-tx';\nexport const PlainTransactionType = TransactionSubTypes.others.plain;\n\nexport class PlainTransactionIntention implements TransactionIntention<PlainTransactionData> {\n application = PlainTransactionApplication;\n\n txType = TransactionType.Other;\n\n txSubType = PlainTransactionType;\n\n protected constructor(public readonly data: PlainTransactionData) {}\n\n serialize() {\n return JSON.stringify(sortKeys(this.data));\n }\n\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n async build(input: { suiClient: SuiClient; account: WalletAccount; network: SuiNetworks }): Promise<Transaction> {\n return Transaction.from(fromHEX(this.data.content));\n }\n\n static fromData(data: PlainTransactionData) {\n return new PlainTransactionIntention(data);\n }\n}\n\nexport class PlainTransactionHelper implements IAppHelperInternal<PlainTransactionData> {\n application: string;\n\n supportSDK = '@mysten/sui' as const;\n\n constructor() {\n this.application = PlainTransactionApplication;\n }\n\n async deserialize(input: {\n transaction: Transaction;\n chain: IdentifierString;\n network: SuiNetworks;\n suiClient: SuiClient;\n account: WalletAccount;\n }): Promise<{ txType: TransactionType; txSubType: string; intentionData: PlainTransactionData }> {\n const { transaction } = input;\n\n const content = await transaction.build({ client: input.suiClient });\n\n return {\n txType: TransactionType.Other,\n txSubType: PlainTransactionType,\n intentionData: { content: toHEX(content) },\n };\n }\n\n async build(input: {\n network: SuiNetworks;\n txType: TransactionType;\n txSubType: string;\n intentionData: PlainTransactionData;\n suiClient: SuiClient;\n account: WalletAccount;\n }): Promise<Transaction> {\n const { account } = input;\n\n const intention = PlainTransactionIntention.fromData(input.intentionData);\n const tx = await intention.build({ suiClient: input.suiClient, network: input.network, account: input.account });\n const client = input.suiClient;\n const inspectResult = await client.devInspectTransactionBlock({\n transactionBlock: tx,\n sender: account.address,\n });\n const success = inspectResult.effects.status.status === 'success';\n if (!success) {\n throw new Error(inspectResult.effects.status.error);\n }\n\n return tx;\n }\n}\n","import { TransactionType } from '@msafe/sui3-utils';\nimport { SuiClient } from '@mysten/sui/client';\nimport { Transaction } from '@mysten/sui/transactions';\nimport { SuiClient as SuiClientLegacy } from '@mysten/sui.js/client';\nimport { TransactionBlock } from '@mysten/sui.js/transactions';\nimport { SuiSignTransactionBlockInput, WalletAccount } from '@mysten/wallet-standard';\n\nimport { IAppHelper } from '@/apps/interface/common';\nimport { IAppHelperInternal } from '@/apps/interface/sui';\nimport { IAppHelperInternalLegacy } from '@/apps/interface/sui-js';\nimport { SuiNetworks } from '@/types';\n\nexport class MSafeApps {\n apps: Map<string, IAppHelper<any>>;\n\n private constructor() {\n this.apps = new Map<string, IAppHelper<any>>();\n }\n\n static fromHelpers(apps: (IAppHelperInternalLegacy<any> | IAppHelperInternal<any>)[]) {\n const mApps = new MSafeApps();\n for (let i = 0; i < apps.length; i++) {\n const app = apps[i];\n switch (app.supportSDK) {\n case '@mysten/sui.js':\n mApps.addLegacyHelper(app);\n break;\n case '@mysten/sui':\n mApps.addHelper(app);\n break;\n default:\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n throw new Error(`${app.application}: ${app.supportSDK} SDK not supported`);\n }\n }\n return mApps;\n }\n\n addLegacyHelper(app: IAppHelperInternalLegacy<any>) {\n this.apps.set(app.application, new SuiJsSdkAdapter(app));\n }\n\n addHelper(app: IAppHelperInternal<any>) {\n this.apps.set(app.application, new SuiSdkAdapter(app));\n }\n\n getAppHelper(appName: string): IAppHelper<any> {\n const app = this.apps.get(appName);\n if (!app) {\n throw new Error(`${appName} not registered`);\n }\n return app;\n }\n}\n\n/*\n SuiSdkAdapter adapts IAppHelperInternal with @mysten/sui to IAppHelper\n TODO: build to @mysten/sui Transaction after update sdk and api\n */\nexport class SuiSdkAdapter implements IAppHelper<any> {\n constructor(public helper: IAppHelperInternal<any>) {}\n\n async deserialize(\n input: SuiSignTransactionBlockInput & {\n network: SuiNetworks;\n clientUrl: string;\n account: WalletAccount;\n },\n ) {\n const client = new SuiClient({ url: input.clientUrl });\n const clientLegacy = new SuiClientLegacy({ url: input.clientUrl });\n const build = await input.transactionBlock.build({ client: clientLegacy });\n const tx = Transaction.from(build);\n return this.helper.deserialize({ ...input, suiClient: client, transaction: tx });\n }\n\n async build(input: {\n intentionData: any;\n txType: TransactionType;\n txSubType: string;\n clientUrl: string;\n account: WalletAccount;\n network: SuiNetworks;\n }): Promise<TransactionBlock> {\n const client = new SuiClient({ url: input.clientUrl });\n const tx = await this.helper.build({ ...input, suiClient: client });\n tx.setSender(input.account.address);\n const bytes = await tx.build({ client });\n return TransactionBlock.from(bytes);\n }\n}\n\n/*\n SuiJsSdkAdapter adapts IAppHelperInternalLegacy with @mysten/sui.js to IAppHelper\n TODO: build to @mysten/sui Transaction after update sdk and api\n */\nexport class SuiJsSdkAdapter implements IAppHelper<any> {\n constructor(public helper: IAppHelperInternalLegacy<any>) {}\n\n async deserialize(\n input: SuiSignTransactionBlockInput & {\n network: SuiNetworks;\n clientUrl: string;\n account: WalletAccount;\n },\n ) {\n const client = new SuiClientLegacy({ url: input.clientUrl });\n return this.helper.deserialize({ ...input, transactionBlock: input.transactionBlock, suiClient: client });\n }\n\n async build(input: {\n intentionData: any;\n txType: TransactionType;\n txSubType: string;\n clientUrl: string;\n account: WalletAccount;\n network: SuiNetworks;\n }): Promise<TransactionBlock> {\n const client = new SuiClientLegacy({ url: input.clientUrl });\n return this.helper.build({ ...input, suiClient: client });\n }\n}\n","import { TransactionType } from '@msafe/sui3-utils';\nimport { SuiClient } from '@mysten/sui.js/client';\nimport { TransactionBlock } from '@mysten/sui.js/transactions';\nimport { SuiSignTransactionBlockInput, WalletAccount } from '@mysten/wallet-standard';\n\nimport { IAppHelperInternalLegacy } from '@/apps/interface/sui-js';\n\nimport { DecoderLending } from './decoders/decoderLending';\nimport { DecoderReferral } from './decoders/decoderReferral';\nimport { DecoderVesca } from './decoders/decoderVesca';\nimport { BorrowIntention, BorrowIntentionData } from './intentions/lending/borrow';\nimport { BorrowWithBoostIntention, BorrowWithBoostIntentionData } from './intentions/lending/borrow-with-boost';\nimport {\n BorrowWithReferralIntention,\n BorrowWithReferralIntentionData,\n} from './intentions/lending/borrow-with-referral';\nimport {\n ClaimIncentiveRewardIntention,\n ClaimIncentiveRewardIntentionData,\n} from './intentions/lending/claim-incentive-reward';\nimport { DepositCollateralIntention, DepositCollateralIntentionData } from './intentions/lending/deposit-collateral';\nimport { MigrateAndClaimIntention, MigrateAndClaimIntentionData } from './intentions/lending/migrate-and-claim';\nimport { MigrateScoinIntention, MigrateScoinIntentionData } from './intentions/lending/migrate-scoin';\nimport {\n MigrateWusdcToUsdcIntention,\n MigrateWusdcToUsdcIntentionData,\n} from './intentions/lending/migrate-wusd-to-usdc';\nimport { OpenObligationIntention, OpenObligationIntentionData } from './intentions/lending/open-obligation';\nimport { RepayIntention, RepayIntentionData } from './intentions/lending/repay';\nimport { RepayWithBoostIntention, RepayWithBoostIntentionData } from './intentions/lending/repay-with-boost';\nimport { StakeSpoolIntention, StakeSpoolIntentionData } from './intentions/lending/stake-spool';\nimport { SupplyLendingIntention, SupplyLendingIntentionData } from './intentions/lending/supply-lending';\nimport { UnstakeSpoolIntention, UnstakeSpoolIntentionData } from './intentions/lending/unstake-spool';\nimport {\n WithdrawAndUnstakeLendingIntention,\n WithdrawAndUnstakeLendingIntentionData,\n} from './intentions/lending/withdraw-and-unstake-lending';\nimport { WithdrawCollateralIntention, WithdrawCollateralIntentionData } from './intentions/lending/withdraw-collateral';\nimport { WithdrawLendingIntention, WithdrawLendingIntentionData } from './intentions/lending/withdraw-lending';\nimport { BindReferralIntention, BindReferralIntentionData } from './intentions/referral/bind-referral';\nimport {\n ClaimRevenueReferralIntention,\n ClaimRevenueReferralIntentionData,\n} from './intentions/referral/claim-revenue-referral';\nimport {\n CreateReferralLinkIntention,\n CreateReferralLinkIntentionData,\n} from './intentions/referral/create-referral-link';\nimport {\n ExtendPeriodAndStakeMoreIntention,\n ExtendPeriodAndStakeMoreIntentionData,\n} from './intentions/staking/extend-period-and-stake-more';\nimport { ExtendStakePeriodIntention, ExtendStakePeriodIntentionData } from './intentions/staking/extend-stake-period';\nimport { RedeemScaIntention, RedeemScaIntentionData } from './intentions/staking/redeem-sca';\nimport {\n RenewExpStakePeriodIntention,\n RenewExpStakePeriodIntentionData,\n} from './intentions/staking/renew-exp-stake-period';\nimport { StakeScaIntention, StakeScaIntentionData } from './intentions/staking/stake-sca';\nimport {\n SupplyAndStakeLendingIntention,\n SupplyAndStakeLendingIntentionData,\n} from './intentions/staking/supply-and-stake-lending';\nimport { WithdrawStakedScaIntention, WithdrawStakedScaIntentionData } from './intentions/staking/withdraw-staked-sca';\nimport { Scallop } from './models/scallop';\nimport { SuiNetworks } from './types';\nimport { TransactionSubType } from './types/utils';\n\nexport type ScallopIntention =\n | SupplyLendingIntention\n | WithdrawLendingIntention\n | BorrowIntention\n | RepayIntention\n | DepositCollateralIntention\n | WithdrawCollateralIntention\n | OpenObligationIntention\n | StakeSpoolIntention\n | UnstakeSpoolIntention\n | ClaimIncentiveRewardIntention\n | BorrowWithBoostIntention\n | StakeScaIntention\n | ExtendStakePeriodIntention\n | ExtendPeriodAndStakeMoreIntention\n | RenewExpStakePeriodIntention\n | WithdrawStakedScaIntention\n | SupplyAndStakeLendingIntention\n | WithdrawAndUnstakeLendingIntention\n | RedeemScaIntention\n | MigrateAndClaimIntention\n | BorrowWithReferralIntention\n | CreateReferralLinkIntention\n | ClaimRevenueReferralIntention\n | BindReferralIntention\n | MigrateScoinIntention\n | RepayWithBoostIntention\n | MigrateWusdcToUsdcIntention;\n\nexport type ScallopIntentionData =\n | SupplyLendingIntentionData\n | WithdrawLendingIntentionData\n | BorrowIntentionData\n | RepayIntentionData\n | DepositCollateralIntentionData\n | WithdrawCollateralIntentionData\n | OpenObligationIntentionData\n | StakeSpoolIntentionData\n | UnstakeSpoolIntentionData\n | ClaimIncentiveRewardIntentionData\n | BorrowWithBoostIntentionData\n | StakeScaIntentionData\n | ExtendStakePeriodIntentionData\n | ExtendPeriodAndStakeMoreIntentionData\n | RenewExpStakePeriodIntentionData\n | WithdrawStakedScaIntentionData\n | SupplyAndStakeLendingIntentionData\n | WithdrawAndUnstakeLendingIntentionData\n | RedeemScaIntentionData\n | MigrateAndClaimIntentionData\n | BorrowWithReferralIntentionData\n | CreateReferralLinkIntentionData\n | ClaimRevenueReferralIntentionData\n | BindReferralIntentionData\n | MigrateScoinIntentionData\n | RepayWithBoostIntentionData\n | MigrateWusdcToUsdcIntentionData;\n\nexport class ScallopAppHelper implements IAppHelperInternalLegacy<ScallopIntentionData> {\n application = 'scallop';\n\n supportSDK = '@mysten/sui.js' as const;\n\n private scallop: Scallop | undefined;\n\n async deserialize(\n input: SuiSignTransactionBlockInput & { network: SuiNetworks; suiClient: SuiClient; account: WalletAccount },\n ): Promise<{\n txType: TransactionType;\n txSubType: TransactionSubType;\n intentionData: ScallopIntentionData;\n }> {\n if (!this.scallop) {\n this.scallop = new Scallop({\n client: input.suiClient,\n walletAddress: input.account.address,\n });\n await this.scallop.init();\n }\n\n const { transactionBlock } = input;\n console.log('transactionBlock', transactionBlock);\n const decoderLending = new DecoderLending(transactionBlock, this.scallop);\n const decoderReferral = new DecoderReferral(transactionBlock, this.scallop);\n const decoderVesca = new DecoderVesca(transactionBlock, this.scallop);\n const result = decoderLending.decode() || decoderReferral.decode() || decoderVesca.decode();\n if (!result) {\n throw new Error('Unknown transaction type');\n }\n return {\n txType: TransactionType.Other,\n txSubType: result.type,\n intentionData: result.intentionData,\n };\n }\n\n async build(input: {\n intentionData: ScallopIntentionData;\n txType: TransactionType;\n txSubType: string;\n suiClient: SuiClient;\n account: WalletAccount;\n network: SuiNetworks;\n }): Promise<TransactionBlock> {\n const { suiClient, account, network, txSubType, intentionData } = input;\n if (!this.scallop) {\n this.scallop = new Scallop({\n client: input.suiClient,\n walletAddress: input.account.address,\n });\n await this.scallop.init();\n }\n\n let intention: ScallopIntention;\n switch (txSubType) {\n case TransactionSubType.SupplyLending:\n intention = SupplyLendingIntention.fromData(intentionData as SupplyLendingIntentionData);\n break;\n case TransactionSubType.WithdrawLending:\n intention = WithdrawLendingIntention.fromData(intentionData as WithdrawLendingIntentionData);\n break;\n case TransactionSubType.Borrow:\n intention = BorrowIntention.fromData(intentionData as BorrowIntentionData);\n break;\n case TransactionSubType.Repay:\n intention = RepayIntention.fromData(intentionData as RepayIntentionData);\n break;\n case TransactionSubType.DepositCollateral:\n intention = DepositCollateralIntention.fromData(intentionData as DepositCollateralIntentionData);\n break;\n case TransactionSubType.WithdrawCollateral:\n intention = WithdrawCollateralIntention.fromData(intentionData as WithdrawCollateralIntentionData);\n break;\n case TransactionSubType.OpenObligation:\n intention = OpenObligationIntention.fromData(intentionData as OpenObligationIntentionData);\n break;\n case TransactionSubType.StakeSpool:\n intention = StakeSpoolIntention.fromData(intentionData as StakeSpoolIntentionData);\n break;\n case TransactionSubType.UnstakeSpool:\n intention = UnstakeSpoolIntention.fromData(intentionData as UnstakeSpoolIntentionData);\n break;\n case TransactionSubType.ClaimIncentiveReward:\n intention = ClaimIncentiveRewardIntention.fromData(intentionData as ClaimIncentiveRewardIntentionData);\n break;\n case TransactionSubType.BorrowWithBoost:\n intention = BorrowWithBoostIntention.fromData(intentionData as BorrowWithBoostIntentionData);\n break;\n case TransactionSubType.StakeSca:\n intention = StakeScaIntention.fromData(intentionData as StakeScaIntentionData);\n break;\n case TransactionSubType.ExtendStakePeriod:\n intention = ExtendStakePeriodIntention.fromData(intentionData as ExtendStakePeriodIntentionData);\n break;\n case TransactionSubType.ExtendPeriodAndStakeMore:\n intention = ExtendPeriodAndStakeMoreIntention.fromData(intentionData as ExtendPeriodAndStakeMoreIntentionData);\n break;\n case TransactionSubType.RenewExpStakePeriod:\n intention = RenewExpStakePeriodIntention.fromData(intentionData as RenewExpStakePeriodIntentionData);\n break;\n case TransactionSubType.WithdrawStakedSca:\n intention = WithdrawStakedScaIntention.fromData(intentionData as WithdrawStakedScaIntentionData);\n break;\n case TransactionSubType.SupplyAndStakeLending:\n intention = SupplyAndStakeLendingIntention.fromData(intentionData as SupplyAndStakeLendingIntentionData);\n break;\n case TransactionSubType.WithdrawAndUnstakeLending:\n intention = WithdrawAndUnstakeLendingIntention.fromData(\n intentionData as WithdrawAndUnstakeLendingIntentionData,\n );\n break;\n case TransactionSubType.RedeemSca:\n intention = RedeemScaIntention.fromData(intentionData as RedeemScaIntentionData);\n break;\n case TransactionSubType.MigrateAndClaim:\n intention = MigrateAndClaimIntention.fromData(intentionData as MigrateAndClaimIntentionData);\n break;\n case TransactionSubType.BorrowWithReferral:\n intention = BorrowWithReferralIntention.fromData(intentionData as BorrowWithReferralIntentionData);\n break;\n case TransactionSubType.CreateReferralLink:\n intention = CreateReferralLinkIntention.fromData(intentionData as CreateReferralLinkIntentionData);\n break;\n case TransactionSubType.ClaimRevenueReferral:\n intention = ClaimRevenueReferralIntention.fromData(intentionData as ClaimRevenueReferralIntentionData);\n break;\n case TransactionSubType.BindReferral:\n intention = BindReferralIntention.fromData(intentionData as BindReferralIntentionData);\n break;\n case TransactionSubType.MigrateScoin:\n intention = MigrateScoinIntention.fromData(intentionData as MigrateScoinIntentionData);\n break;\n case TransactionSubType.RepayWithBoost:\n intention = RepayWithBoostIntention.fromData(intentionData as RepayWithBoostIntentionData);\n break;\n case TransactionSubType.MigrateWusdcToUsdc:\n intention = MigrateWusdcToUsdcIntention.fromData(intentionData as MigrateWusdcToUsdcIntentionData);\n break;\n default:\n throw new Error('not implemented');\n }\n return intention.build({ suiClient, account, network, scallop: this.scallop });\n }\n}\n","import { TransactionType } from '@msafe/sui3-utils';\nimport { MoveCallTransaction, SplitCoinsTransaction } from '@mysten/sui.js/dist/cjs/transactions';\n\nimport { Decoder } from './decoder';\nimport { OLD_BORROW_INCENTIVE_PROTOCOL_ID } from '../constants';\nimport { SupportBorrowIncentiveRewardCoins, SupportStakeMarketCoins } from '../types';\nimport { DecodeResult, TransactionSubType } from '../types/utils';\nimport { MoveCallHelper } from '../utils/moveCallHelper';\nimport { SplitCoinHelper } from '../utils/splitCoinHelper';\n\nexport class DecoderLending extends Decoder {\n decode() {\n if (this.isMoveAsset()) {\n return this.decodeMoveAsset();\n }\n if (this.isSupplyWithStakeSpoolTransaction()) {\n return this.decodeSupplyWithStakeSpool();\n }\n if (this.isUnstakeAndWithdrawTransaction()) {\n return this.decodeUnstakeAndWithdraw();\n }\n if (this.isStakeSpoolTransaction()) {\n return this.decodeStakeSpool();\n }\n if (this.isDepositCollateralTransaction()) {\n return this.decodeDepositCollateral();\n }\n if (this.isWithdrawCollateralTransaction()) {\n return this.decodeWithdrawCollateral();\n }\n if (this.isWithdrawLendingScoinTransaction()) {\n return this.decodeWithdrawLendingScoin();\n }\n if (this.isWithdrawLendingTransaction()) {\n return this.decodeWithdrawLending();\n }\n if (this.isSupplyLendingTransaction()) {\n return this.decodeSupplyLending();\n }\n if (this.isBorrowWithReferralTransaction()) {\n return this.decodeBorrowWithReferral();\n }\n if (this.isBorrowWithBoostTransaction()) {\n return this.decodeBorrowWithBoost();\n }\n if (this.isBorrowTransaction()) {\n return this.decodeBorrow();\n }\n if (this.isRepayWithBoostTransaction()) {\n return this.decodeRepayWithBoost();\n }\n if (this.isRepayTransaction()) {\n return this.decodeRepay();\n }\n if (this.isUnstakeSpoolTransaction()) {\n return this.decodeUnstakeSpool();\n }\n if (this.isClaimRewardTransaction()) {\n return this.decodeClaimReward();\n }\n if (this.isOpenObligationTransaction()) {\n return this.decodeOpenObligation();\n }\n if (this.isMigrateAndClaim()) {\n return this.decodeMigrateAndClaim();\n }\n if (this.isMigrateScoinTransaction()) {\n return this.decodeMigrateScoin();\n }\n return undefined;\n }\n\n private isMoveAsset() {\n return !!this.getMoveCallTransaction(\n '0x5857d185897aaff40ae37b2eecc895efc1a9dff1b210c4fb894eabbce4ac2603::slippage_check::check_slippage',\n );\n }\n\n private isMigrateScoinTransaction() {\n return !!this.getMoveCallTransaction(`${this.coreId.scoin}::s_coin_converter::mint_s_coin`);\n }\n\n private isSupplyLendingTransaction() {\n return !!this.getMoveCallTransaction(`${this.coreId.protocolPkg}::mint::mint`);\n }\n\n private isSupplyWithStakeSpoolTransaction() {\n const supplyMoveCall = this.getMoveCallTransaction(`${this.coreId.protocolPkg}::mint::mint`);\n const stakeMoveCall = this.getMoveCallTransaction(`${this.coreId.spoolPkg}::user::stake`);\n return !!supplyMoveCall && !!stakeMoveCall;\n }\n\n private isUnstakeAndWithdrawTransaction() {\n const unstakeMoveCall = this.getMoveCallTransaction(`${this.coreId.spoolPkg}::user::unstake`);\n const withdrawMoveCall = this.getMoveCallTransaction(`${this.coreId.protocolPkg}::redeem::redeem`);\n return !!unstakeMoveCall && !!withdrawMoveCall;\n }\n\n private isStakeSpoolTransaction() {\n return !!this.getMoveCallTransaction(`${this.coreId.spoolPkg}::user::stake`);\n }\n\n private isWithdrawLendingTransaction() {\n return !!this.getMoveCallTransaction(`${this.coreId.protocolPkg}::redeem::redeem`);\n }\n\n private isWithdrawLendingScoinTransaction() {\n const redeem = !!this.getMoveCallTransaction(`${this.coreId.protocolPkg}::redeem::redeem`);\n const burnScoin = !!this.getMoveCallTransaction(`${this.coreId.scoin}::s_coin_converter::burn_s_coin`);\n return !!redeem && !!burnScoin;\n }\n\n private isDepositCollateralTransaction() {\n return !!this.getMoveCallTransaction(`${this.coreId.protocolPkg}::deposit_collateral::deposit_collateral`);\n }\n\n private isWithdrawCollateralTransaction() {\n return !!this.getMoveCallTransaction(`${this.coreId.protocolPkg}::withdraw_collateral::withdraw_collateral`);\n }\n\n private isBorrowTransaction() {\n return !!this.getMoveCallTransaction(`${this.coreId.protocolPkg}::borrow::borrow`);\n }\n\n private isBorrowWithBoostTransaction() {\n const borrowMoveCall = this.getMoveCallTransaction(`${this.coreId.protocolPkg}::borrow::borrow`);\n const stakeMoveCall = this.getMoveCallTransaction(`${this.coreId.borrowIncentivePkg}::user::stake_with_ve_sca`);\n return !!borrowMoveCall && !!stakeMoveCall;\n }\n\n private isBorrowWithReferralTransaction() {\n const borrowWithReferral = this.getMoveCallTransaction(`${this.coreId.protocolPkg}::borrow::borrow_with_referral`);\n return !!borrowWithReferral;\n }\n\n private isRepayTransaction() {\n return !!this.getMoveCallTransaction(`${this.coreId.protocolPkg}::repay::repay`);\n }\n\n private isRepayWithBoostTransaction() {\n const repayMoveCall = !!this.getMoveCallTransaction(`${this.coreId.protocolPkg}::repay::repay`);\n const stakeMoveCall = this.getMoveCallTransaction(`${this.coreId.borrowIncentivePkg}::user::stake_with_ve_sca`);\n return !!repayMoveCall && !!stakeMoveCall;\n }\n\n private isUnstakeSpoolTransaction() {\n return !!this.getMoveCallTransaction(`${this.coreId.spoolPkg}::user::unstake`);\n }\n\n private isCreateStakeAccountTransaction() {\n return !!this.getMoveCallTransaction(`${this.coreId.spoolPkg}::user::new_spool_account`);\n }\n\n private isClaimRewardTransaction() {\n const lendingIncentive = this.getMoveCallTransaction(`${this.coreId.spoolPkg}::user::redeem_rewards`);\n const borrowIncentiveV2 = this.getMoveCallTransaction(`${this.coreId.borrowIncentivePkg}::user::redeem_rewards`);\n return !!lendingIncentive || !!borrowIncentiveV2;\n }\n\n private isOpenObligationTransaction() {\n return !!this.getMoveCallTransaction(`${this.coreId.protocolPkg}::open_obligation::open_obligation`);\n }\n\n private isMigrateAndClaim() {\n const oldBorrowIncentive = this.getMoveCallTransaction(`${OLD_BORROW_INCENTIVE_PROTOCOL_ID}::user::redeem_rewards`);\n const stakeWithVeSca = this.getMoveCallTransaction(`${this.coreId.borrowIncentivePkg}::user::stake_with_ve_sca`);\n const stakeWithoutVesca = this.getMoveCallTransaction(`${this.coreId.borrowIncentivePkg}::user::stake`);\n return !!oldBorrowIncentive && (!!stakeWithVeSca || !!stakeWithoutVesca);\n }\n\n private get helperClaimLendingReward() {\n const moveCalls = this.transactions\n .filter(\n (trans) =>\n trans.kind === 'MoveCall' && trans.target.startsWith(`${this.coreId.spoolPkg}::user::redeem_rewards`),\n )\n .map((trans) => new MoveCallHelper(trans as MoveCallTransaction, this.txb));\n return moveCalls;\n }\n\n private get helperClaimBorrowV2Reward() {\n const moveCalls = this.transactions\n .filter(\n (trans) =>\n trans.kind === 'MoveCall' &&\n trans.target.startsWith(`${this.coreId.borrowIncentivePkg}::user::redeem_rewards`),\n )\n .map((trans) => new MoveCallHelper(trans as MoveCallTransaction, this.txb));\n return moveCalls;\n }\n\n private get helperStakeObligationWithVeSca() {\n const moveCall = this.transactions.find(\n (trans) =>\n trans.kind === 'MoveCall' &&\n trans.target.startsWith(`${this.coreId.borrowIncentivePkg}::user::stake_with_ve_sca`),\n ) as MoveCallTransaction;\n return new MoveCallHelper(moveCall, this.txb);\n }\n\n private get helperClaimBorrowReward() {\n const moveCalls = this.transactions\n .filter(\n (trans) =>\n trans.kind === 'MoveCall' &&\n trans.target.startsWith(`${OLD_BORROW_INCENTIVE_PROTOCOL_ID}::user::redeem_rewards`),\n )\n .map((trans) => new MoveCallHelper(trans as MoveCallTransaction, this.txb));\n return moveCalls;\n }\n\n private get helperMint() {\n const moveCall = this.transactions.find(\n (trans) => trans.kind === 'MoveCall' && trans.target.startsWith(`${this.coreId.protocolPkg}::mint::mint`),\n ) as MoveCallTransaction;\n return new MoveCallHelper(moveCall, this.txb);\n }\n\n private get helperUnstakes() {\n const moveCalls = this.transactions\n .filter((trans) => trans.kind === 'MoveCall' && trans.target.startsWith(`${this.coreId.spoolPkg}::user::unstake`))\n .map((trans) => new MoveCallHelper(trans as MoveCallTransaction, this.txb));\n return moveCalls;\n }\n\n private get helperRedeems() {\n const moveCalls = this.transactions\n .filter(\n (trans) => trans.kind === 'MoveCall' && trans.target.startsWith(`${this.coreId.protocolPkg}::redeem::redeem`),\n )\n .map((trans) => new MoveCallHelper(trans as MoveCallTransaction, this.txb));\n return moveCalls;\n }\n\n private get helperRedeem() {\n const moveCall = this.transactions.find(\n (trans) => trans.kind === 'MoveCall' && trans.target.startsWith(`${this.coreId.protocolPkg}::redeem::redeem`),\n ) as MoveCallTransaction;\n return new MoveCallHelper(moveCall, this.txb);\n }\n\n private get helperBurnScoin() {\n const moveCall = this.transactions.find(\n (trans) =>\n trans.kind === 'MoveCall' && trans.target.startsWith(`${this.coreId.scoin}::s_coin_converter::burn_s_coin`),\n ) as MoveCallTransaction;\n return new MoveCallHelper(moveCall, this.txb);\n }\n\n private get helperSlippage() {\n const moveCall = this.transactions.find(\n (trans) =>\n trans.kind === 'MoveCall' &&\n trans.target.startsWith(\n `0x5857d185897aaff40ae37b2eecc895efc1a9dff1b210c4fb894eabbce4ac2603::slippage_check::check_slippage`,\n ),\n ) as MoveCallTransaction;\n return new MoveCallHelper(moveCall, this.txb);\n }\n\n private get helperStake() {\n const moveCall = this.transactions.find(\n (trans) => trans.kind === 'MoveCall' && trans.target.startsWith(`${this.coreId.spoolPkg}::user::stake`),\n ) as MoveCallTransaction;\n return new MoveCallHelper(moveCall, this.txb);\n }\n\n private get helperUnstake() {\n const moveCall = this.transactions.find(\n (trans) => trans.kind === 'MoveCall' && trans.target.startsWith(`${this.coreId.spoolPkg}::user::unstake`),\n ) as MoveCallTransaction;\n return new MoveCallHelper(moveCall, this.txb);\n }\n\n private get helperDepositCollateral() {\n const moveCall = this.transactions.find(\n (trans) =>\n trans.kind === 'MoveCall' &&\n trans.target.startsWith(`${this.coreId.protocolPkg}::deposit_collateral::deposit_collateral`),\n ) as MoveCallTransaction;\n return new MoveCallHelper(moveCall, this.txb);\n }\n\n private get helperWithdrawCollateral() {\n const moveCall = this.transactions.find(\n (trans) =>\n trans.kind === 'MoveCall' &&\n trans.target.startsWith(`${this.coreId.protocolPkg}::withdraw_collateral::withdraw_collateral`),\n ) as MoveCallTransaction;\n return new MoveCallHelper(moveCall, this.txb);\n }\n\n private get helperBorrow() {\n const moveCall = this.transactions.find(\n (trans) => trans.kind === 'MoveCall' && trans.target.startsWith(`${this.coreId.protocolPkg}::borrow::borrow`),\n ) as MoveCallTransaction;\n return new MoveCallHelper(moveCall, this.txb);\n }\n\n private get helperBorrowWithReferral() {\n const moveCall = this.transactions.find(\n (trans) =>\n trans.kind === 'MoveCall' &&\n trans.target.startsWith(`${this.coreId.protocolPkg}::borrow::borrow_with_referral`),\n ) as MoveCallTransaction;\n return new MoveCallHelper(moveCall, this.txb);\n }\n\n private get helperRepay() {\n const moveCall = this.transactions.find(\n (trans) => trans.kind === 'MoveCall' && trans.target.startsWith(`${this.coreId.protocolPkg}::repay::repay`),\n ) as MoveCallTransaction;\n return new MoveCallHelper(moveCall, this.txb);\n }\n\n private decodeMigrateScoin(): DecodeResult {\n return {\n txType: TransactionType.Other,\n type: TransactionSubType.MigrateScoin,\n intentionData: {},\n };\n }\n\n private decodeMigrateAndClaim(): DecodeResult {\n let veScaKey;\n if (this.helperStakeObligationWithVeSca.moveCall) {\n veScaKey = this.helperStakeObligationWithVeSca.decodeOwnedObjectId(9);\n }\n const obligationKey = this.helperClaimBorrowReward[0].decodeOwnedObjectId(2);\n const obligationId = this.helperClaimBorrowReward[0].decodeSharedObjectId(3);\n const rewardCoinName = this.scallop.utils.parseCoinNameFromType(\n this.helperClaimBorrowReward[0].typeArg(0),\n ) as SupportBorrowIncentiveRewardCoins;\n return {\n txType: TransactionType.Other,\n type: TransactionSubType.MigrateAndClaim,\n intentionData: {\n obligationKey,\n obligationId,\n rewardCoinName,\n veScaKey,\n },\n };\n }\n\n private decodeOpenObligation(): DecodeResult {\n return {\n txType: TransactionType.Other,\n type: TransactionSubType.OpenObligation,\n intentionData: {},\n };\n }\n\n private decodeSupplyLending(): DecodeResult {\n const coinName = this.scallop.utils.parseCoinNameFromType(this.helperMint.typeArg(0));\n const amount = this.helperMint.getNestedInputParam<SplitCoinsTransaction>(2);\n const amountFromSplitCoin = new SplitCoinHelper(amount, this.txb).getAmountInput().reduce((a, b) => a + b, 0);\n return {\n txType: TransactionType.Other,\n type: TransactionSubType.SupplyLending,\n intentionData: {\n amount: amountFromSplitCoin,\n coinName,\n },\n };\n }\n\n private decodeWithdrawLending(): DecodeResult {\n const coinName = this.scallop.utils.parseCoinNameFromType(this.helperRedeem.typeArg(0));\n const amount = this.helperRedeem.getNestedInputParam<SplitCoinsTransaction>(2);\n const amountFromSplitCoin = new SplitCoinHelper(amount, this.txb).getAmountInput().reduce((a, b) => a + b, 0);\n return {\n txType: TransactionType.Other,\n type: TransactionSubType.WithdrawLending,\n intentionData: {\n amount: amountFromSplitCoin,\n coinName,\n },\n };\n }\n\n private decodeWithdrawLendingScoin(): DecodeResult {\n const coinName = this.scallop.utils.parseCoinNameFromType(this.helperRedeem.typeArg(0));\n const amount = this.helperBurnScoin.getNestedInputParam<SplitCoinsTransaction>(1);\n const amountFromSplitCoin = new SplitCoinHelper(amount, this.txb).getAmountInput().reduce((a, b) => a + b, 0);\n return {\n txType: TransactionType.Other,\n type: TransactionSubType.WithdrawLending,\n intentionData: {\n amount: amountFromSplitCoin,\n coinName,\n },\n };\n }\n\n private decodeDepositCollateral(): DecodeResult {\n const coinName = this.scallop.utils.parseCoinNameFromType(this.helperDepositCollateral.typeArg(0));\n const amount = this.helperDepositCollateral.getNestedInputParam<SplitCoinsTransaction>(3);\n const amountFromSplitCoin = new SplitCoinHelper(amount, this.txb).getAmountInput().reduce((a, b) => a + b, 0);\n const obligationId = this.helperDepositCollateral.decodeSharedObjectId(1);\n return {\n txType: TransactionType.Other,\n type: TransactionSubType.DepositCollateral,\n intentionData: {\n amount: amountFromSplitCoin,\n obligationId,\n collateralCoinName: coinName,\n },\n };\n }\n\n private decodeWithdrawCollateral(): DecodeResult {\n const coinName = this.scallop.utils.parseCoinNameFromType(this.helperWithdrawCollateral.typeArg(0));\n const amount = this.helperWithdrawCollateral.decodeInputU64(5);\n const obligationId = this.helperWithdrawCollateral.decodeSharedObjectId(1);\n const obligationKey = this.helperWithdrawCollateral.decodeOwnedObjectId(2);\n return {\n txType: TransactionType.Other,\n type: TransactionSubType.WithdrawCollateral,\n intentionData: {\n amount,\n collateralCoinName: coinName,\n obligationKey,\n obligationId,\n },\n };\n }\n\n private decodeBorrow(): DecodeResult {\n const coinName = this.scallop.utils.parseCoinNameFromType(this.helperBorrow.typeArg(0));\n const amount = this.helperBorrow.decodeInputU64(5);\n const obligationId = this.helperBorrow.decodeSharedObjectId(1);\n const obligationKey = this.helperBorrow.decodeOwnedObjectId(2);\n return {\n txType: TransactionType.Other,\n type: TransactionSubType.Borrow,\n intentionData: {\n amount,\n coinName,\n obligationKey,\n obligationId,\n },\n };\n }\n\n private decodeBorrowWithBoost(): DecodeResult {\n const coinName = this.scallop.utils.parseCoinNameFromType(this.helperBorrow.typeArg(0));\n const veScaKey = this.helperStakeObligationWithVeSca.decodeOwnedObjectId(9);\n const amount = this.helperBorrow.decodeInputU64(5);\n const obligationId = this.helperBorrow.decodeSharedObjectId(1);\n const obligationKey = this.helperBorrow.decodeOwnedObjectId(2);\n return {\n txType: TransactionType.Other,\n type: TransactionSubType.BorrowWithBoost,\n intentionData: {\n amount,\n coinName,\n obligationKey,\n obligationId,\n veScaKey,\n },\n };\n }\n\n private decodeBorrowWithReferral(): DecodeResult {\n const coinName = this.scallop.utils.parseCoinNameFromType(this.helperBorrowWithReferral.typeArg(0));\n let veScaKey;\n if (this.helperStakeObligationWithVeSca.moveCall) {\n veScaKey = this.helperStakeObligationWithVeSca.decodeOwnedObjectId(9);\n }\n const amount = this.helperBorrowWithReferral.decodeInputU64(6);\n const obligationId = this.helperBorrowWithReferral.decodeSharedObjectId(1);\n const obligationKey = this.helperBorrowWithReferral.decodeOwnedObjectId(2);\n return {\n txType: TransactionType.Other,\n type: TransactionSubType.BorrowWithReferral,\n intentionData: {\n amount,\n coinName,\n obligationKey,\n obligationId,\n veScaKey,\n },\n };\n }\n\n private decodeRepay(): DecodeResult {\n const coinName = this.scallop.utils.parseCoinNameFromType(this.helperRepay.typeArg(0));\n const amount = this.helperRepay.getNestedInputParam<SplitCoinsTransaction>(3);\n const amountFromSplitCoin = new SplitCoinHelper(amount, this.txb).getAmountInput().reduce((a, b) => a + b, 0);\n const obligationId = this.helperRepay.decodeSharedObjectId(1);\n return {\n txType: TransactionType.Other,\n type: TransactionSubType.Repay,\n intentionData: {\n amount: amountFromSplitCoin,\n obligationId,\n coinName,\n },\n };\n }\n\n private decodeRepayWithBoost(): DecodeResult {\n const coinName = this.scallop.utils.parseCoinNameFromType(this.helperRepay.typeArg(0));\n const veScaKey = this.helperStakeObligationWithVeSca.decodeOwnedObjectId(9);\n const amount = this.helperRepay.getNestedInputParam<SplitCoinsTransaction>(3);\n const amountFromSplitCoin = new SplitCoinHelper(amount, this.txb).getAmountInput().reduce((a, b) => a + b, 0);\n const obligationId = this.helperRepay.decodeSharedObjectId(1);\n return {\n txType: TransactionType.Other,\n type: TransactionSubType.RepayWithBoost,\n intentionData: {\n amount: amountFromSplitCoin,\n obligationId,\n coinName,\n veScaKey,\n },\n };\n }\n\n private decodeStakeSpool(): DecodeResult {\n let stakeSpoolAccount;\n if (!this.isCreateStakeAccountTransaction()) {\n stakeSpoolAccount = this.helperStake.decodeOwnedObjectId(1);\n }\n let amountFromSplitCoin = 0;\n if (this.helperBurnScoin.moveCall) {\n const amount = this.helperBurnScoin.getNestedInputParam<SplitCoinsTransaction>(1);\n amountFromSplitCoin = new SplitCoinHelper(amount, this.txb).getAmountInput().reduce((a, b) => a + b, 0);\n }\n if (this.helperStake.moveCall && amountFromSplitCoin === 0) {\n const amount = this.helperStake.getNestedInputParam<SplitCoinsTransaction>(2);\n amountFromSplitCoin = new SplitCoinHelper(amount, this.txb).getAmountInput().reduce((a, b) => a + b, 0);\n }\n const coinType = this.helperStake.typeArg(0);\n const coinName = this.scallop.utils.parseCoinNameFromType(coinType);\n return {\n txType: TransactionType.Other,\n type: TransactionSubType.StakeSpool,\n intentionData: {\n amount: amountFromSplitCoin,\n marketCoinName: coinName,\n stakeAccountId: stakeSpoolAccount,\n },\n };\n }\n\n private decodeUnstakeSpool(): DecodeResult {\n const stakeSpoolAccount = this.helperUnstake.decodeOwnedObjectId(1);\n const amount = this.helperUnstake.decodeInputU64(2);\n const coinType = this.helperUnstake.typeArg(0);\n const coinName = this.scallop.utils.parseCoinNameFromType(coinType);\n return {\n txType: TransactionType.Other,\n type: TransactionSubType.UnstakeSpool,\n intentionData: {\n amount,\n marketCoinName: coinName,\n stakeAccountId: stakeSpoolAccount,\n },\n };\n }\n\n private decodeSupplyWithStakeSpool(): DecodeResult {\n const coinName = this.scallop.utils.parseCoinNameFromType(this.helperMint.typeArg(0));\n const amount = this.helperMint.getNestedInputParam<SplitCoinsTransaction>(2);\n const amountFromSplitCoin = new SplitCoinHelper(amount, this.txb).getAmountInput().reduce((a, b) => a + b, 0);\n let stakeSpoolAccount;\n if (!this.isCreateStakeAccountTransaction()) {\n stakeSpoolAccount = this.helperStake.decodeOwnedObjectId(1);\n }\n return {\n txType: TransactionType.Other,\n type: TransactionSubType.SupplyAndStakeLending,\n intentionData: {\n amount: amountFromSplitCoin,\n coinName,\n stakeAccountId: stakeSpoolAccount,\n },\n };\n }\n\n private decodeUnstakeAndWithdraw(): DecodeResult {\n const stakeAccountWithAmount: { id: string; coin: number }[] = [];\n this.helperUnstakes.forEach((tx) => {\n const stakeAccountId = tx.decodeOwnedObjectId(1);\n const amount = tx.decodeInputU64(2);\n stakeAccountWithAmount.push({ id: stakeAccountId, coin: amount });\n });\n const coinName = this.scallop.utils.parseCoinNameFromType(this.helperRedeems[0].typeArg(0));\n let amountFromSplitCoin = 0;\n if (this.helperBurnScoin.moveCall) {\n const amount = this.helperBurnScoin.getNestedInputParam<SplitCoinsTransaction>(1);\n amountFromSplitCoin = new SplitCoinHelper(amount, this.txb).getAmountInput().reduce((a, b) => a + b, 0);\n }\n return {\n txType: TransactionType.Other,\n type: TransactionSubType.WithdrawAndUnstakeLending,\n intentionData: {\n amount: amountFromSplitCoin,\n coinName,\n stakeAccountId: stakeAccountWithAmount,\n },\n };\n }\n\n private decodeMoveAsset(): DecodeResult {\n const stakeAccountWithAmount: { id: string; coin: number }[] = [];\n this.helperUnstakes.forEach((tx) => {\n const stakeAccountId = tx.decodeOwnedObjectId(1);\n const amount = tx.decodeInputU64(2);\n stakeAccountWithAmount.push({ id: stakeAccountId, coin: amount });\n });\n const coinName = this.scallop.utils.parseCoinNameFromType(this.helperRedeems[0].typeArg(0));\n let amountFromSplitCoin = 0;\n if (this.helperBurnScoin.moveCall) {\n const amount = this.helperBurnScoin.getNestedInputParam<SplitCoinsTransaction>(1);\n amountFromSplitCoin = new SplitCoinHelper(amount, this.txb).getAmountInput().reduce((a, b) => a + b, 0);\n }\n const slippage = this.helperSlippage.decodePureArg(1, 'u64');\n const validSwapAmount = this.helperSlippage.decodePureArg(2, 'string');\n\n return {\n txType: TransactionType.Other,\n type: TransactionSubType.MigrateWusdcToUsdc,\n intentionData: {\n amount: amountFromSplitCoin,\n coinName,\n slippage,\n validSwapAmount,\n stakeAccountId: stakeAccountWithAmount,\n },\n };\n }\n\n private decodeClaimReward(): DecodeResult {\n const lendingReward: {\n stakeMarketCoinName: SupportStakeMarketCoins;\n stakeAccountId: string;\n }[] = [];\n const borrowRewardV2: {\n obligationId: string;\n obligationKey: string;\n rewardCoinName: SupportBorrowIncentiveRewardCoins;\n }[] = [];\n\n const borrowReward: {\n obligationId: string;\n obligationKey: string;\n rewardCoinName: SupportBorrowIncentiveRewardCoins;\n }[] = [];\n\n this.helperClaimLendingReward.forEach((tx) => {\n const stakeAccountId = tx.decodeOwnedObjectId(2);\n const stakeMarketCoinName = tx.typeArg(0);\n const coinName = this.scallop.utils.parseCoinNameFromType(stakeMarketCoinName);\n lendingReward.push({ stakeMarketCoinName: coinName as SupportStakeMarketCoins, stakeAccountId });\n });\n\n this.helperClaimBorrowV2Reward.forEach((tx) => {\n const obligationKey = tx.decodeSharedObjectId(3);\n const obligationId = tx.decodeOwnedObjectId(4);\n const rewardCoinName = this.scallop.utils.parseCoinNameFromType(\n tx.typeArg(0),\n ) as SupportBorrowIncentiveRewardCoins;\n borrowRewardV2.push({ obligationId, obligationKey, rewardCoinName });\n });\n\n this.helperClaimBorrowReward.forEach((tx) => {\n const obligationKey = tx.decodeSharedObjectId(2);\n const obligationId = tx.decodeOwnedObjectId(3);\n const rewardCoinName = this.scallop.utils.parseCoinNameFromType(\n tx.typeArg(0),\n ) as SupportBorrowIncentiveRewardCoins;\n borrowReward.push({ obligationId, obligationKey, rewardCoinName });\n });\n\n return {\n txType: TransactionType.Other,\n type: TransactionSubType.ClaimIncentiveReward,\n intentionData: {\n lendingIncentive: lendingReward,\n borrowIncentiveV2: borrowRewardV2,\n borrowIncentive: borrowReward,\n },\n };\n }\n}\n","import { TransactionBlock } from '@mysten/sui.js/dist/cjs/transactions';\n\nimport { Scallop } from '../models';\n\nexport class Decoder {\n protected scallop: Scallop;\n\n constructor(\n public readonly txb: TransactionBlock,\n scallop: Scallop,\n ) {\n this.scallop = scallop;\n }\n\n protected get coreId() {\n return {\n protocolPkg: this.scallop.address.get('core.packages.protocol.id'),\n market: this.scallop.address.get('core.market'),\n version: this.scallop.address.get('core.version'),\n coinDecimalsRegistry: this.scallop.address.get('core.coinDecimalsRegistry'),\n xOracle: this.scallop.address.get('core.oracles.xOracle'),\n spoolPkg: this.scallop.address.get('spool.id'),\n borrowIncentivePkg: this.scallop.address.get('borrowIncentive.id'),\n veScaPkgId: this.scallop.address.get('vesca.id'),\n scoin: this.scallop.address.get('scoin.id'),\n referral: this.scallop.address.get('referral.id'),\n };\n }\n\n protected get transactions() {\n return this.txb.blockData.transactions;\n }\n\n protected get inputTransaction() {\n return this.txb.blockData.inputs;\n }\n\n protected getMoveCallTransaction(target: string) {\n return this.transactions.find((trans) => trans.kind === 'MoveCall' && trans.target === target);\n }\n}\n","// export const API_BASE_URL = 'https://sui.api.scallop.io';\nexport const API_BASE_URL = 'https://sui.apis.scallop.io';\nexport const SDK_API_BASE_URL = 'https://sdk.api.scallop.io';\n\nexport const IS_VE_SCA_TEST = false;\nexport const USE_TEST_ADDRESS = false;\n\n// export const ADDRESSES_ID = '';\nexport const ADDRESSES_ID =\n IS_VE_SCA_TEST || USE_TEST_ADDRESS ? ('65fb07c39c845425d71d7b18' as const) : ('66f8e7ed9bb9e07fdfb86bbb' as const);\n// : ('6601955b8b0024600a917079' as const);\n// : ('6462a088a7ace142bb6d7e9b' as const);\n\nexport const PROTOCOL_OBJECT_ID = IS_VE_SCA_TEST\n ? ('0xc9f859f98ca352a11b97a038c4b4162bee437b8df8caa047990fe9cb03d4f778' as const)\n : ('0xefe8b36d5b2e43728cc323298626b83177803521d195cfb11e15b910e892fddf' as const);\n// export const PROTOCOL_OBJECT_ID =\n// '0x87ddec2984645dbbe2403a509cc6edf393a43acdba9b77d45da2bcbefcf733c1' as const;\n\nexport const BORROW_FEE_PROTOCOL_ID = IS_VE_SCA_TEST\n ? ('0xc9f859f98ca352a11b97a038c4b4162bee437b8df8caa047990fe9cb03d4f778' as const) // test environment\n : ('0xc38f849e81cfe46d4e4320f508ea7dda42934a329d5a6571bb4c3cb6ea63f5da' as const);\n// export const BORROW_FEE_PROTOCOL_ID =\n// '0x87ddec2984645dbbe2403a509cc6edf393a43acdba9b77d45da2bcbefcf733c1' as const;\n\nexport const SCA_COIN_TYPE = IS_VE_SCA_TEST\n ? (`0x6cd813061a3adf3602b76545f076205f0c8e7ec1d3b1eab9a1da7992c18c0524::sca::SCA` as const)\n : ('0x7016aae72cfc67f2fadf55769c0a7dd54291a583b63051a5ed71081cce836ac6::sca::SCA' as const);\n\nexport const OLD_BORROW_INCENTIVE_PROTOCOL_ID =\n '0xc63072e7f5f4983a2efaf5bdba1480d5e7d74d57948e1c7cc436f8e22cbeb410' as const;\n\nexport const SUPPORT_POOLS = [\n 'weth',\n 'wbtc',\n 'wusdc',\n 'wusdt',\n 'sui',\n 'wapt',\n 'wsol',\n 'cetus',\n 'afsui',\n 'hasui',\n 'vsui',\n 'sca',\n 'usdc',\n] as const;\n\nexport const SUPPORT_COLLATERALS = [\n 'weth',\n 'wbtc',\n 'wusdc',\n 'wusdt',\n 'sui',\n 'wapt',\n 'wsol',\n 'cetus',\n 'afsui',\n 'hasui',\n 'vsui',\n 'sca',\n 'usdc',\n] as const;\n\nexport const SUPPORT_SPOOLS = [\n 'sweth',\n 'ssui',\n 'swusdc',\n 'swusdt',\n 'scetus',\n 'safsui',\n 'shasui',\n 'svsui',\n 'susdc',\n] as const;\n\nexport const SUPPORT_SCOIN = [\n 'ssui',\n 'swusdc',\n 'swusdt',\n 'safsui',\n 'shasui',\n 'svsui',\n 'sweth',\n 'ssca',\n 'scetus',\n 'swbtc',\n 'swsol',\n 'susdc',\n] as const;\n\nexport const UNSUPPORT_SCOIN = ['btc', 'sol'] as const;\n\nexport const SUPPORT_SPOOLS_REWARDS = ['sui'] as const;\n\nexport const SUPPORT_BORROW_INCENTIVE_POOLS = [\n 'sui',\n 'wusdc',\n 'wusdt',\n 'afsui',\n 'hasui',\n 'vsui',\n 'weth',\n 'sca',\n 'wbtc',\n 'wsol',\n 'usdc',\n] as const;\n\nexport const SUPPORT_BORROW_INCENTIVE_REWARDS = ['sui', 'sca'] as const;\nexport const SUPPORT_ORACLES = ['supra', 'switchboard', 'pyth'] as const;\n\nexport const SUPPORT_PACKAGES = [\n 'coinDecimalsRegistry',\n 'math',\n 'whitelist',\n 'x',\n 'protocol',\n 'protocolWhitelist',\n 'query',\n 'supra',\n 'pyth',\n 'switchboard',\n 'xOracle',\n 'testCoin',\n] as const;\n","import type {\n SupportCoinDecimals,\n AssetCoins,\n MarketCoins,\n StakeMarketCoins,\n StakeRewardCoins,\n BorrowIncentiveRewardCoins,\n AssetCoinIds,\n WormholeCoinIds,\n VoloCoinIds,\n SCoinIds,\n} from '../types';\n\nexport const coinDecimals: SupportCoinDecimals = {\n weth: 8,\n wbtc: 8,\n wusdc: 6,\n usdc: 6,\n wusdt: 6,\n sui: 9,\n wapt: 8,\n wsol: 8,\n sca: 9,\n cetus: 9,\n afsui: 9,\n hasui: 9,\n vsui: 9,\n sweth: 8,\n swbtc: 8,\n susdc: 6,\n swusdt: 6,\n swusdc: 6,\n ssui: 9,\n swapt: 8,\n swsol: 8,\n scetus: 9,\n safsui: 9,\n shasui: 9,\n svsui: 9,\n ssca: 9,\n};\n\nexport const assetCoins: AssetCoins = {\n weth: 'weth',\n wbtc: 'wbtc',\n wusdc: 'wusdc',\n usdc: 'usdc',\n wusdt: 'wusdt',\n sui: 'sui',\n wapt: 'wapt',\n wsol: 'wsol',\n cetus: 'cetus',\n afsui: 'afsui',\n hasui: 'hasui',\n vsui: 'vsui',\n sca: 'sca',\n};\n\nexport const marketCoins: MarketCoins = {\n sweth: 'sweth',\n swbtc: 'swbtc',\n swusdc: 'swusdc',\n swusdt: 'swusdt',\n ssui: 'ssui',\n swapt: 'swapt',\n swsol: 'swsol',\n scetus: 'scetus',\n safsui: 'safsui',\n shasui: 'shasui',\n svsui: 'svsui',\n ssca: 'ssca',\n susdc: 'susdc',\n};\n\nexport const stakeMarketCoins: StakeMarketCoins = {\n sweth: 'sweth',\n ssui: 'ssui',\n susdc: 'susdc',\n swusdt: 'swusdt',\n swusdc: 'swusdc',\n scetus: 'scetus',\n safsui: 'safsui',\n shasui: 'shasui',\n svsui: 'svsui',\n};\n\nexport const spoolRewardCoins: StakeRewardCoins = {\n sweth: 'sui',\n ssui: 'sui',\n swusdc: 'sui',\n swusdt: 'sui',\n scetus: 'sui',\n safsui: 'sui',\n shasui: 'sui',\n svsui: 'sui',\n susdc: 'sui',\n};\n\nexport const borrowIncentiveRewardCoins: BorrowIncentiveRewardCoins = {\n sui: ['sui', 'sca'],\n wusdc: ['sui', 'sca'],\n wusdt: ['sui', 'sca'],\n afsui: ['sui', 'sca'],\n hasui: ['sui', 'sca'],\n vsui: ['sui', 'sca'],\n sca: ['sui', 'sca'],\n weth: ['sui', 'sca'],\n wbtc: ['sui', 'sca'],\n wsol: ['sui', 'sca'],\n usdc: ['sui', 'sca'],\n};\n\nexport const coinIds: AssetCoinIds = {\n sui: '0x0000000000000000000000000000000000000000000000000000000000000002',\n weth: '0xaf8cd5edc19c4512f4259f0bee101a40d41ebed738ade5874359610ef8eeced5',\n wbtc: '0x027792d9fed7f9844eb4839566001bb6f6cb4804f66aa2da6fe1ee242d896881',\n wusdc: '0x5d4b302506645c37ff133b98c4b50a5ae14841659738d6d733d59d0d217a93bf',\n wusdt: '0xc060006111016b8a020ad5b33834984a437aaa7d3c74c18e09a95d48aceab08c',\n wapt: '0x3a5143bb1196e3bcdfab6203d1683ae29edd26294fc8bfeafe4aaa9d2704df37',\n wsol: '0xb7844e289a8410e50fb3ca48d69eb9cf29e27d223ef90353fe1bd8e27ff8f3f8',\n cetus: '0x06864a6f921804860930db6ddbe2e16acdf8504495ea7481637a1c8b9a8fe54b',\n afsui: '0xf325ce1300e8dac124071d3152c5c5ee6174914f8bc2161e88329cf579246efc',\n hasui: '0xbde4ba4c2e274a60ce15c1cfff9e5c42e41654ac8b6d906a57efa4bd3c29f47d',\n vsui: '0x549e8b69270defbfafd4f94e17ec44cdbdd99820b33bda2278dea3b9a32d3f55',\n sca: '0x7016aae72cfc67f2fadf55769c0a7dd54291a583b63051a5ed71081cce836ac6',\n usdc: '0xdba34672e30cb065b1f93e3ab55318768fd6fef66c15942c9f7cb846e2f900e7',\n};\n\nexport const wormholeCoinIds: WormholeCoinIds = {\n weth: '0xaf8cd5edc19c4512f4259f0bee101a40d41ebed738ade5874359610ef8eeced5',\n wbtc: '0x027792d9fed7f9844eb4839566001bb6f6cb4804f66aa2da6fe1ee242d896881',\n wusdc: '0x5d4b302506645c37ff133b98c4b50a5ae14841659738d6d733d59d0d217a93bf',\n wusdt: '0xc060006111016b8a020ad5b33834984a437aaa7d3c74c18e09a95d48aceab08c',\n wapt: '0x3a5143bb1196e3bcdfab6203d1683ae29edd26294fc8bfeafe4aaa9d2704df37',\n wsol: '0xb7844e289a8410e50fb3ca48d69eb9cf29e27d223ef90353fe1bd8e27ff8f3f8',\n};\n\nexport const voloCoinIds: VoloCoinIds = {\n vsui: '0x549e8b69270defbfafd4f94e17ec44cdbdd99820b33bda2278dea3b9a32d3f55',\n};\n\n// PROD VERSION\nexport const sCoinIds: SCoinIds = {\n ssui: '0xaafc4f740de0dd0dde642a31148fb94517087052f19afb0f7bed1dc41a50c77b::scallop_sui::SCALLOP_SUI',\n scetus: '0xea346ce428f91ab007210443efcea5f5cdbbb3aae7e9affc0ca93f9203c31f0c::scallop_cetus::SCALLOP_CETUS',\n ssca: '0x5ca17430c1d046fae9edeaa8fd76c7b4193a00d764a0ecfa9418d733ad27bc1e::scallop_sca::SCALLOP_SCA',\n swusdc:\n '0xad4d71551d31092230db1fd482008ea42867dbf27b286e9c70a79d2a6191d58d::scallop_wormhole_usdc::SCALLOP_WORMHOLE_USDC',\n swusdt:\n '0xe6e5a012ec20a49a3d1d57bd2b67140b96cd4d3400b9d79e541f7bdbab661f95::scallop_wormhole_usdt::SCALLOP_WORMHOLE_USDT',\n sweth:\n '0x67540ceb850d418679e69f1fb6b2093d6df78a2a699ffc733f7646096d552e9b::scallop_wormhole_eth::SCALLOP_WORMHOLE_ETH',\n safsui: '0x00671b1fa2a124f5be8bdae8b91ee711462c5d9e31bda232e70fd9607b523c88::scallop_af_sui::SCALLOP_AF_SUI',\n shasui: '0x9a2376943f7d22f88087c259c5889925f332ca4347e669dc37d54c2bf651af3c::scallop_ha_sui::SCALLOP_HA_SUI',\n svsui: '0xe1a1cc6bcf0001a015eab84bcc6713393ce20535f55b8b6f35c142e057a25fbe::scallop_v_sui::SCALLOP_V_SUI',\n swbtc:\n '0x2cf76a9cf5d3337961d1154283234f94da2dcff18544dfe5cbdef65f319591b5::scallop_wormhole_btc::SCALLOP_WORMHOLE_BTC',\n swsol:\n '0x1392650f2eca9e3f6ffae3ff89e42a3590d7102b80e2b430f674730bc30d3259::scallop_wormhole_sol::SCALLOP_WORMHOLE_SOL',\n susdc: '0x854950aa624b1df59fe64e630b2ba7c550642e9342267a33061d59fb31582da5::scallop_usdc::SCALLOP_USDC',\n} as const;\n","import { bcs } from '@mysten/sui.js/bcs';\nimport { MoveCallTransaction, TransactionBlock, TransactionBlockInput } from '@mysten/sui.js/dist/cjs/transactions';\nimport { normalizeStructTag, normalizeSuiAddress } from '@mysten/sui.js/utils';\n\nexport class MoveCallHelper {\n constructor(\n public readonly moveCall: MoveCallTransaction,\n public readonly txb: TransactionBlock,\n ) {}\n\n decodeSharedObjectId(argIndex: number) {\n const input = this.getInputParam(argIndex);\n return MoveCallHelper.getSharedObjectId(input);\n }\n\n decodeOwnedObjectId(argIndex: number) {\n const input = this.getInputParam(argIndex);\n return MoveCallHelper.getOwnedObjectId(input);\n }\n\n decodeInputU64(argIndex: number) {\n const strVal = this.decodePureArg<string>(argIndex, 'u64');\n return Number(strVal);\n }\n\n decodeInputU8(argIndex: number) {\n const strVal = this.decodePureArg<string>(argIndex, 'u8');\n return Number(strVal);\n }\n\n decodeInputAddress(argIndex: number) {\n const input = this.decodePureArg<string>(argIndex, 'address');\n return normalizeSuiAddress(input);\n }\n\n decodeInputString(argIndex: number) {\n return this.decodePureArg<string>(argIndex, 'string');\n }\n\n decodeInputBool(argIndex: number) {\n return this.decodePureArg<boolean>(argIndex, 'bool');\n }\n\n decodePureArg<T>(argIndex: number, bcsType: string) {\n const input = this.getInputParam(argIndex);\n return MoveCallHelper.getPureInputValue<T>(input, bcsType);\n }\n\n getInputParam(argIndex: number) {\n const arg = this.moveCall.arguments[argIndex];\n if (arg.kind !== 'Input') {\n throw new Error('not input type');\n }\n return this.txb.blockData.inputs[arg.index];\n }\n\n getNestedInputParam<T>(argIndex: number) {\n const arg = this.moveCall.arguments[argIndex];\n if (arg.kind !== 'NestedResult') {\n throw new Error('not input type');\n }\n return this.txb.blockData.transactions[arg.index] as T;\n }\n\n isHaveNestedInput(argIndex: number) {\n const arg = this.moveCall.arguments[argIndex];\n return arg.kind === 'NestedResult';\n }\n\n static getPureInputValue<T>(input: TransactionBlockInput, bcsType: string) {\n if (input.type !== 'pure') {\n throw new Error('not pure argument');\n }\n if (typeof input.value === 'object' && 'Pure' in input.value) {\n const bcsNums = input.value.Pure;\n return bcs.de(bcsType, new Uint8Array(bcsNums)) as T;\n }\n return input.value as T;\n }\n\n static getOwnedObjectId(input: TransactionBlockInput) {\n if (input.type !== 'object') {\n throw new Error(`not object argument: ${JSON.stringify(input)}`);\n }\n if (typeof input.value === 'object') {\n if (!('Object' in input.value) || !('ImmOrOwned' in input.value.Object)) {\n throw new Error('not ImmOrOwned');\n }\n return normalizeSuiAddress(input.value.Object.ImmOrOwned.objectId as string);\n }\n return normalizeSuiAddress(input.value as string);\n }\n\n static getSharedObjectId(input: TransactionBlockInput) {\n if (input.type !== 'object') {\n throw new Error(`not object argument: ${JSON.stringify(input)}`);\n }\n if (typeof input.value !== 'object') {\n return normalizeSuiAddress(input.value as string);\n }\n if (!('Object' in input.value) || !('Shared' in input.value.Object)) {\n throw new Error('not Shared');\n }\n return normalizeSuiAddress(input.value.Object.Shared.objectId as string);\n }\n\n static getPureInput<T>(input: TransactionBlockInput, bcsType: string) {\n if (input.type !== 'pure') {\n throw new Error('not pure argument');\n }\n if (typeof input.value !== 'object') {\n return input.value as T;\n }\n if (!('Pure' in input.value)) {\n throw new Error('Pure not in value');\n }\n const bcsVal = input.value.Pure;\n return bcs.de(bcsType, new Uint8Array(bcsVal)) as T;\n }\n\n typeArg(index: number) {\n return normalizeStructTag(this.moveCall.typeArguments[index]);\n }\n\n txArg(index: number) {\n return this.moveCall.arguments[index];\n }\n}\n","import { bcs } from '@mysten/sui.js/bcs';\nimport { SplitCoinsTransaction, TransactionBlock, TransactionBlockInput } from '@mysten/sui.js/dist/cjs/transactions';\n\nimport { MoveCallHelper } from './moveCallHelper';\n\nexport class SplitCoinHelper {\n constructor(\n public readonly splitCoin: SplitCoinsTransaction,\n public readonly txb: TransactionBlock,\n ) {}\n\n getAmountInput() {\n return this.splitCoin.amounts\n .map((input) => {\n if (input.kind === 'Input') {\n return Number(MoveCallHelper.getPureInputValue<number>(input, 'u64'));\n }\n return undefined;\n })\n .filter((input) => input !== undefined);\n }\n\n static getPureInputValue<T>(input: TransactionBlockInput, bcsType: string) {\n if (input.type !== 'pure') {\n throw new Error('not pure argument');\n }\n if (typeof input.value === 'object' && 'Pure' in input.value) {\n const bcsNums = input.value.Pure;\n return bcs.de(bcsType, new Uint8Array(bcsNums)) as T;\n }\n return input.value as T;\n }\n}\n","import { TransactionType } from '@msafe/sui3-utils';\nimport { MoveCallTransaction } from '@mysten/sui.js/dist/cjs/transactions';\n\nimport { Decoder } from './decoder';\nimport { DecodeResult } from '../types';\nimport { TransactionSubType } from '../types/utils';\nimport { MoveCallHelper } from '../utils/moveCallHelper';\n\nexport class DecoderReferral extends Decoder {\n decode() {\n if (this.isCreateReferralLink()) {\n return this.decodeCreateReferralLink();\n }\n if (this.isClaimRevenueReferral()) {\n return this.decodeClaimRevenueReferral();\n }\n if (this.isBindReferral()) {\n return this.decodeBindReferral();\n }\n return undefined;\n }\n\n private isClaimRevenueReferral() {\n return !!this.getMoveCallTransaction(\n `${this.coreId.referral}::referral_revenue_pool::claim_revenue_with_ve_sca_key`,\n );\n }\n\n private isCreateReferralLink() {\n return !!this.getMoveCallTransaction(`${this.coreId.veScaPkgId}::ve_sca::mint_ve_sca_placeholder_key`);\n }\n\n private isBindReferral() {\n return !!this.getMoveCallTransaction(`${this.coreId.referral}::referral_bindings::bind_ve_sca_referrer`);\n }\n\n private get helperClaimRevenueReferral() {\n const moveCalls = this.transactions\n .filter(\n (trans) =>\n trans.kind === 'MoveCall' &&\n trans.target.startsWith(`${this.coreId.referral}::referral_revenue_pool::claim_revenue_with_ve_sca_key`),\n )\n .map((trans) => new MoveCallHelper(trans as MoveCallTransaction, this.txb));\n return moveCalls;\n }\n\n private get helperBindReferral() {\n const moveCall = this.transactions.find(\n (trans) =>\n trans.kind === 'MoveCall' &&\n trans.target.startsWith(`${this.coreId.referral}::referral_bindings::bind_ve_sca_referrer`),\n ) as MoveCallTransaction;\n return new MoveCallHelper(moveCall, this.txb);\n }\n\n private decodeCreateReferralLink(): DecodeResult {\n return {\n txType: TransactionType.Other,\n type: TransactionSubType.CreateReferralLink,\n intentionData: {},\n };\n }\n\n private decodeClaimRevenueReferral(): DecodeResult {\n const veScaKey = this.helperClaimRevenueReferral[0].decodeOwnedObjectId(2);\n const coins = this.helperClaimRevenueReferral.map((helper) => helper.typeArg(0));\n return {\n txType: TransactionType.Other,\n type: TransactionSubType.ClaimRevenueReferral,\n intentionData: {\n veScaKey,\n coins,\n },\n };\n }\n\n private decodeBindReferral(): DecodeResult {\n const veScaKey = this.helperBindReferral.decodePureArg(1, 'address');\n return {\n txType: TransactionType.Other,\n type: TransactionSubType.BindReferral,\n intentionData: {\n veScaKey,\n },\n };\n }\n}\n","import { TransactionType } from '@msafe/sui3-utils';\nimport { MoveCallTransaction, SplitCoinsTransaction } from '@mysten/sui.js/dist/cjs/transactions';\n\nimport { Decoder } from './decoder';\nimport { OLD_BORROW_INCENTIVE_PROTOCOL_ID } from '../constants';\nimport { DecodeResult } from '../types';\nimport { TransactionSubType } from '../types/utils';\nimport { MoveCallHelper } from '../utils/moveCallHelper';\nimport { SplitCoinHelper } from '../utils/splitCoinHelper';\n\nexport class DecoderVesca extends Decoder {\n decode() {\n if (this.isExtendPeriodAndStakeMoreSca()) {\n return this.decodePeriodAndStakeMoreSca();\n }\n if (this.isStakeScaFirsTime() || this.isStakeMoreSca()) {\n return this.decodeStakeSca();\n }\n if (this.isRenewExpiredVeSca()) {\n return this.decodeRenewExpiredVeSca();\n }\n if (this.isExtendPeriod()) {\n return this.decodeExtendStakePeriod();\n }\n if (this.isRedeemSca()) {\n return this.decodeRedeemSca();\n }\n return undefined;\n }\n\n private isStakeScaFirsTime() {\n return !!this.getMoveCallTransaction(`${this.coreId.veScaPkgId}::ve_sca::mint_ve_sca_key`);\n }\n\n private isExtendPeriodAndStakeMoreSca() {\n const extendPeriod = this.getMoveCallTransaction(`${this.coreId.veScaPkgId}::ve_sca::extend_lock_period`);\n const stakeMoreSca = this.getMoveCallTransaction(`${this.coreId.veScaPkgId}::ve_sca::lock_more_sca`);\n return !!extendPeriod && !!stakeMoreSca;\n }\n\n private isRedeemSca() {\n return !!this.getMoveCallTransaction(`${this.coreId.veScaPkgId}::ve_sca::redeem`);\n }\n\n private isStakeMoreSca() {\n return !!this.getMoveCallTransaction(`${this.coreId.veScaPkgId}::ve_sca::lock_more_sca`);\n }\n\n private isExtendPeriod() {\n return !!this.getMoveCallTransaction(`${this.coreId.veScaPkgId}::ve_sca::extend_lock_period`);\n }\n\n private isRenewExpiredVeSca() {\n return !!this.getMoveCallTransaction(`${this.coreId.veScaPkgId}::ve_sca::renew_expired_ve_sca`);\n }\n\n private get helperStakeMoreSca() {\n const moveCall = this.transactions.find(\n (trans) =>\n trans.kind === 'MoveCall' && trans.target.startsWith(`${this.coreId.veScaPkgId}::ve_sca::lock_more_sca`),\n ) as MoveCallTransaction;\n return new MoveCallHelper(moveCall, this.txb);\n }\n\n private get helperStakeSca() {\n const moveCall = this.transactions.find(\n (trans) =>\n trans.kind === 'MoveCall' && trans.target.startsWith(`${this.coreId.veScaPkgId}::ve_sca::mint_ve_sca_key`),\n ) as MoveCallTransaction;\n return new MoveCallHelper(moveCall, this.txb);\n }\n\n private get helperExtendStakePeriod() {\n const moveCall = this.transactions.find(\n (trans) =>\n trans.kind === 'MoveCall' && trans.target.startsWith(`${this.coreId.veScaPkgId}::ve_sca::extend_lock_period`),\n ) as MoveCallTransaction;\n return new MoveCallHelper(moveCall, this.txb);\n }\n\n private get helperRedeemSca() {\n const moveCall = this.transactions.find(\n (trans) => trans.kind === 'MoveCall' && trans.target.startsWith(`${this.coreId.veScaPkgId}::ve_sca::redeem`),\n ) as MoveCallTransaction;\n return new MoveCallHelper(moveCall, this.txb);\n }\n\n private get helperRenewExpired() {\n const moveCall = this.transactions.find(\n (trans) =>\n trans.kind === 'MoveCall' && trans.target.startsWith(`${this.coreId.veScaPkgId}::ve_sca::renew_expired_ve_sca`),\n ) as MoveCallTransaction;\n return new MoveCallHelper(moveCall, this.txb);\n }\n\n private get helperOldUnstakeObligation() {\n const moveCall = this.transactions.find(\n (trans) =>\n trans.kind === 'MoveCall' && trans.target.startsWith(`${OLD_BORROW_INCENTIVE_PROTOCOL_ID}::user::unstake`),\n ) as MoveCallTransaction;\n return new MoveCallHelper(moveCall, this.txb);\n }\n\n private get helperUnstakeObligation() {\n const moveCall = this.transactions.find(\n (trans) =>\n trans.kind === 'MoveCall' && trans.target.startsWith(`${this.coreId.borrowIncentivePkg}::user::unstake`),\n ) as MoveCallTransaction;\n return new MoveCallHelper(moveCall, this.txb);\n }\n\n private get helperStakeObligationWithVeSca() {\n const moveCall = this.transactions.find(\n (trans) =>\n trans.kind === 'MoveCall' &&\n trans.target.startsWith(`${this.coreId.borrowIncentivePkg}::user::stake_with_ve_sca`),\n ) as MoveCallTransaction;\n return new MoveCallHelper(moveCall, this.txb);\n }\n\n private decodeRedeemSca(): DecodeResult {\n const veScaKey = this.helperRedeemSca.decodeOwnedObjectId(1);\n return {\n txType: TransactionType.Other,\n type: TransactionSubType.RedeemSca,\n intentionData: {\n veScaKey,\n },\n };\n }\n\n private decodeRenewExpiredVeSca(): DecodeResult {\n const lockSca = this.helperRenewExpired.getNestedInputParam<SplitCoinsTransaction>(4);\n const unlockTime = this.helperRenewExpired.decodeInputU64(5);\n const amountFromSplitCoin = new SplitCoinHelper(lockSca, this.txb).getAmountInput().reduce((a, b) => a + b, 0);\n const veScaKey = this.helperRenewExpired.decodeOwnedObjectId(1);\n const isHaveRedeem = !!this.helperRedeemSca.moveCall;\n let oldUnstakeObligation: string[] = [];\n let unstakeObligation: string[] = [];\n let stakeObligation: string[] = [];\n if (this.helperOldUnstakeObligation.moveCall) {\n oldUnstakeObligation = [\n this.helperOldUnstakeObligation.decodeSharedObjectId(2), // Obligation key\n this.helperOldUnstakeObligation.decodeSharedObjectId(3), // Obligation Id\n ];\n }\n if (this.helperUnstakeObligation.moveCall) {\n unstakeObligation = [\n this.helperUnstakeObligation.decodeSharedObjectId(3), // Obligation key\n this.helperUnstakeObligation.decodeSharedObjectId(4), // Obligation Id\n ];\n }\n if (this.helperStakeObligationWithVeSca.moveCall) {\n stakeObligation = [\n this.helperStakeObligationWithVeSca.decodeSharedObjectId(3), // Obligation key\n this.helperStakeObligationWithVeSca.decodeSharedObjectId(4), // Obligation Id\n ];\n }\n let isObligationLocked = false;\n let isOldBorrowIncentive = false;\n let obligationId;\n let obligationKey;\n\n const operations = [\n { condition: oldUnstakeObligation, isOld: true },\n { condition: unstakeObligation, isOld: false },\n { condition: stakeObligation, isOld: false },\n ];\n\n for (let i = 0; i < operations.length; i++) {\n if (operations[i].condition.length > 1) {\n [obligationKey, obligationId] = operations[i].condition;\n isObligationLocked = true;\n isOldBorrowIncentive = operations[i].isOld;\n }\n }\n return {\n txType: TransactionType.Other,\n type: TransactionSubType.RenewExpStakePeriod,\n intentionData: {\n amount: amountFromSplitCoin,\n lockPeriodInDays: unlockTime,\n obligationId,\n obligationKey,\n veScaKey,\n isHaveRedeem,\n isObligationLocked,\n isOldBorrowIncentive,\n },\n };\n }\n\n private decodeExtendStakePeriod(): DecodeResult {\n const unlockTime = this.helperExtendStakePeriod.decodeInputU64(4);\n const veScaKey = this.helperExtendStakePeriod.decodeOwnedObjectId(1);\n let oldUnstakeObligation: string[] = [];\n let unstakeObligation: string[] = [];\n let stakeObligation: string[] = [];\n if (this.helperOldUnstakeObligation.moveCall) {\n oldUnstakeObligation = [\n this.helperOldUnstakeObligation.decodeSharedObjectId(2), // Obligation key\n this.helperOldUnstakeObligation.decodeSharedObjectId(3), // Obligation Id\n ];\n }\n if (this.helperUnstakeObligation.moveCall) {\n unstakeObligation = [\n this.helperUnstakeObligation.decodeSharedObjectId(3), // Obligation key\n this.helperUnstakeObligation.decodeSharedObjectId(4), // Obligation Id\n ];\n }\n if (this.helperStakeObligationWithVeSca.moveCall) {\n stakeObligation = [\n this.helperStakeObligationWithVeSca.decodeSharedObjectId(3), // Obligation key\n this.helperStakeObligationWithVeSca.decodeSharedObjectId(4), // Obligation Id\n ];\n }\n let isObligationLocked = false;\n let isOldBorrowIncentive = false;\n let obligationId;\n let obligationKey;\n\n const operations = [\n { condition: oldUnstakeObligation, isOld: true },\n { condition: unstakeObligation, isOld: false },\n { condition: stakeObligation, isOld: false },\n ];\n\n for (let i = 0; i < operations.length; i++) {\n if (operations[i].condition.length > 1) {\n [obligationKey, obligationId] = operations[i].condition;\n isObligationLocked = true;\n isOldBorrowIncentive = operations[i].isOld;\n }\n }\n return {\n txType: TransactionType.Other,\n type: TransactionSubType.ExtendStakePeriod,\n intentionData: {\n lockPeriodInDays: unlockTime,\n obligationId,\n obligationKey,\n veScaKey,\n isObligationLocked,\n isOldBorrowIncentive,\n },\n };\n }\n\n private decodePeriodAndStakeMoreSca(): DecodeResult {\n const lockSca = this.helperStakeMoreSca.getNestedInputParam<SplitCoinsTransaction>(4);\n const unlockTime = this.helperExtendStakePeriod.decodeInputU64(4);\n const amountFromSplitCoin = new SplitCoinHelper(lockSca, this.txb).getAmountInput().reduce((a, b) => a + b, 0);\n let oldUnstakeObligation: string[] = [];\n let unstakeObligation: string[] = [];\n let veScaKey;\n let stakeObligation: string[] = [];\n if (this.helperOldUnstakeObligation.moveCall) {\n oldUnstakeObligation = [\n this.helperOldUnstakeObligation.decodeSharedObjectId(2), // Obligation key\n this.helperOldUnstakeObligation.decodeSharedObjectId(3), // Obligation Id\n ];\n }\n if (this.helperUnstakeObligation.moveCall) {\n unstakeObligation = [\n this.helperUnstakeObligation.decodeSharedObjectId(3), // Obligation key\n this.helperUnstakeObligation.decodeSharedObjectId(4), // Obligation Id\n ];\n }\n if (this.helperStakeMoreSca.moveCall) {\n veScaKey = this.helperStakeMoreSca.decodeOwnedObjectId(1);\n }\n if (this.helperStakeObligationWithVeSca.moveCall) {\n stakeObligation = [\n this.helperStakeObligationWithVeSca.decodeSharedObjectId(3), // Obligation key\n this.helperStakeObligationWithVeSca.decodeSharedObjectId(4), // Obligation Id\n ];\n }\n let isObligationLocked = false;\n let isOldBorrowIncentive = false;\n let obligationId;\n let obligationKey;\n\n const operations = [\n { condition: oldUnstakeObligation, isOld: true },\n { condition: unstakeObligation, isOld: false },\n { condition: stakeObligation, isOld: false },\n ];\n\n for (let i = 0; i < operations.length; i++) {\n if (operations[i].condition.length > 1) {\n [obligationKey, obligationId] = operations[i].condition;\n isObligationLocked = true;\n isOldBorrowIncentive = operations[i].isOld;\n }\n }\n return {\n txType: TransactionType.Other,\n type: TransactionSubType.ExtendPeriodAndStakeMore,\n intentionData: {\n amount: amountFromSplitCoin,\n veScaKey,\n lockPeriodInDays: unlockTime,\n obligationId,\n obligationKey,\n isOldBorrowIncentive,\n isObligationLocked,\n },\n };\n }\n\n private decodeStakeSca(): DecodeResult {\n let lockSca;\n let unlockTime;\n if (this.helperStakeSca.moveCall && this.helperStakeMoreSca.moveCall === undefined) {\n lockSca = this.helperStakeSca.getNestedInputParam<SplitCoinsTransaction>(3);\n unlockTime = this.helperStakeSca.decodeInputU64(4);\n } else {\n lockSca = this.helperStakeMoreSca.getNestedInputParam<SplitCoinsTransaction>(4);\n }\n const amountFromSplitCoin = new SplitCoinHelper(lockSca, this.txb).getAmountInput().reduce((a, b) => a + b, 0);\n let oldUnstakeObligation: string[] = [];\n let unstakeObligation: string[] = [];\n let veScaKey;\n let stakeObligation: string[] = [];\n if (this.helperOldUnstakeObligation.moveCall) {\n oldUnstakeObligation = [\n this.helperOldUnstakeObligation.decodeSharedObjectId(2), // Obligation key\n this.helperOldUnstakeObligation.decodeSharedObjectId(3), // Obligation Id\n ];\n }\n if (this.helperUnstakeObligation.moveCall) {\n unstakeObligation = [\n this.helperUnstakeObligation.decodeSharedObjectId(3), // Obligation key\n this.helperUnstakeObligation.decodeSharedObjectId(4), // Obligation Id\n ];\n }\n if (this.helperStakeMoreSca.moveCall) {\n veScaKey = this.helperStakeMoreSca.decodeOwnedObjectId(1);\n }\n if (this.helperStakeObligationWithVeSca.moveCall) {\n stakeObligation = [\n this.helperStakeObligationWithVeSca.decodeSharedObjectId(3), // Obligation key\n this.helperStakeObligationWithVeSca.decodeSharedObjectId(4), // Obligation Id\n ];\n }\n let isObligationLocked = false;\n let isOldBorrowIncentive = false;\n let obligationId;\n let obligationKey;\n\n const operations = [\n { condition: oldUnstakeObligation, isOld: true },\n { condition: unstakeObligation, isOld: false },\n { condition: stakeObligation, isOld: false },\n ];\n\n for (let i = 0; i < operations.length; i++) {\n if (operations[i].condition.length > 1) {\n [obligationKey, obligationId] = operations[i].condition;\n isObligationLocked = true;\n isOldBorrowIncentive = operations[i].isOld;\n }\n }\n return {\n txType: TransactionType.Other,\n type: TransactionSubType.StakeSca,\n intentionData: {\n amount: amountFromSplitCoin,\n lockPeriodInDays: unlockTime,\n obligationId,\n obligationKey,\n veScaKey,\n isObligationLocked,\n isOldBorrowIncentive,\n },\n };\n }\n}\n","import { TransactionType } from '@msafe/sui3-utils';\nimport { SuiClient } from '@mysten/sui.js/client';\nimport { TransactionBlock } from '@mysten/sui.js/transactions';\nimport { WalletAccount } from '@mysten/wallet-standard';\nimport sortKeys from 'sort-keys-recursive';\n\nimport { BaseIntentionLegacy } from '@/apps/interface/sui-js';\nimport { SuiNetworks } from '@/types';\n\nimport { Scallop } from '../models';\n\nexport abstract class ScallopCoreBaseIntention<D> implements BaseIntentionLegacy<D> {\n abstract txType: TransactionType;\n\n abstract txSubType: string;\n\n protected constructor(public readonly data: D) {}\n\n get application() {\n return 'msafe-core';\n }\n\n serialize() {\n return JSON.stringify(sortKeys(this.data));\n }\n\n abstract build(input: {\n suiClient: SuiClient;\n account: WalletAccount;\n network: SuiNetworks;\n scallop: Scallop;\n }): Promise<TransactionBlock>;\n}\n","import { TransactionType } from '@msafe/sui3-utils';\nimport { SuiClient } from '@mysten/sui.js/client';\nimport { TransactionBlock } from '@mysten/sui.js/transactions';\nimport { WalletAccount } from '@mysten/wallet-standard';\n\nimport { SuiNetworks } from '@/types';\n\nimport { Scallop } from '../../models';\nimport { SupportPoolCoins } from '../../types';\nimport { TransactionSubType } from '../../types/utils';\nimport { ScallopCoreBaseIntention } from '../scallopCoreBaseIntention';\n\nexport interface BorrowIntentionData {\n coinName: SupportPoolCoins;\n amount: number | string;\n obligationId: string;\n obligationKey: string;\n}\n\nexport class BorrowIntention extends ScallopCoreBaseIntention<BorrowIntentionData> {\n txType: TransactionType.Other;\n\n txSubType: TransactionSubType.Borrow;\n\n constructor(public readonly data: BorrowIntentionData) {\n super(data);\n }\n\n async build(input: {\n suiClient: SuiClient;\n account: WalletAccount;\n network: SuiNetworks;\n scallop: Scallop;\n }): Promise<TransactionBlock> {\n return input.scallop.client.borrow(\n this.data.coinName,\n Number(this.data.amount),\n this.data.obligationId,\n this.data.obligationKey,\n input.account.address,\n );\n }\n\n static fromData(data: BorrowIntentionData): BorrowIntention {\n return new BorrowIntention(data);\n }\n}\n","import { TransactionType } from '@msafe/sui3-utils';\nimport { SuiClient } from '@mysten/sui.js/client';\nimport { TransactionBlock } from '@mysten/sui.js/transactions';\nimport { WalletAccount } from '@mysten/wallet-standard';\n\nimport { SuiNetworks } from '@/types';\n\nimport { Scallop } from '../../models';\nimport { SupportPoolCoins } from '../../types';\nimport { TransactionSubType } from '../../types/utils';\nimport { ScallopCoreBaseIntention } from '../scallopCoreBaseIntention';\n\nexport interface BorrowWithBoostIntentionData {\n coinName: SupportPoolCoins;\n amount: number | string;\n obligationId: string;\n obligationKey: string;\n veScaKey: string;\n}\n\nexport class BorrowWithBoostIntention extends ScallopCoreBaseIntention<BorrowWithBoostIntentionData> {\n txType: TransactionType.Other;\n\n txSubType: TransactionSubType.Borrow;\n\n constructor(public readonly data: BorrowWithBoostIntentionData) {\n super(data);\n }\n\n async build(input: {\n suiClient: SuiClient;\n account: WalletAccount;\n network: SuiNetworks;\n scallop: Scallop;\n }): Promise<TransactionBlock> {\n return input.scallop.client.borrowWithBoost(\n this.data.coinName,\n Number(this.data.amount),\n this.data.obligationId,\n this.data.obligationKey,\n this.data.veScaKey,\n input.account.address,\n );\n }\n\n static fromData(data: BorrowWithBoostIntentionData): BorrowWithBoostIntention {\n return new BorrowWithBoostIntention(data);\n }\n}\n","import { TransactionType } from '@msafe/sui3-utils';\nimport { SuiClient } from '@mysten/sui.js/client';\nimport { TransactionBlock } from '@mysten/sui.js/transactions';\nimport { WalletAccount } from '@mysten/wallet-standard';\n\nimport { SuiNetworks } from '@/types';\n\nimport { Scallop } from '../../models';\nimport { SupportPoolCoins } from '../../types';\nimport { TransactionSubType } from '../../types/utils';\nimport { ScallopCoreBaseIntention } from '../scallopCoreBaseIntention';\n\nexport interface BorrowWithReferralIntentionData {\n coinName: SupportPoolCoins;\n amount: number | string;\n obligationId: string;\n obligationKey: string;\n veScaKey: string | undefined;\n}\n\nexport class BorrowWithReferralIntention extends ScallopCoreBaseIntention<BorrowWithReferralIntentionData> {\n txType: TransactionType.Other;\n\n txSubType: TransactionSubType.BorrowWithReferral;\n\n constructor(public readonly data: BorrowWithReferralIntentionData) {\n super(data);\n }\n\n async build(input: {\n suiClient: SuiClient;\n account: WalletAccount;\n network: SuiNetworks;\n scallop: Scallop;\n }): Promise<TransactionBlock> {\n return input.scallop.client.borrowWithReferral(\n this.data.coinName,\n Number(this.data.amount),\n this.data.obligationId,\n this.data.obligationKey,\n this.data.veScaKey,\n input.account.address,\n );\n }\n\n static fromData(data: BorrowWithReferralIntentionData): BorrowWithReferralIntention {\n return new BorrowWithReferralIntention(data);\n }\n}\n","import { TransactionType } from '@msafe/sui3-utils';\nimport { SuiClient } from '@mysten/sui.js/client';\nimport { TransactionBlock } from '@mysten/sui.js/transactions';\nimport { WalletAccount } from '@mysten/wallet-standard';\n\nimport { SuiNetworks } from '@/types';\n\nimport { Scallop } from '../../models';\nimport { BorrowIncentiveParams, SpoolIncentiveParams } from '../../types';\nimport { TransactionSubType } from '../../types/utils';\nimport { ScallopCoreBaseIntention } from '../scallopCoreBaseIntention';\n\nexport interface ClaimIncentiveRewardIntentionData {\n lendingIncentive: SpoolIncentiveParams[];\n borrowIncentiveV2: BorrowIncentiveParams[];\n borrowIncentive: BorrowIncentiveParams[];\n}\n\nexport class ClaimIncentiveRewardIntention extends ScallopCoreBaseIntention<ClaimIncentiveRewardIntentionData> {\n txType: TransactionType.Other;\n\n txSubType: TransactionSubType.ClaimIncentiveReward;\n\n constructor(public readonly data: ClaimIncentiveRewardIntentionData) {\n super(data);\n }\n\n async build(input: {\n suiClient: SuiClient;\n account: WalletAccount;\n network: SuiNetworks;\n scallop: Scallop;\n }): Promise<TransactionBlock> {\n return input.scallop.client.claim(\n this.data.lendingIncentive,\n this.data.borrowIncentiveV2,\n this.data.borrowIncentive,\n input.account.address,\n );\n }\n\n static fromData(data: ClaimIncentiveRewardIntentionData): ClaimIncentiveRewardIntention {\n return new ClaimIncentiveRewardIntention(data);\n }\n}\n","import { TransactionType } from '@msafe/sui3-utils';\nimport { SuiClient } from '@mysten/sui.js/client';\nimport { TransactionBlock } from '@mysten/sui.js/transactions';\nimport { WalletAccount } from '@mysten/wallet-standard';\n\nimport { SuiNetworks } from '@/types';\n\nimport { Scallop } from '../../models';\nimport { SupportCollateralCoins } from '../../types';\nimport { TransactionSubType } from '../../types/utils';\nimport { ScallopCoreBaseIntention } from '../scallopCoreBaseIntention';\n\nexport interface DepositCollateralIntentionData {\n collateralCoinName: SupportCollateralCoins;\n amount: number | string;\n obligationId: string;\n}\n\nexport class DepositCollateralIntention extends ScallopCoreBaseIntention<DepositCollateralIntentionData> {\n txType: TransactionType.Other;\n\n txSubType: TransactionSubType.DepositCollateral;\n\n constructor(public readonly data: DepositCollateralIntentionData) {\n super(data);\n }\n\n async build(input: {\n suiClient: SuiClient;\n account: WalletAccount;\n network: SuiNetworks;\n scallop: Scallop;\n }): Promise<TransactionBlock> {\n return input.scallop.client.depositCollateral(\n this.data.collateralCoinName,\n Number(this.data.amount),\n this.data.obligationId,\n input.account.address,\n );\n }\n\n static fromData(data: DepositCollateralIntentionData): DepositCollateralIntention {\n return new DepositCollateralIntention(data);\n }\n}\n","import { TransactionType } from '@msafe/sui3-utils';\nimport { SuiClient } from '@mysten/sui.js/client';\nimport { TransactionBlock } from '@mysten/sui.js/transactions';\nimport { WalletAccount } from '@mysten/wallet-standard';\n\nimport { SuiNetworks } from '@/types';\n\nimport { Scallop } from '../../models';\nimport { SupportBorrowIncentiveRewardCoins, TransactionSubType } from '../../types';\nimport { ScallopCoreBaseIntention } from '../scallopCoreBaseIntention';\n\nexport interface MigrateAndClaimIntentionData {\n obligationKey: string;\n obligationId: string;\n rewardCoinName: SupportBorrowIncentiveRewardCoins;\n veScaKey?: string;\n}\n\nexport class MigrateAndClaimIntention extends ScallopCoreBaseIntention<MigrateAndClaimIntentionData> {\n txType: TransactionType.Other;\n\n txSubType: TransactionSubType.MigrateAndClaim;\n\n constructor(public readonly data: MigrateAndClaimIntentionData) {\n super(data);\n }\n\n async build(input: {\n suiClient: SuiClient;\n account: WalletAccount;\n network: SuiNetworks;\n scallop: Scallop;\n }): Promise<TransactionBlock> {\n return input.scallop.client.migrateAndClaim(\n this.data.obligationKey,\n this.data.obligationId,\n this.data.rewardCoinName,\n this.data.veScaKey,\n );\n }\n\n static fromData(data: MigrateAndClaimIntentionData): MigrateAndClaimIntention {\n return new MigrateAndClaimIntention(data);\n }\n}\n","import { TransactionType } from '@msafe/sui3-utils';\nimport { SuiClient } from '@mysten/sui.js/client';\nimport { TransactionBlock } from '@mysten/sui.js/transactions';\nimport { WalletAccount } from '@mysten/wallet-standard';\n\nimport { SuiNetworks } from '@/types';\n\nimport { Scallop } from '../../models';\nimport { TransactionSubType } from '../../types';\nimport { ScallopCoreBaseIntention } from '../scallopCoreBaseIntention';\n\n// eslint-disable-next-line @typescript-eslint/no-empty-interface\nexport interface MigrateScoinIntentionData {}\n\nexport class MigrateScoinIntention extends ScallopCoreBaseIntention<MigrateScoinIntentionData> {\n txType: TransactionType.Other;\n\n txSubType: TransactionSubType.MigrateScoin;\n\n constructor(public readonly data: MigrateScoinIntentionData) {\n super(data);\n }\n\n async build(input: {\n suiClient: SuiClient;\n account: WalletAccount;\n network: SuiNetworks;\n scallop: Scallop;\n }): Promise<TransactionBlock> {\n return input.scallop.client.migrateAllMarketCoin();\n }\n\n static fromData(data: MigrateScoinIntentionData): MigrateScoinIntention {\n return new MigrateScoinIntention(data);\n }\n}\n","/* eslint-disable import/no-extraneous-dependencies */\nimport { TransactionType } from '@msafe/sui3-utils';\nimport { SuiClient } from '@mysten/sui.js/client';\nimport { TransactionBlock } from '@mysten/sui.js/transactions';\nimport { WalletAccount } from '@mysten/wallet-standard';\n\nimport { SuiNetworks } from '@/types';\n\nimport { Scallop } from '../../models';\nimport { SupportAssetCoins, TransactionSubType } from '../../types';\nimport { ScallopCoreBaseIntention } from '../scallopCoreBaseIntention';\n\nexport interface MigrateWusdcToUsdcIntentionData {\n amount: number | undefined;\n coinName: SupportAssetCoins;\n slippage: number;\n validSwapAmount: string;\n stakeAccountId: { id: string; coin: number }[];\n}\n\nexport class MigrateWusdcToUsdcIntention extends ScallopCoreBaseIntention<MigrateWusdcToUsdcIntentionData> {\n txType: TransactionType.Other;\n\n txSubType: TransactionSubType.MigrateWusdcToUsdc;\n\n constructor(public readonly data: MigrateWusdcToUsdcIntentionData) {\n super(data);\n }\n\n async build(input: {\n suiClient: SuiClient;\n account: WalletAccount;\n network: SuiNetworks;\n scallop: Scallop;\n }): Promise<TransactionBlock> {\n return input.scallop.client.migrateLendingWusdcToUsdcNative(\n this.data.coinName,\n Number(this.data.amount),\n this.data.slippage,\n this.data.validSwapAmount,\n this.data.stakeAccountId,\n );\n }\n\n static fromData(data: MigrateWusdcToUsdcIntentionData): MigrateWusdcToUsdcIntention {\n return new MigrateWusdcToUsdcIntention(data);\n }\n}\n","import { TransactionType } from '@msafe/sui3-utils';\nimport { SuiClient } from '@mysten/sui.js/client';\nimport { TransactionBlock } from '@mysten/sui.js/transactions';\nimport { WalletAccount } from '@mysten/wallet-standard';\n\nimport { SuiNetworks } from '@/types';\n\nimport { Scallop } from '../../models';\nimport { TransactionSubType } from '../../types/utils';\nimport { ScallopCoreBaseIntention } from '../scallopCoreBaseIntention';\n\n// eslint-disable-next-line @typescript-eslint/no-empty-interface\nexport interface OpenObligationIntentionData {}\n\nexport class OpenObligationIntention extends ScallopCoreBaseIntention<OpenObligationIntentionData> {\n txType: TransactionType.Other;\n\n txSubType: TransactionSubType.OpenObligation;\n\n constructor(public readonly data: OpenObligationIntentionData) {\n super(data);\n }\n\n async build(input: {\n suiClient: SuiClient;\n account: WalletAccount;\n network: SuiNetworks;\n scallop: Scallop;\n }): Promise<TransactionBlock> {\n return input.scallop.client.openObligation();\n }\n\n static fromData(data: OpenObligationIntentionData): OpenObligationIntention {\n return new OpenObligationIntention(data);\n }\n}\n","import { TransactionType } from '@msafe/sui3-utils';\nimport { SuiClient } from '@mysten/sui.js/client';\nimport { TransactionBlock } from '@mysten/sui.js/transactions';\nimport { WalletAccount } from '@mysten/wallet-standard';\n\nimport { SuiNetworks } from '@/types';\n\nimport { Scallop } from '../../models';\nimport { SupportPoolCoins } from '../../types';\nimport { TransactionSubType } from '../../types/utils';\nimport { ScallopCoreBaseIntention } from '../scallopCoreBaseIntention';\n\nexport interface RepayIntentionData {\n coinName: SupportPoolCoins;\n amount: number | string;\n obligationId: string;\n obligationKey: string;\n}\n\nexport class RepayIntention extends ScallopCoreBaseIntention<RepayIntentionData> {\n txType: TransactionType.Other;\n\n txSubType: TransactionSubType.Repay;\n\n constructor(public readonly data: RepayIntentionData) {\n super(data);\n }\n\n async build(input: {\n suiClient: SuiClient;\n account: WalletAccount;\n network: SuiNetworks;\n scallop: Scallop;\n }): Promise<TransactionBlock> {\n return input.scallop.client.repay(\n this.data.coinName,\n Number(this.data.amount),\n this.data.obligationId,\n this.data.obligationKey,\n input.account.address,\n );\n }\n\n static fromData(data: RepayIntentionData): RepayIntention {\n return new RepayIntention(data);\n }\n}\n","import { TransactionType } from '@msafe/sui3-utils';\nimport { SuiClient } from '@mysten/sui.js/client';\nimport { TransactionBlock } from '@mysten/sui.js/transactions';\nimport { WalletAccount } from '@mysten/wallet-standard';\n\nimport { SuiNetworks } from '@/types';\n\nimport { Scallop } from '../../models';\nimport { SupportPoolCoins } from '../../types';\nimport { TransactionSubType } from '../../types/utils';\nimport { ScallopCoreBaseIntention } from '../scallopCoreBaseIntention';\n\nexport interface RepayWithBoostIntentionData {\n coinName: SupportPoolCoins;\n amount: number | string;\n obligationId: string;\n veScaKey: string;\n}\n\nexport class RepayWithBoostIntention extends ScallopCoreBaseIntention<RepayWithBoostIntentionData> {\n txType: TransactionType.Other;\n\n txSubType: TransactionSubType.RepayWithBoost;\n\n constructor(public readonly data: RepayWithBoostIntentionData) {\n super(data);\n }\n\n async build(input: {\n suiClient: SuiClient;\n account: WalletAccount;\n network: SuiNetworks;\n scallop: Scallop;\n }): Promise<TransactionBlock> {\n return input.scallop.client.repayWithBoost(\n this.data.coinName,\n Number(this.data.amount),\n this.data.obligationId,\n this.data.veScaKey,\n input.account.address,\n );\n }\n\n static fromData(data: RepayWithBoostIntentionData): RepayWithBoostIntention {\n return new RepayWithBoostIntention(data);\n }\n}\n","import { TransactionType } from '@msafe/sui3-utils';\nimport { SuiClient } from '@mysten/sui.js/client';\nimport { TransactionBlock } from '@mysten/sui.js/transactions';\nimport { WalletAccount } from '@mysten/wallet-standard';\n\nimport { SuiNetworks } from '@/types';\n\nimport { Scallop } from '../../models';\nimport { SupportStakeMarketCoins } from '../../types';\nimport { TransactionSubType } from '../../types/utils';\nimport { ScallopCoreBaseIntention } from '../scallopCoreBaseIntention';\n\nexport interface StakeSpoolIntentionData {\n amount: number | string;\n marketCoinName: SupportStakeMarketCoins;\n stakeAccountId?: string | null;\n}\n\nexport class StakeSpoolIntention extends ScallopCoreBaseIntention<StakeSpoolIntentionData> {\n txType: TransactionType.Other;\n\n txSubType: TransactionSubType.StakeSpool;\n\n constructor(public readonly data: StakeSpoolIntentionData) {\n super(data);\n }\n\n async build(input: {\n suiClient: SuiClient;\n account: WalletAccount;\n network: SuiNetworks;\n scallop: Scallop;\n }): Promise<TransactionBlock> {\n return input.scallop.client.stake(\n this.data.marketCoinName,\n Number(this.data.amount),\n undefined,\n input.account.address,\n );\n }\n\n static fromData(data: StakeSpoolIntentionData): StakeSpoolIntention {\n return new StakeSpoolIntention(data);\n }\n}\n","/* eslint-disable import/no-extraneous-dependencies */\nimport { TransactionType } from '@msafe/sui3-utils';\nimport { SuiClient } from '@mysten/sui.js/client';\nimport { TransactionBlock } from '@mysten/sui.js/transactions';\nimport { WalletAccount } from '@mysten/wallet-standard';\n\nimport { SuiNetworks } from '@/types';\n\nimport { Scallop } from '../../models';\nimport { SupportAssetCoins, TransactionSubType } from '../../types';\nimport { ScallopCoreBaseIntention } from '../scallopCoreBaseIntention';\n\nexport interface SupplyLendingIntentionData {\n amount: number | string;\n coinName: SupportAssetCoins;\n}\n\nexport class SupplyLendingIntention extends ScallopCoreBaseIntention<SupplyLendingIntentionData> {\n txType: TransactionType.Other;\n\n txSubType: TransactionSubType.SupplyLending;\n\n constructor(public readonly data: SupplyLendingIntentionData) {\n super(data);\n }\n\n async build(input: {\n suiClient: SuiClient;\n account: WalletAccount;\n network: SuiNetworks;\n scallop: Scallop;\n }): Promise<TransactionBlock> {\n return input.scallop.client.deposit(this.data.coinName, Number(this.data.amount), input.account.address);\n }\n\n static fromData(data: SupplyLendingIntentionData): SupplyLendingIntention {\n return new SupplyLendingIntention(data);\n }\n}\n","import { TransactionType } from '@msafe/sui3-utils';\nimport { SuiClient } from '@mysten/sui.js/client';\nimport { TransactionBlock } from '@mysten/sui.js/transactions';\nimport { WalletAccount } from '@mysten/wallet-standard';\n\nimport { SuiNetworks } from '@/types';\n\nimport { Scallop } from '../../models';\nimport { SupportStakeMarketCoins } from '../../types';\nimport { TransactionSubType } from '../../types/utils';\nimport { ScallopCoreBaseIntention } from '../scallopCoreBaseIntention';\n\nexport interface UnstakeSpoolIntentionData {\n amount: number | string;\n marketCoinName: SupportStakeMarketCoins;\n stakeAccountId: string | null;\n}\n\nexport class UnstakeSpoolIntention extends ScallopCoreBaseIntention<UnstakeSpoolIntentionData> {\n txType: TransactionType.Other;\n\n txSubType: TransactionSubType.UnstakeSpool;\n\n constructor(public readonly data: UnstakeSpoolIntentionData) {\n super(data);\n }\n\n async build(input: {\n suiClient: SuiClient;\n account: WalletAccount;\n network: SuiNetworks;\n scallop: Scallop;\n }): Promise<TransactionBlock> {\n return input.scallop.client.unstake(\n this.data.marketCoinName,\n Number(this.data.amount),\n undefined,\n input.account.address,\n );\n }\n\n static fromData(data: UnstakeSpoolIntentionData): UnstakeSpoolIntention {\n return new UnstakeSpoolIntention(data);\n }\n}\n","/* eslint-disable import/no-extraneous-dependencies */\nimport { TransactionType } from '@msafe/sui3-utils';\nimport { SuiClient } from '@mysten/sui.js/client';\nimport { TransactionBlock } from '@mysten/sui.js/transactions';\nimport { WalletAccount } from '@mysten/wallet-standard';\n\nimport { SuiNetworks } from '@/types';\n\nimport { Scallop } from '../../models';\nimport { SupportAssetCoins, TransactionSubType } from '../../types';\nimport { ScallopCoreBaseIntention } from '../scallopCoreBaseIntention';\n\nexport interface WithdrawAndUnstakeLendingIntentionData {\n amount: number | undefined;\n coinName: SupportAssetCoins;\n stakeAccountId: { id: string; coin: number }[];\n}\n\nexport class WithdrawAndUnstakeLendingIntention extends ScallopCoreBaseIntention<WithdrawAndUnstakeLendingIntentionData> {\n txType: TransactionType.Other;\n\n txSubType: TransactionSubType.WithdrawAndUnstakeLending;\n\n constructor(public readonly data: WithdrawAndUnstakeLendingIntentionData) {\n super(data);\n }\n\n async build(input: {\n suiClient: SuiClient;\n account: WalletAccount;\n network: SuiNetworks;\n scallop: Scallop;\n }): Promise<TransactionBlock> {\n return input.scallop.client.unstakeAndWithdraw(\n this.data.coinName,\n Number(this.data.amount),\n this.data.stakeAccountId,\n );\n }\n\n static fromData(data: WithdrawAndUnstakeLendingIntentionData): WithdrawAndUnstakeLendingIntention {\n return new WithdrawAndUnstakeLendingIntention(data);\n }\n}\n","import { TransactionType } from '@msafe/sui3-utils';\nimport { SuiClient } from '@mysten/sui.js/client';\nimport { TransactionBlock } from '@mysten/sui.js/transactions';\nimport { WalletAccount } from '@mysten/wallet-standard';\n\nimport { SuiNetworks } from '@/types';\n\nimport { Scallop } from '../../models';\nimport { SupportCollateralCoins } from '../../types';\nimport { TransactionSubType } from '../../types/utils';\nimport { ScallopCoreBaseIntention } from '../scallopCoreBaseIntention';\n\nexport interface WithdrawCollateralIntentionData {\n collateralCoinName: SupportCollateralCoins;\n amount: number | string;\n obligationId: string;\n obligationKey: string;\n}\n\nexport class WithdrawCollateralIntention extends ScallopCoreBaseIntention<WithdrawCollateralIntentionData> {\n txType: TransactionType.Other;\n\n txSubType: TransactionSubType.WithdrawCollateral;\n\n constructor(public readonly data: WithdrawCollateralIntentionData) {\n super(data);\n }\n\n async build(input: {\n suiClient: SuiClient;\n account: WalletAccount;\n network: SuiNetworks;\n scallop: Scallop;\n }): Promise<TransactionBlock> {\n return input.scallop.client.withdrawCollateral(\n this.data.collateralCoinName,\n Number(this.data.amount),\n this.data.obligationId,\n this.data.obligationKey,\n input.account.address,\n );\n }\n\n static fromData(data: WithdrawCollateralIntentionData): WithdrawCollateralIntention {\n return new WithdrawCollateralIntention(data);\n }\n}\n","import { TransactionType } from '@msafe/sui3-utils';\nimport { SuiClient } from '@mysten/sui.js/client';\nimport { TransactionBlock } from '@mysten/sui.js/transactions';\nimport { WalletAccount } from '@mysten/wallet-standard';\n\nimport { Scallop } from '../../models';\nimport { SupportAssetCoins } from '../../types';\nimport { SuiNetworks, TransactionSubType } from '../../types/utils';\nimport { ScallopCoreBaseIntention } from '../scallopCoreBaseIntention';\n\nexport interface WithdrawLendingIntentionData {\n amount: string | number;\n coinName: SupportAssetCoins;\n}\n\nexport class WithdrawLendingIntention extends ScallopCoreBaseIntention<WithdrawLendingIntentionData> {\n txType: TransactionType.Other;\n\n txSubType: TransactionSubType.WithdrawLending;\n\n constructor(public readonly data: WithdrawLendingIntentionData) {\n super(data);\n }\n\n async build(input: {\n suiClient: SuiClient;\n account: WalletAccount;\n network: SuiNetworks;\n scallop: Scallop;\n }): Promise<TransactionBlock> {\n return input.scallop.client.withdraw(this.data.coinName, Number(this.data.amount), input.account.address);\n }\n\n static fromData(data: WithdrawLendingIntentionData): WithdrawLendingIntention {\n return new WithdrawLendingIntention(data);\n }\n}\n","import { TransactionType } from '@msafe/sui3-utils';\nimport { SuiClient } from '@mysten/sui.js/client';\nimport { TransactionBlock } from '@mysten/sui.js/transactions';\nimport { WalletAccount } from '@mysten/wallet-standard';\n\nimport { SuiNetworks } from '@/types';\n\nimport { Scallop } from '../../models';\nimport { TransactionSubType } from '../../types/utils';\nimport { ScallopCoreBaseIntention } from '../scallopCoreBaseIntention';\n\nexport interface BindReferralIntentionData {\n veScaKey: string;\n}\n\nexport class BindReferralIntention extends ScallopCoreBaseIntention<BindReferralIntentionData> {\n txType: TransactionType.Other;\n\n txSubType: TransactionSubType.BindReferral;\n\n constructor(public readonly data: BindReferralIntentionData) {\n super(data);\n }\n\n async build(input: {\n suiClient: SuiClient;\n account: WalletAccount;\n network: SuiNetworks;\n scallop: Scallop;\n }): Promise<TransactionBlock> {\n return input.scallop.client.bindReferral(this.data.veScaKey);\n }\n\n static fromData(data: BindReferralIntentionData): BindReferralIntention {\n return new BindReferralIntention(data);\n }\n}\n","import { TransactionType } from '@msafe/sui3-utils';\nimport { SuiClient } from '@mysten/sui.js/client';\nimport { TransactionBlock } from '@mysten/sui.js/transactions';\nimport { WalletAccount } from '@mysten/wallet-standard';\n\nimport { SuiNetworks } from '@/types';\n\nimport { Scallop } from '../../models';\nimport { TransactionSubType } from '../../types/utils';\nimport { ScallopCoreBaseIntention } from '../scallopCoreBaseIntention';\n\nexport interface ClaimRevenueReferralIntentionData {\n veScaKey: string;\n coins: string[];\n}\n\nexport class ClaimRevenueReferralIntention extends ScallopCoreBaseIntention<ClaimRevenueReferralIntentionData> {\n txType: TransactionType.Other;\n\n txSubType: TransactionSubType.ClaimRevenueReferral;\n\n constructor(public readonly data: ClaimRevenueReferralIntentionData) {\n super(data);\n }\n\n async build(input: {\n suiClient: SuiClient;\n account: WalletAccount;\n network: SuiNetworks;\n scallop: Scallop;\n }): Promise<TransactionBlock> {\n return input.scallop.client.claimRevenuReferral(this.data.veScaKey, this.data.coins);\n }\n\n static fromData(data: ClaimRevenueReferralIntentionData): ClaimRevenueReferralIntention {\n return new ClaimRevenueReferralIntention(data);\n }\n}\n","import { TransactionType } from '@msafe/sui3-utils';\nimport { SuiClient } from '@mysten/sui.js/client';\nimport { TransactionBlock } from '@mysten/sui.js/transactions';\nimport { WalletAccount } from '@mysten/wallet-standard';\n\nimport { SuiNetworks } from '@/types';\n\nimport { Scallop } from '../../models';\nimport { TransactionSubType } from '../../types/utils';\nimport { ScallopCoreBaseIntention } from '../scallopCoreBaseIntention';\n\n// eslint-disable-next-line @typescript-eslint/no-empty-interface\nexport interface CreateReferralLinkIntentionData {}\n\nexport class CreateReferralLinkIntention extends ScallopCoreBaseIntention<CreateReferralLinkIntentionData> {\n txType: TransactionType.Other;\n\n txSubType: TransactionSubType.CreateReferralLink;\n\n constructor(public readonly data: CreateReferralLinkIntentionData) {\n super(data);\n }\n\n async build(input: {\n suiClient: SuiClient;\n account: WalletAccount;\n network: SuiNetworks;\n scallop: Scallop;\n }): Promise<TransactionBlock> {\n return input.scallop.client.createReferralLink();\n }\n\n static fromData(data: CreateReferralLinkIntentionData): CreateReferralLinkIntention {\n return new CreateReferralLinkIntention(data);\n }\n}\n","import { TransactionType } from '@msafe/sui3-utils';\nimport { SuiClient } from '@mysten/sui.js/client';\nimport { TransactionBlock } from '@mysten/sui.js/transactions';\nimport { WalletAccount } from '@mysten/wallet-standard';\n\nimport { SuiNetworks } from '@/types';\n\nimport { Scallop } from '../../models';\nimport { TransactionSubType } from '../../types/utils';\nimport { ScallopCoreBaseIntention } from '../scallopCoreBaseIntention';\n\nexport interface ExtendPeriodAndStakeMoreIntentionData {\n amount: number;\n veScaKey: string;\n lockPeriodInDays: number;\n obligationId: string | undefined;\n obligationKey: string | undefined;\n isOldBorrowIncentive: boolean;\n isObligationLocked: boolean;\n}\n\nexport class ExtendPeriodAndStakeMoreIntention extends ScallopCoreBaseIntention<ExtendPeriodAndStakeMoreIntentionData> {\n txType: TransactionType.Other;\n\n txSubType: TransactionSubType.ExtendPeriodAndStakeMore;\n\n constructor(public readonly data: ExtendPeriodAndStakeMoreIntentionData) {\n super(data);\n }\n\n async build(input: {\n suiClient: SuiClient;\n account: WalletAccount;\n network: SuiNetworks;\n scallop: Scallop;\n }): Promise<TransactionBlock> {\n return input.scallop.client.extendPeriodAndStakeMoreSca(\n this.data.amount,\n this.data.veScaKey,\n this.data.lockPeriodInDays,\n this.data.obligationId,\n this.data.obligationKey,\n this.data.isObligationLocked,\n this.data.isOldBorrowIncentive,\n input.account.address,\n );\n }\n\n static fromData(data: ExtendPeriodAndStakeMoreIntentionData): ExtendPeriodAndStakeMoreIntention {\n return new ExtendPeriodAndStakeMoreIntention(data);\n }\n}\n","import { TransactionType } from '@msafe/sui3-utils';\nimport { SuiClient } from '@mysten/sui.js/client';\nimport { TransactionBlock } from '@mysten/sui.js/transactions';\nimport { WalletAccount } from '@mysten/wallet-standard';\n\nimport { SuiNetworks } from '@/types';\n\nimport { Scallop } from '../../models';\nimport { TransactionSubType } from '../../types/utils';\nimport { ScallopCoreBaseIntention } from '../scallopCoreBaseIntention';\n\nexport interface ExtendStakePeriodIntentionData {\n isObligationLocked: boolean;\n isOldBorrowIncentive: boolean;\n obligationId: string | undefined;\n obligationKey: string | undefined;\n lockPeriodInDays: number | undefined;\n veScaKey: string | undefined;\n}\n\nexport class ExtendStakePeriodIntention extends ScallopCoreBaseIntention<ExtendStakePeriodIntentionData> {\n txType: TransactionType.Other;\n\n txSubType: TransactionSubType.ExtendStakePeriod;\n\n constructor(public readonly data: ExtendStakePeriodIntentionData) {\n super(data);\n }\n\n async build(input: {\n suiClient: SuiClient;\n account: WalletAccount;\n network: SuiNetworks;\n scallop: Scallop;\n }): Promise<TransactionBlock> {\n return input.scallop.client.extendStakeScaLockPeriod(\n this.data.lockPeriodInDays,\n this.data.veScaKey,\n this.data.obligationId,\n this.data.obligationKey,\n this.data.isObligationLocked,\n this.data.isOldBorrowIncentive,\n input.account.address,\n );\n }\n\n static fromData(data: ExtendStakePeriodIntentionData): ExtendStakePeriodIntention {\n return new ExtendStakePeriodIntention(data);\n }\n}\n","import { TransactionType } from '@msafe/sui3-utils';\nimport { SuiClient } from '@mysten/sui.js/client';\nimport { TransactionBlock } from '@mysten/sui.js/transactions';\nimport { WalletAccount } from '@mysten/wallet-standard';\n\nimport { SuiNetworks } from '@/types';\n\nimport { Scallop } from '../../models';\nimport { TransactionSubType } from '../../types';\nimport { ScallopCoreBaseIntention } from '../scallopCoreBaseIntention';\n\nexport interface RedeemScaIntentionData {\n veScaKey: string;\n}\n\nexport class RedeemScaIntention extends ScallopCoreBaseIntention<RedeemScaIntentionData> {\n txType: TransactionType.Other;\n\n txSubType: TransactionSubType.RedeemSca;\n\n constructor(public readonly data: RedeemScaIntentionData) {\n super(data);\n }\n\n async build(input: {\n suiClient: SuiClient;\n account: WalletAccount;\n network: SuiNetworks;\n scallop: Scallop;\n }): Promise<TransactionBlock> {\n return input.scallop.client.redeemSca(this.data.veScaKey);\n }\n\n static fromData(data: RedeemScaIntentionData): RedeemScaIntention {\n return new RedeemScaIntention(data);\n }\n}\n","import { TransactionType } from '@msafe/sui3-utils';\nimport { SuiClient } from '@mysten/sui.js/client';\nimport { TransactionBlock } from '@mysten/sui.js/transactions';\nimport { WalletAccount } from '@mysten/wallet-standard';\n\nimport { SuiNetworks } from '@/types';\n\nimport { Scallop } from '../../models';\nimport { TransactionSubType } from '../../types/utils';\nimport { ScallopCoreBaseIntention } from '../scallopCoreBaseIntention';\n\nexport interface RenewExpStakePeriodIntentionData {\n amount: number;\n lockPeriodInDays: number;\n vescaKey: string;\n isHaveRedeem: boolean;\n obligation?: string;\n obligationKey?: string;\n isObligationLocked: boolean;\n isOldBorrowIncentive: boolean;\n}\n\nexport class RenewExpStakePeriodIntention extends ScallopCoreBaseIntention<RenewExpStakePeriodIntentionData> {\n txType: TransactionType.Other;\n\n txSubType: TransactionSubType.RenewExpStakePeriod;\n\n constructor(public readonly data: RenewExpStakePeriodIntentionData) {\n super(data);\n }\n\n async build(input: {\n suiClient: SuiClient;\n account: WalletAccount;\n network: SuiNetworks;\n scallop: Scallop;\n }): Promise<TransactionBlock> {\n return input.scallop.client.renewExpiredStakeSca(\n this.data.amount,\n this.data.lockPeriodInDays,\n this.data.vescaKey,\n this.data.isHaveRedeem,\n this.data.obligation,\n this.data.obligationKey,\n this.data.isObligationLocked,\n this.data.isOldBorrowIncentive,\n input.account.address,\n );\n }\n\n static fromData(data: RenewExpStakePeriodIntentionData): RenewExpStakePeriodIntention {\n return new RenewExpStakePeriodIntention(data);\n }\n}\n","import { TransactionType } from '@msafe/sui3-utils';\nimport { SuiClient } from '@mysten/sui.js/client';\nimport { TransactionBlock } from '@mysten/sui.js/transactions';\nimport { WalletAccount } from '@mysten/wallet-standard';\n\nimport { SuiNetworks } from '@/types';\n\nimport { Scallop } from '../../models';\nimport { TransactionSubType } from '../../types/utils';\nimport { ScallopCoreBaseIntention } from '../scallopCoreBaseIntention';\n\nexport interface StakeScaIntentionData {\n amount: number;\n isObligationLocked: boolean;\n isOldBorrowIncentive: boolean;\n obligationId: string | undefined;\n obligationKey: string | undefined;\n lockPeriodInDays: number | undefined;\n veScaKey: string | undefined;\n}\n\nexport class StakeScaIntention extends ScallopCoreBaseIntention<StakeScaIntentionData> {\n txType: TransactionType.Other;\n\n txSubType: TransactionSubType.StakeSca;\n\n constructor(public readonly data: StakeScaIntentionData) {\n super(data);\n }\n\n async build(input: {\n suiClient: SuiClient;\n account: WalletAccount;\n network: SuiNetworks;\n scallop: Scallop;\n }): Promise<TransactionBlock> {\n return input.scallop.client.stakeSca(\n this.data.amount,\n this.data.isObligationLocked,\n this.data.isOldBorrowIncentive,\n this.data.obligationId,\n this.data.obligationKey,\n this.data.lockPeriodInDays,\n this.data.veScaKey,\n input.account.address,\n );\n }\n\n static fromData(data: StakeScaIntentionData): StakeScaIntention {\n return new StakeScaIntention(data);\n }\n}\n","/* eslint-disable import/no-extraneous-dependencies */\nimport { TransactionType } from '@msafe/sui3-utils';\nimport { SuiClient } from '@mysten/sui.js/client';\nimport { TransactionBlock } from '@mysten/sui.js/transactions';\nimport { WalletAccount } from '@mysten/wallet-standard';\n\nimport { SuiNetworks } from '@/types';\n\nimport { Scallop } from '../../models';\nimport { SupportAssetCoins, TransactionSubType } from '../../types';\nimport { ScallopCoreBaseIntention } from '../scallopCoreBaseIntention';\n\nexport interface SupplyAndStakeLendingIntentionData {\n amount: number | string;\n coinName: SupportAssetCoins;\n stakeAccountId?: string | null;\n}\n\nexport class SupplyAndStakeLendingIntention extends ScallopCoreBaseIntention<SupplyAndStakeLendingIntentionData> {\n txType: TransactionType.Other;\n\n txSubType: TransactionSubType.SupplyAndStakeLending;\n\n constructor(public readonly data: SupplyAndStakeLendingIntentionData) {\n super(data);\n }\n\n async build(input: {\n suiClient: SuiClient;\n account: WalletAccount;\n network: SuiNetworks;\n scallop: Scallop;\n }): Promise<TransactionBlock> {\n return input.scallop.client.supplyAndStake(\n this.data.coinName,\n Number(this.data.amount),\n this.data.stakeAccountId,\n input.account.address,\n );\n }\n\n static fromData(data: SupplyAndStakeLendingIntentionData): SupplyAndStakeLendingIntention {\n return new SupplyAndStakeLendingIntention(data);\n }\n}\n","import { TransactionType } from '@msafe/sui3-utils';\nimport { SuiClient } from '@mysten/sui.js/client';\nimport { TransactionBlock } from '@mysten/sui.js/transactions';\nimport { WalletAccount } from '@mysten/wallet-standard';\n\nimport { SuiNetworks } from '@/types';\n\nimport { Scallop } from '../../models';\nimport { TransactionSubType } from '../../types/utils';\nimport { ScallopCoreBaseIntention } from '../scallopCoreBaseIntention';\n\nexport interface WithdrawStakedScaIntentionData {\n vescaKey?: string;\n}\n\nexport class WithdrawStakedScaIntention extends ScallopCoreBaseIntention<WithdrawStakedScaIntentionData> {\n txType: TransactionType.Other;\n\n txSubType: TransactionSubType.WithdrawStakedSca;\n\n constructor(public readonly data: WithdrawStakedScaIntentionData) {\n super(data);\n }\n\n async build(input: {\n suiClient: SuiClient;\n account: WalletAccount;\n network: SuiNetworks;\n scallop: Scallop;\n }): Promise<TransactionBlock> {\n return input.scallop.client.withdrawUnlockedSca(this.data.vescaKey, input.account.address);\n }\n\n static fromData(data: WithdrawStakedScaIntentionData): WithdrawStakedScaIntention {\n return new WithdrawStakedScaIntention(data);\n }\n}\n","import { API_BASE_URL } from '../constants';\nimport type { ScallopAddressParams, AddressesInterface, AddressStringPath } from '../types';\n\n/**\n * @description\n * It provides methods for managing addresses.\n *\n * @example\n * ```typescript\n * const scallopAddress = new ScallopAddress(<parameters>);\n * scallopAddress.<address functions>();\n * await scallopAddress.<address async functions>();\n * ```\n */\nexport class ScallopAddress {\n private id: string;\n\n private addresses: AddressesInterface;\n\n public constructor(params: ScallopAddressParams) {\n const { id } = params;\n this.id = id;\n }\n\n /**\n * Get addresses API id.\n *\n * @return The addresses API id.\n */\n public getId() {\n return this.id;\n }\n\n /**\n * Get the addresses, If `network` is not provided, returns the current\n * addresses or the default network addresses in the addresses map.\n *\n * @param network - Specifies which network's addresses you want to get.\n */\n public getAddresses() {\n return this.addresses;\n }\n\n /**\n * Get the address at the provided path.\n *\n * @param path - The path of the address to get.\n * @return The address at the provided path.\n */\n public get(path: AddressStringPath): string {\n if (!this.addresses) {\n throw new Error(`Failed to fetch address ${this.id}`);\n }\n const value = path\n .split('.')\n .reduce(\n (nestedAddressObj: any, key: string) =>\n typeof nestedAddressObj === 'object' ? nestedAddressObj[key] : nestedAddressObj,\n this.addresses,\n );\n return value;\n }\n\n public async read() {\n const options = {\n method: 'GET',\n headers: new Headers({ 'Content-Type': 'application/json' }),\n } as const;\n\n const response = await fetch(`${API_BASE_URL}/addresses/${this.id}`, options);\n if (response.status === 200) {\n const responseData = await response.json();\n\n if ('mainnet' in responseData) {\n this.addresses = responseData.mainnet;\n return;\n }\n throw new Error('Mainnet key is not in address!');\n }\n throw new Error(`Failed to fetch address with id ${this.id}`);\n }\n}\n","import type { SuiClient } from '@mysten/sui.js/client';\nimport { TransactionBlock, TransactionObjectArgument, TransactionResult } from '@mysten/sui.js/transactions';\nimport BigNumber from 'bignumber.js';\n\nimport { ScallopAddress } from './scallopAddress';\nimport { ScallopBuilder } from './scallopBuilder';\nimport { ScallopQuery } from './scallopQuery';\nimport { ScallopUtils } from './scallopUtils';\nimport { generateBorrowIncentiveQuickMethod } from '../builders/borrowIncentiveBuilder';\nimport { generateCoreQuickMethod } from '../builders/coreBuilder';\nimport { generateReferralNormalMethod, generateReferralQuickMethod } from '../builders/referralBuilder';\nimport { generateSCoinNormalMethod } from '../builders/sCoinBuilder';\nimport { SlippageTxBuilder } from '../builders/slipPageBuilder';\nimport { generateSpoolQuickMethod } from '../builders/spoolBuilder';\nimport { generateQuickVeScaMethod } from '../builders/vescaBuilder';\nimport { SCA_COIN_TYPE, SUPPORT_BORROW_INCENTIVE_POOLS, SUPPORT_SCOIN, SUPPORT_SPOOLS } from '../constants';\n// eslint-disable-next-line import/no-cycle\nimport { DeepBookSwap } from '../swap/deepbook/swap';\nimport type {\n ScallopClientParams,\n SupportPoolCoins,\n SupportCollateralCoins,\n SupportStakeMarketCoins,\n BorrowIncentiveParams,\n SpoolIncentiveParams,\n SupportBorrowIncentiveRewardCoins,\n SupportSCoin,\n SuiObjectArg,\n} from '../types';\n\n/**\n * @description\n * It provides contract interaction operations for general users.\n *\n * @example\n * ```typescript\n * const scallopClient = new ScallopClient(<parameters>);\n * await scallopClient.init();\n * scallopClient.<client functions>();\n * await scallopClient.<client async functions>();\n * ```\n */\nexport class ScallopClient {\n public readonly params: ScallopClientParams;\n\n public client: SuiClient;\n\n private address: ScallopAddress;\n\n public builder: ScallopBuilder;\n\n public query: ScallopQuery;\n\n public utils: ScallopUtils;\n\n public walletAddress: string;\n\n public deepbookSwap: DeepBookSwap;\n\n public constructor(params: ScallopClientParams, address: ScallopAddress) {\n this.params = params;\n this.client = params.client;\n\n this.address = address;\n this.utils = new ScallopUtils(params, this.address);\n\n this.query = new ScallopQuery(params, {\n address: this.address,\n utils: this.utils,\n });\n this.builder = new ScallopBuilder(params, {\n address: this.address,\n query: this.query,\n utils: this.utils,\n });\n\n this.deepbookSwap = new DeepBookSwap({\n client: this.client,\n currentAddress: this.params.walletAddress,\n scallopUtils: this.utils,\n });\n }\n\n /* ==================== Query Method ==================== */\n\n /**\n * Get obligations data.\n *\n * @description\n * This method might be @deprecated in the future, please use the {@link ScallopQuery} query instance instead.\n *\n * @param ownerAddress - The owner address.\n * @return Obligations data.\n */\n public async getObligations(ownerAddress?: string) {\n const owner = ownerAddress || this.params.walletAddress;\n return this.query.getObligations(owner);\n }\n\n /**\n * Query all stake accounts data.\n *\n * @description\n * This method might be @deprecated in the future, please use the {@link ScallopQuery} query instance instead.\n *\n * @param ownerAddress - The owner address.\n * @return All stake accounts data.\n */\n async getAllStakeAccounts(ownerAddress?: string) {\n const owner = ownerAddress || this.params.walletAddress;\n return this.query.getAllStakeAccounts(owner);\n }\n\n /**\n * Query stake account data.\n *\n * @description\n * This method might be @deprecated in the future, please use the {@link ScallopQuery} query instance instead.\n *\n * @param stakeMarketCoinName - Support stake market coin.\n * @param ownerAddress - The owner address.\n * @return Stake accounts data.\n */\n async getStakeAccounts(stakeMarketCoinName: SupportStakeMarketCoins, ownerAddress?: string) {\n const owner = ownerAddress || this.params.walletAddress;\n return this.query.getStakeAccounts(stakeMarketCoinName, owner);\n }\n\n /**\n * Query stake pool data.\n *\n * @description\n * This method might be @deprecated in the future, please use the {@link ScallopQuery} query instance instead.\n *\n * @param stakeMarketCoinName - Support stake market coin.\n * @return Stake pool data.\n */\n async getStakePool(stakeMarketCoinName: SupportStakeMarketCoins) {\n return this.query.getStakePool(stakeMarketCoinName);\n }\n\n /**\n * Query reward pool data.\n *\n * @description\n * This method might be @deprecated in the future, please use the {@link ScallopQuery} query instance instead.\n *\n * @param stakeMarketCoinName - Support stake market coin.\n * @return Reward pool data.\n */\n async getStakeRewardPool(stakeMarketCoinName: SupportStakeMarketCoins) {\n return this.query.getStakeRewardPool(stakeMarketCoinName);\n }\n\n /* ==================== Core Method ==================== */\n\n /**\n * Open obligation.\n *\n * @param sign - Decide to directly sign the transaction or return the transaction block.\n * @return Transaction block response or transaction block.\n */\n public async openObligation(walletAddress?: string): Promise<TransactionBlock> {\n const txBlock = new TransactionBlock();\n const coreQuickMethod = await generateCoreQuickMethod({ builder: this.builder, txBlock });\n const borrowIncentiveMethod = await generateBorrowIncentiveQuickMethod({ builder: this.builder, txBlock });\n const sender = walletAddress || this.params.walletAddress;\n txBlock.setSender(sender);\n const [obligationId, obligationKey, hotPotato] = coreQuickMethod.normalMethod.openObligation();\n borrowIncentiveMethod.normalMethod.stakeObligation(obligationId, obligationKey);\n coreQuickMethod.normalMethod.returnObligation(obligationId, hotPotato);\n txBlock.transferObjects([obligationKey], sender);\n return txBlock;\n }\n\n /**\n * Deposit collateral into the specific pool.\n *\n * @param collateralCoinName - Types of collateral coin.\n * @param amount - The amount of coins would deposit.\n * @param sign - Decide to directly sign the transaction or return the transaction block.\n * @param obligationId - The obligation object.\n * @param walletAddress - The wallet address of the owner.\n * @return Transaction block response or transaction block.\n */\n public async depositCollateral(\n collateralCoinName: SupportCollateralCoins,\n amount: number,\n obligationId?: string,\n walletAddress?: string,\n ): Promise<TransactionBlock> {\n const txBlock = new TransactionBlock();\n const sender = walletAddress || this.params.walletAddress;\n txBlock.setSender(sender);\n const quickMethod = await generateCoreQuickMethod({ builder: this.builder, txBlock });\n\n const obligations = await this.query.getObligations(sender);\n const specificObligationId = obligationId || obligations?.[0]?.id;\n if (specificObligationId) {\n await quickMethod.addCollateralQuick(amount, collateralCoinName, specificObligationId);\n } else {\n const [obligation, obligationKey, hotPotato] = quickMethod.normalMethod.openObligation();\n await quickMethod.addCollateralQuick(amount, collateralCoinName, obligation);\n quickMethod.normalMethod.returnObligation(obligation, hotPotato);\n txBlock.transferObjects([obligationKey], sender);\n }\n return txBlock;\n }\n\n /**\n * Withdraw collateral from the specific pool.\n *\n * @param collateralCoinName - Types of collateral coin.\n * @param amount - The amount of coins would deposit.\n * @param sign - Decide to directly sign the transaction or return the transaction block.\n * @param obligationId - The obligation object.\n * @param obligationKey - The obligation key object to verifying obligation authority.\n * @param walletAddress - The wallet address of the owner.\n * @return Transaction block response or transaction block.\n */\n public async withdrawCollateral(\n collateralCoinName: SupportCollateralCoins,\n amount: number,\n obligationId: string,\n obligationKey: string,\n walletAddress?: string,\n ): Promise<TransactionBlock> {\n const txBlock = new TransactionBlock();\n const quickMethod = await generateCoreQuickMethod({ builder: this.builder, txBlock });\n const sender = walletAddress || this.params.walletAddress;\n txBlock.setSender(sender);\n\n const collateralCoin = await quickMethod.takeCollateralQuick(\n amount,\n collateralCoinName,\n obligationId,\n obligationKey,\n );\n txBlock.transferObjects([collateralCoin], sender);\n return txBlock;\n }\n\n /**\n * Deposit asset into the specific pool.\n *\n * @param poolCoinName - Types of pool coin.\n * @param amount - The amount of coins would deposit.\n * @param sign - Decide to directly sign the transaction or return the transaction block.\n * @param walletAddress - The wallet address of the owner.\n * @return Transaction block response or transaction block.\n */\n public async deposit(\n poolCoinName: SupportPoolCoins,\n amount: number,\n walletAddress?: string,\n ): Promise<TransactionBlock> {\n const txBlock = new TransactionBlock();\n const quickMethod = await generateCoreQuickMethod({\n builder: this.builder,\n txBlock,\n });\n const scoinMethod = await generateSCoinNormalMethod({ builder: this.builder, txBlock });\n const sender = walletAddress || this.params.walletAddress;\n txBlock.setSender(sender);\n\n const marketCoin = await quickMethod.depositQuick(amount, poolCoinName, walletAddress);\n const parseScoin = this.utils.parseMarketCoinName(poolCoinName);\n if (!SUPPORT_SCOIN.includes(parseScoin as SupportSCoin)) {\n txBlock.transferObjects([marketCoin], sender);\n } else {\n const scoin = scoinMethod.mintSCoin(parseScoin as SupportSCoin, marketCoin);\n txBlock.transferObjects([scoin], sender);\n }\n return txBlock;\n }\n\n /**\n * Withdraw asset from the specific pool, must return market coin.\n *\n * @param poolCoinName - Specific support pool coin name.\n * @param amount - The amount of coins would withdraw.\n * @param sign - Decide to directly sign the transaction or return the transaction block.\n * @param walletAddress - The wallet address of the owner.\n * @return Transaction block response or transaction block.\n */\n public async withdraw(\n poolCoinName: SupportPoolCoins,\n amount: number,\n walletAddress?: string,\n ): Promise<TransactionBlock> {\n const txBlock = new TransactionBlock();\n const sender = walletAddress || this.params.walletAddress;\n const quickMethod = await generateCoreQuickMethod({\n builder: this.builder,\n txBlock,\n });\n txBlock.setSender(sender);\n\n const coin = await quickMethod.withdrawQuick(amount, poolCoinName);\n txBlock.transferObjects([coin], sender);\n return txBlock;\n }\n\n /**\n * Borrow asset from the specific pool.\n *\n * @param poolCoinName - Specific support pool coin name.\n * @param amount - The amount of coins would borrow.\n * @param sign - Decide to directly sign the transaction or return the transaction block.\n * @param obligationId - The obligation object.\n * @param obligationKey - The obligation key object to verifying obligation authority.\n * @param walletAddress - The wallet address of the owner.\n * @return Transaction block response or transaction block.\n */\n public async borrow(\n poolCoinName: SupportPoolCoins,\n amount: number,\n obligationId: string,\n obligationKey: string,\n walletAddress?: string,\n ): Promise<TransactionBlock> {\n const txBlock = new TransactionBlock();\n const quickMethod = await generateCoreQuickMethod({ builder: this.builder, txBlock });\n const borrowIncentiveQuickMethod = await generateBorrowIncentiveQuickMethod({\n builder: this.builder,\n txBlock,\n });\n const sender = walletAddress || this.params.walletAddress;\n txBlock.setSender(sender);\n\n const availableStake = (SUPPORT_BORROW_INCENTIVE_POOLS as readonly SupportPoolCoins[]).includes(poolCoinName);\n if (availableStake) {\n await borrowIncentiveQuickMethod.unstakeObligationQuick(obligationId, obligationKey);\n }\n const coin = await quickMethod.borrowQuick(amount, poolCoinName, obligationId, obligationKey);\n txBlock.transferObjects([coin], sender);\n if (availableStake) {\n await borrowIncentiveQuickMethod.stakeObligationQuick(obligationId, obligationKey);\n }\n return txBlock;\n }\n\n /**\n * Borrow asset from the specific pool with boost from SCA stake.\n *\n * @param poolCoinName - Specific support pool coin name.\n * @param amount - The amount of coins would borrow.\n * @param sign - Decide to directly sign the transaction or return the transaction block.\n * @param obligationId - The obligation object.\n * @param obligationKey - The obligation key object to verifying obligation authority.\n * @param veScaKey - The vesca key object to verifying sca staker.\n * @param walletAddress - The wallet address of the owner.\n * @return Transaction block response or transaction block.\n */\n public async borrowWithBoost(\n poolCoinName: SupportPoolCoins,\n amount: number,\n obligationId: string,\n obligationKey: string,\n veScaKey: string,\n walletAddress?: string,\n ): Promise<TransactionBlock> {\n const txBlock = new TransactionBlock();\n const quickMethod = await generateCoreQuickMethod({ builder: this.builder, txBlock });\n const borrowIncentiveQuickMethod = await generateBorrowIncentiveQuickMethod({\n builder: this.builder,\n txBlock,\n });\n const sender = walletAddress || this.params.walletAddress;\n txBlock.setSender(sender);\n\n const availableStake = (SUPPORT_BORROW_INCENTIVE_POOLS as readonly SupportPoolCoins[]).includes(poolCoinName);\n if (availableStake) {\n await borrowIncentiveQuickMethod.unstakeObligationQuick(obligationId, obligationKey);\n }\n const coin = await quickMethod.borrowQuick(amount, poolCoinName, obligationId, obligationKey);\n txBlock.transferObjects([coin], sender);\n if (availableStake) {\n await borrowIncentiveQuickMethod.stakeObligationWithVeScaQuick(obligationId, obligationKey, veScaKey);\n }\n return txBlock;\n }\n\n /**\n * Borrow asset from the specific pool with boost from SCA stake.\n *\n * @param poolCoinName - Specific support pool coin name.\n * @param amount - The amount of coins would borrow.\n * @param sign - Decide to directly sign the transaction or return the transaction block.\n * @param obligationId - The obligation object.\n * @param obligationKey - The obligation key object to verifying obligation authority.\n * @param veScaKey - The vesca key object to verifying sca staker.\n * @param walletAddress - The wallet address of the owner.\n * @return Transaction block response or transaction block.\n */\n public async borrowWithReferral(\n poolCoinName: SupportPoolCoins,\n amount: number,\n obligationId: string,\n obligationKey: string,\n veScaKey: string | undefined,\n walletAddress?: string,\n ): Promise<TransactionBlock> {\n const txBlock = new TransactionBlock();\n const quickMethod = await generateCoreQuickMethod({ builder: this.builder, txBlock });\n const borrowIncentiveQuickMethod = await generateBorrowIncentiveQuickMethod({\n builder: this.builder,\n txBlock,\n });\n const referralMethod = await generateReferralNormalMethod({ builder: this.builder, txBlock });\n const sender = walletAddress || this.params.walletAddress;\n txBlock.setSender(sender);\n\n const availableStake = (SUPPORT_BORROW_INCENTIVE_POOLS as readonly SupportPoolCoins[]).includes(poolCoinName);\n if (availableStake) {\n await borrowIncentiveQuickMethod.unstakeObligationQuick(obligationId, obligationKey);\n }\n const borrowReferral = referralMethod.claimReferralTicket(poolCoinName);\n const coin = await quickMethod.borrowWithReferralQuick(\n amount,\n poolCoinName,\n borrowReferral,\n obligationId,\n obligationKey,\n );\n referralMethod.burnReferralTicket(borrowReferral, poolCoinName);\n txBlock.transferObjects([coin], sender);\n if (availableStake && veScaKey) {\n await borrowIncentiveQuickMethod.stakeObligationWithVeScaQuick(obligationId, obligationKey, veScaKey);\n } else {\n await borrowIncentiveQuickMethod.stakeObligationQuick(obligationId, obligationKey);\n }\n return txBlock;\n }\n\n /**\n * Repay asset into the specific pool.\n *\n * @param poolCoinName - Specific support pool coin name.\n * @param amount - The amount of coins would repay.\n * @param sign - Decide to directly sign the transaction or return the transaction block.\n * @param obligationId - The obligation object.\n * @param walletAddress - The wallet address of the owner.\n * @return Transaction block response or transaction block.\n */\n public async repay(\n poolCoinName: SupportPoolCoins,\n amount: number,\n obligationId: string,\n obligationKey: string,\n walletAddress?: string,\n ): Promise<TransactionBlock> {\n const txBlock = new TransactionBlock();\n const quickMethod = await generateCoreQuickMethod({ builder: this.builder, txBlock });\n const borrowIncentiveQuickMethod = await generateBorrowIncentiveQuickMethod({\n builder: this.builder,\n txBlock,\n });\n const sender = walletAddress || this.params.walletAddress;\n txBlock.setSender(sender);\n\n const availableStake = (SUPPORT_BORROW_INCENTIVE_POOLS as readonly SupportPoolCoins[]).includes(poolCoinName);\n if (availableStake) {\n await borrowIncentiveQuickMethod.unstakeObligationQuick(obligationId, obligationKey);\n }\n await quickMethod.repayQuick(amount, poolCoinName, obligationId, sender);\n if (availableStake) {\n await borrowIncentiveQuickMethod.stakeObligationQuick(obligationId, obligationKey);\n }\n return txBlock;\n }\n\n /**\n * Repay asset into the specific pool.\n *\n * @param poolCoinName - Specific support pool coin name.\n * @param amount - The amount of coins would repay.\n * @param sign - Decide to directly sign the transaction or return the transaction block.\n * @param obligationId - The obligation object.\n * @param walletAddress - The wallet address of the owner.\n * @return Transaction block response or transaction block.\n */\n public async repayWithBoost(\n poolCoinName: SupportPoolCoins,\n amount: number,\n obligationId: string,\n veScaKey: string,\n walletAddress?: string,\n ): Promise<TransactionBlock> {\n const txBlock = new TransactionBlock();\n const quickMethod = await generateCoreQuickMethod({ builder: this.builder, txBlock });\n const borrowIncentiveQuickMethod = await generateBorrowIncentiveQuickMethod({\n builder: this.builder,\n txBlock,\n });\n const sender = walletAddress || this.params.walletAddress;\n txBlock.setSender(sender);\n\n const availableStake = (SUPPORT_BORROW_INCENTIVE_POOLS as readonly SupportPoolCoins[]).includes(poolCoinName);\n if (availableStake) {\n await borrowIncentiveQuickMethod.unstakeObligationQuick(obligationId, undefined);\n }\n await quickMethod.repayQuick(amount, poolCoinName, obligationId, sender);\n if (availableStake) {\n await borrowIncentiveQuickMethod.stakeObligationWithVeScaQuick(obligationId, undefined, veScaKey);\n }\n return txBlock;\n }\n\n /* ==================== Spool Method ==================== */\n\n /**\n * Create stake account.\n *\n * @param sign - Decide to directly sign the transaction or return the transaction block.\n * @param walletAddress - The wallet address of the owner.\n * @return Transaction block response or transaction block.\n */\n public async createStakeAccount(\n marketCoinName: SupportStakeMarketCoins,\n walletAddress?: string,\n ): Promise<TransactionBlock> {\n const txBlock = new TransactionBlock();\n const spoolQuickMethod = await generateSpoolQuickMethod({ builder: this.builder, txBlock });\n const sender = walletAddress || this.params.walletAddress;\n txBlock.setSender(sender);\n\n const stakeAccount = spoolQuickMethod.normalMethod.createStakeAccount(marketCoinName);\n txBlock.transferObjects([stakeAccount], sender);\n return txBlock;\n }\n\n public async supplyAndStake(\n poolCoinName: SupportPoolCoins,\n amount: number,\n stakeAccountId: string,\n walletAddress?: string,\n ): Promise<TransactionBlock> {\n const txBlock = new TransactionBlock();\n const quickMethod = await generateCoreQuickMethod({\n builder: this.builder,\n txBlock,\n });\n const spoolQuickMethod = await generateSpoolQuickMethod({ builder: this.builder, txBlock });\n const sender = walletAddress || this.params.walletAddress;\n txBlock.setSender(sender);\n\n const marketCoin = await quickMethod.depositQuick(amount, poolCoinName, walletAddress);\n const stakeMarketCoinName = this.utils.parseMarketCoinName(poolCoinName);\n if (!SUPPORT_SPOOLS.find((coin) => coin === stakeMarketCoinName)) {\n return txBlock;\n }\n const stakeAccounts = await this.query.getStakeAccounts(stakeMarketCoinName as SupportStakeMarketCoins, sender);\n const targetStakeAccount = stakeAccountId || (stakeAccounts.length > 0 ? stakeAccounts[0].id : undefined);\n if (targetStakeAccount) {\n await spoolQuickMethod.stakeQuick(marketCoin, stakeMarketCoinName as SupportStakeMarketCoins, targetStakeAccount);\n } else {\n const account = spoolQuickMethod.normalMethod.createStakeAccount(stakeMarketCoinName as SupportStakeMarketCoins);\n await spoolQuickMethod.stakeQuick(marketCoin, stakeMarketCoinName as SupportStakeMarketCoins, account);\n txBlock.transferObjects([account], sender);\n }\n return txBlock;\n }\n\n public async unstakeAndWithdraw(\n poolCoinName: SupportPoolCoins,\n amount: number,\n unstakeAccount: { id: string; coin: number }[],\n ) {\n const txBlock = new TransactionBlock();\n const quickMethod = await generateCoreQuickMethod({\n builder: this.builder,\n txBlock,\n });\n const spoolQuickMethod = await generateSpoolQuickMethod({ builder: this.builder, txBlock });\n const sender = this.params.walletAddress;\n const withdrawCoins = [];\n txBlock.setSender(sender);\n const stakeMarketCoinName = this.utils.parseMarketCoinName(poolCoinName) as SupportStakeMarketCoins;\n for (let i = 0; i < unstakeAccount.length; i++) {\n const account = unstakeAccount[i];\n const [marketCoin] = await spoolQuickMethod.unstakeQuick(account.coin, stakeMarketCoinName, account.id);\n if (marketCoin) {\n const wdScoin = quickMethod.normalMethod.withdraw(marketCoin, poolCoinName);\n withdrawCoins.push(wdScoin);\n }\n }\n if (amount > 0) {\n const wdCoin = await quickMethod.withdrawQuick(amount, poolCoinName);\n withdrawCoins.push(wdCoin);\n }\n if (withdrawCoins.length > 1) {\n txBlock.mergeCoins(withdrawCoins[0], withdrawCoins.slice(1));\n }\n txBlock.transferObjects(withdrawCoins, sender);\n return txBlock;\n }\n\n /**\n * Stake market coin into the specific spool.\n *\n * @param marketCoinName - Types of market coin.\n * @param amount - The amount of coins would deposit.\n * @param sign - Decide to directly sign the transaction or return the transaction block.\n * @param stakeAccountId - The stake account object.\n * @param walletAddress - The wallet address of the owner.\n * @return Transaction block response or transaction block.\n */\n public async stake(\n stakeMarketCoinName: SupportStakeMarketCoins,\n amount: number,\n stakeAccountId?: string,\n walletAddress?: string,\n ): Promise<TransactionBlock> {\n const txBlock = new TransactionBlock();\n const spoolQuickMethod = await generateSpoolQuickMethod({ builder: this.builder, txBlock });\n const sender = walletAddress || this.params.walletAddress;\n txBlock.setSender(sender);\n\n const stakeAccounts = await this.query.getStakeAccounts(stakeMarketCoinName, sender);\n const targetStakeAccount = stakeAccountId || (stakeAccounts.length > 0 ? stakeAccounts[0].id : undefined);\n if (targetStakeAccount) {\n await spoolQuickMethod.stakeQuick(amount, stakeMarketCoinName, targetStakeAccount);\n } else {\n const account = spoolQuickMethod.normalMethod.createStakeAccount(stakeMarketCoinName);\n await spoolQuickMethod.stakeQuick(amount, stakeMarketCoinName, account);\n txBlock.transferObjects([account], sender);\n }\n return txBlock;\n }\n\n /**\n * Unstake market coin from the specific spool.\n *\n * @param stakeMarketCoinName - Types of mak coin.\n * @param amount - The amount of coins would deposit.\n * @param sign - Decide to directly sign the transaction or return the transaction block.\n * @param accountId - The stake account object.\n * @param walletAddress - The wallet address of the owner.\n * @return Transaction block response or transaction block.\n */\n public async unstake(\n stakeMarketCoinName: SupportStakeMarketCoins,\n amount: number,\n stakeAccountId?: string,\n walletAddress?: string,\n ): Promise<TransactionBlock> {\n const txBlock = new TransactionBlock();\n const spoolQuickMethod = await generateSpoolQuickMethod({ builder: this.builder, txBlock });\n const sender = walletAddress || this.params.walletAddress;\n txBlock.setSender(sender);\n const returnScoin = SUPPORT_SCOIN.includes(stakeMarketCoinName);\n const marketCoins = await spoolQuickMethod.unstakeQuick(amount, stakeMarketCoinName, stakeAccountId, returnScoin);\n txBlock.transferObjects([marketCoins], txBlock.pure(sender));\n return txBlock;\n }\n\n /**\n * Claim reward coin from the specific spool.\n *\n * @param stakeMarketCoinName - Types of mak coin.\n * @param amount - The amount of coins would deposit.\n * @param sign - Decide to directly sign the transaction or return the transaction block.\n * @param accountId - The stake account object.\n * @param walletAddress - The wallet address of the owner.\n * @return Transaction block response or transaction block.\n */\n public async claim(\n lendingIncentive: SpoolIncentiveParams[],\n borrowIncentiveV2: BorrowIncentiveParams[],\n borrowIncentive: BorrowIncentiveParams[],\n walletAddress?: string,\n ): Promise<TransactionBlock> {\n const txBlock = new TransactionBlock();\n const spoolQuickMethod = await generateSpoolQuickMethod({ builder: this.builder, txBlock });\n const borrowIncentiveRewarad = await generateBorrowIncentiveQuickMethod({ builder: this.builder, txBlock });\n const sender = walletAddress || this.params.walletAddress;\n txBlock.setSender(sender);\n\n const rewardCoins: { sui: TransactionResult[]; sca: TransactionResult[] } = {\n sui: [],\n sca: [],\n };\n\n for (let i = 0; i < lendingIncentive.length; i++) {\n const { stakeMarketCoinName, stakeAccountId } = lendingIncentive[i];\n const rewardCoin = spoolQuickMethod.normalMethod.claim(stakeAccountId, stakeMarketCoinName);\n rewardCoins.sui.push(rewardCoin);\n }\n\n for (let i = 0; i < borrowIncentiveV2.length; i++) {\n const { obligationId, obligationKey, rewardCoinName } = borrowIncentiveV2[i];\n const rewardCoin = borrowIncentiveRewarad.normalMethod.claimBorrowIncentive(\n obligationId,\n obligationKey,\n rewardCoinName,\n );\n rewardCoins[rewardCoinName].push(rewardCoin);\n }\n\n for (let i = 0; i < borrowIncentive.length; i++) {\n const { obligationId, obligationKey, rewardCoinName } = borrowIncentive[i];\n const rewardCoin = borrowIncentiveRewarad.normalMethod.oldClaimBorrowIncentive(\n obligationId,\n obligationKey,\n rewardCoinName,\n );\n rewardCoins[rewardCoinName].push(rewardCoin);\n }\n\n if (rewardCoins.sui.length > 0) {\n if (rewardCoins.sui.length > 1) {\n txBlock.mergeCoins(rewardCoins.sui[0], rewardCoins.sui.slice(1));\n }\n txBlock.transferObjects([rewardCoins.sui[0]], txBlock.pure(sender));\n }\n\n if (rewardCoins.sca.length > 0) {\n if (rewardCoins.sca.length > 1) {\n txBlock.mergeCoins(rewardCoins.sca[0], rewardCoins.sca.slice(1));\n }\n txBlock.transferObjects([rewardCoins.sca[0]], txBlock.pure(sender));\n }\n return txBlock;\n }\n\n /* ==================== Borrow Incentive Method ==================== */\n\n /**\n * stake obligaion.\n *\n * @param obligationId - The obligation account object.\n * @param obligationKeyId - The obligation key account object.\n * @param sign - Decide to directly sign the transaction or return the transaction block.\n * @param walletAddress - The wallet address of the owner.\n * @return Transaction block response or transaction block\n */\n public async stakeObligation(\n obligationId: string,\n obligationKeyId: string,\n walletAddress?: string,\n ): Promise<TransactionBlock> {\n const txBlock = this.builder.createTxBlock();\n const borrowIncentiveQuickMethod = await generateBorrowIncentiveQuickMethod({ builder: this.builder, txBlock });\n const sender = walletAddress || this.params.walletAddress;\n txBlock.setSender(sender);\n\n await borrowIncentiveQuickMethod.stakeObligationQuick(obligationId, obligationKeyId);\n return txBlock;\n }\n\n /**\n * unstake obligaion.\n *\n * @param obligationId - The obligation account object.\n * @param obligationKeyId - The obligation key account object.\n * @param sign - Decide to directly sign the transaction or return the transaction block.\n * @param walletAddress - The wallet address of the owner.\n * @return Transaction block response or transaction block\n */\n public async unstakeObligation(\n obligationId: string,\n obligationKeyId: string,\n walletAddress?: string,\n ): Promise<TransactionBlock> {\n const txBlock = this.builder.createTxBlock();\n const borrowIncentiveQuickMethod = await generateBorrowIncentiveQuickMethod({ builder: this.builder, txBlock });\n const sender = walletAddress || this.params.walletAddress;\n txBlock.setSender(sender);\n\n await borrowIncentiveQuickMethod.unstakeObligationQuick(obligationId, obligationKeyId);\n return txBlock;\n }\n\n /**\n * Stake SCA.\n *\n * @param amount - Types of mak coin.\n * @param lockPeriod - The amount of coins would deposit.\n * @param walletAddress - The wallet address of the owner.\n * @return Transaction block response or transaction block.\n */\n public async stakeSca(\n amount: number,\n isObligationLocked = false,\n isOldBorrowIncentive = false,\n obligationId?: string,\n obligationKey?: string,\n lockPeriod?: number,\n vescaKey?: string,\n walletAddress?: string,\n ): Promise<TransactionBlock> {\n const txBlock = new TransactionBlock();\n const vescaQuickMethod = await generateQuickVeScaMethod({ builder: this.builder, txBlock });\n const borrowIncentive = await generateBorrowIncentiveQuickMethod({ builder: this.builder, txBlock });\n const sender = walletAddress || this.params.walletAddress;\n txBlock.setSender(sender);\n\n // Get all SCA and merge them into one.\n const coins = await this.builder.utils.selectCoinIds(amount, SCA_COIN_TYPE, sender);\n const [takeCoin, leftCoin] = this.builder.utils.takeAmountFromCoins(txBlock, coins, amount);\n\n let newVescaKey;\n if (!vescaKey) {\n newVescaKey = vescaQuickMethod.normalMethod.lockSca(takeCoin, lockPeriod);\n } else {\n vescaQuickMethod.normalMethod.extendLockAmount(vescaKey, takeCoin);\n }\n\n if (obligationId && obligationKey) {\n if (isObligationLocked) {\n if (isOldBorrowIncentive) {\n borrowIncentive.normalMethod.oldUnstakeObligation(obligationId, obligationKey);\n } else {\n borrowIncentive.normalMethod.unstakeObligation(obligationId, obligationKey);\n }\n }\n borrowIncentive.normalMethod.stakeObligationWithVesca(obligationId, obligationKey, vescaKey || newVescaKey);\n }\n\n if (!vescaKey) {\n txBlock.transferObjects([newVescaKey, leftCoin], sender);\n }\n\n return txBlock;\n }\n\n /**\n * Stake more SCA.\n *\n * @param amount - Types of mak coin.\n * @param vescaKey - The vesca key object.\n * @param walletAddress - The wallet address of the owner.\n * @return Transaction block response or transaction block.\n */\n public async stakeMoreSca(amount: number, vescaKey?: string, walletAddress?: string): Promise<TransactionBlock> {\n const txBlock = new TransactionBlock();\n // const vescaQuickMethod = await generateQuickVeScaMethod({ builder: this.builder, txBlock });\n const sender = walletAddress || this.params.walletAddress;\n txBlock.setSender(sender);\n\n // await vescaQuickMethod.extendLockAmountQuick(amount, vescaKey);\n return txBlock;\n }\n\n /**\n * Extend stake lock period.\n *\n * @param lockPeriodInDays\n * @param vescaKey\n * @param walletAddress\n * @returns Transaction block response or transaction block.\n */\n public async extendStakeScaLockPeriod(\n lockPeriodInDays: number,\n vescaKey: string,\n obligationId?: string,\n obligationKey?: string,\n isObligationLocked = false,\n isOldBorrowIncentive = false,\n walletAddress?: string,\n ): Promise<TransactionBlock> {\n const txBlock = new TransactionBlock();\n const vescaQuickMethod = await generateQuickVeScaMethod({ builder: this.builder, txBlock });\n const borrowIncentive = await generateBorrowIncentiveQuickMethod({ builder: this.builder, txBlock });\n const sender = walletAddress || this.params.walletAddress;\n txBlock.setSender(sender);\n\n vescaQuickMethod.normalMethod.extendLockPeriod(vescaKey, lockPeriodInDays);\n if (obligationId && obligationKey) {\n if (isObligationLocked) {\n if (isOldBorrowIncentive) {\n borrowIncentive.normalMethod.oldUnstakeObligation(obligationId, obligationKey);\n } else {\n borrowIncentive.normalMethod.unstakeObligation(obligationId, obligationKey);\n }\n }\n borrowIncentive.normalMethod.stakeObligationWithVesca(obligationId, obligationKey, vescaKey);\n }\n return txBlock;\n }\n\n public async extendPeriodAndStakeMoreSca(\n amount: number,\n vescaKey: string,\n lockPeriodInDays: number,\n obligation?: string,\n obligationKey?: string,\n isObligationLocked = false,\n isOldBorrowIncentive = false,\n walletAddress?: string,\n ): Promise<TransactionBlock> {\n const txBlock = new TransactionBlock();\n const vescaQuickMethod = await generateQuickVeScaMethod({ builder: this.builder, txBlock });\n const borrowIncentive = await generateBorrowIncentiveQuickMethod({ builder: this.builder, txBlock });\n const sender = walletAddress || this.params.walletAddress;\n txBlock.setSender(sender);\n\n // Get all SCA and merge them into one.\n const coins = await this.builder.utils.selectCoinIds(amount, SCA_COIN_TYPE, sender);\n const [takeCoin, leftCoin] = this.builder.utils.takeAmountFromCoins(txBlock, coins, amount);\n vescaQuickMethod.normalMethod.extendLockPeriod(vescaKey, lockPeriodInDays);\n vescaQuickMethod.normalMethod.extendLockAmount(vescaKey, takeCoin);\n txBlock.transferObjects([leftCoin], sender);\n if (!obligation || !obligationKey) {\n return txBlock;\n }\n if (isObligationLocked) {\n if (isOldBorrowIncentive) {\n borrowIncentive.normalMethod.oldUnstakeObligation(obligation, obligationKey);\n } else {\n borrowIncentive.normalMethod.unstakeObligation(obligation, obligationKey);\n }\n }\n borrowIncentive.normalMethod.stakeObligationWithVesca(obligation, obligationKey, vescaKey);\n return txBlock;\n }\n\n /**\n * Renew expired stake SCA.\n *\n * @param amount\n * @param lockPeriodInDays\n * @param vescaKey\n * @param walletAddress\n * @returns Transaction block response or transaction block.\n */\n public async renewExpiredStakeSca(\n amount: number,\n lockPeriodInDays: number,\n vescaKey: string,\n isHaveRedeem = false,\n obligation?: string,\n obligationKey?: string,\n isObligationLocked = false,\n isOldBorrowIncentive = false,\n walletAddress?: string,\n ): Promise<TransactionBlock> {\n const txBlock = new TransactionBlock();\n const vescaQuickMethod = await generateQuickVeScaMethod({ builder: this.builder, txBlock });\n const borrowIncentive = await generateBorrowIncentiveQuickMethod({ builder: this.builder, txBlock });\n const sender = walletAddress || this.params.walletAddress;\n txBlock.setSender(sender);\n\n if (isHaveRedeem) {\n const redeem = vescaQuickMethod.normalMethod.redeemSca(vescaKey);\n txBlock.transferObjects([redeem], sender);\n }\n\n // Get all SCA and merge them into one.\n const coins = await this.builder.utils.selectCoinIds(amount, SCA_COIN_TYPE, sender);\n const [takeCoin, leftCoin] = this.builder.utils.takeAmountFromCoins(txBlock, coins, amount);\n txBlock.transferObjects([leftCoin], sender);\n // renew veSCA\n vescaQuickMethod.normalMethod.renewExpiredVeSca(vescaKey, takeCoin, lockPeriodInDays);\n if (!obligation || !obligationKey) {\n return txBlock;\n }\n if (isObligationLocked) {\n if (isOldBorrowIncentive) {\n borrowIncentive.normalMethod.oldUnstakeObligation(obligation, obligationKey);\n } else {\n borrowIncentive.normalMethod.unstakeObligation(obligation, obligationKey);\n }\n }\n borrowIncentive.normalMethod.stakeObligationWithVesca(obligation, obligationKey, vescaKey);\n return txBlock;\n }\n\n public async redeemSca(veScaKey: string): Promise<TransactionBlock> {\n const txBlock = new TransactionBlock();\n const vescaQuickMethod = await generateQuickVeScaMethod({ builder: this.builder, txBlock });\n const sender = this.params.walletAddress;\n txBlock.setSender(sender);\n\n await vescaQuickMethod.redeemScaQuick(veScaKey);\n return txBlock;\n }\n\n public async migrateAndClaim(\n obligationKey: string,\n obligationId: string,\n rewardCoinName: SupportBorrowIncentiveRewardCoins,\n veScaKey?: string,\n ) {\n const txBlock = new TransactionBlock();\n const borrowIncentive = await generateBorrowIncentiveQuickMethod({ builder: this.builder, txBlock });\n const sender = this.params.walletAddress;\n txBlock.setSender(sender);\n\n const rewardCoin = borrowIncentive.normalMethod.oldClaimBorrowIncentive(\n obligationId,\n obligationKey,\n rewardCoinName,\n );\n txBlock.transferObjects([rewardCoin], sender);\n await borrowIncentive.unstakeObligationQuick(obligationId, obligationKey);\n if (veScaKey) {\n await borrowIncentive.stakeObligationWithVeScaQuick(obligationId, obligationKey, veScaKey);\n } else {\n await borrowIncentive.stakeObligationQuick(obligationId, obligationKey);\n }\n return txBlock;\n }\n\n /**\n * Withdraw unlocked SCA.\n *\n * @param vescaKey\n * @param walletAddress\n * @returns Transaction block response or transaction block.\n */\n public async withdrawUnlockedSca(vescaKey?: string, walletAddress?: string): Promise<TransactionBlock> {\n const txBlock = new TransactionBlock();\n const vescaQuickMethod = await generateQuickVeScaMethod({ builder: this.builder, txBlock });\n const sender = walletAddress || this.params.walletAddress;\n txBlock.setSender(sender);\n\n await vescaQuickMethod.redeemScaQuick(vescaKey);\n return txBlock;\n }\n\n private calculateAvailableClaimCoin(accountPoint: any, poolPoint: any): BigNumber {\n const borrowAmount = new BigNumber(accountPoint.weightedAmount);\n const baseIndexRate = 1e9;\n const increasePointRate = poolPoint.currentPointIndex\n ? BigNumber(poolPoint.currentPointIndex - accountPoint.index).dividedBy(baseIndexRate)\n : 1;\n return borrowAmount\n .multipliedBy(increasePointRate)\n .plus(accountPoint.points)\n .shiftedBy(-1 * poolPoint.coinDecimal);\n }\n\n /**\n * Create Referral Link\n *\n * @returns Transaction block response or transaction block.\n */\n public async createReferralLink(): Promise<TransactionBlock> {\n const txBlock = new TransactionBlock();\n const vescaMethod = await generateQuickVeScaMethod({ builder: this.builder, txBlock });\n const sender = this.params.walletAddress;\n txBlock.setSender(sender);\n\n const referralTicket = vescaMethod.normalMethod.mintEmptyVeSca();\n txBlock.transferObjects([referralTicket], sender);\n return txBlock;\n }\n\n /**\n * Claim Referral Revenue\n * @param veScaKey - The vesca key object.\n * @param coins - The coins would claim.\n *\n * @returns Transaction block response or transaction block.\n */\n public async claimRevenuReferral(veScaKey: string, coins: string[]): Promise<TransactionBlock> {\n const txBlock = new TransactionBlock();\n const referral = await generateReferralQuickMethod({ builder: this.builder, txBlock });\n const sender = this.params.walletAddress;\n txBlock.setSender(sender);\n const coinsName = coins.map((coin) => this.utils.parseCoinNameFromType(coin) as SupportPoolCoins);\n\n await referral.claimReferralRevenueQuick(veScaKey, sender, coinsName);\n return txBlock;\n }\n\n /**\n * Bind Referral\n * @param veScaKey - The vesca key object.\n *\n *\n * @returns Transaction block response or transaction block.\n */\n public async bindReferral(veScaKey: string): Promise<TransactionBlock> {\n const txBlock = new TransactionBlock();\n const referral = await generateReferralNormalMethod({ builder: this.builder, txBlock });\n const sender = this.params.walletAddress;\n txBlock.setSender(sender);\n referral.bindToReferral(veScaKey);\n return txBlock;\n }\n\n /* ==================== Migrate market coin to sCoin method ==================== */\n /**\n * Function to migrate all market coin in user wallet into sCoin\n * @returns Transaction response\n */\n public async migrateAllMarketCoin(): Promise<TransactionBlock> {\n const txBlock = new TransactionBlock();\n const scoinNormalMethod = await generateSCoinNormalMethod({ builder: this.builder, txBlock });\n const spoolQuickMethod = await generateSpoolQuickMethod({ builder: this.builder, txBlock });\n txBlock.setSender(this.params.walletAddress);\n\n const toTransfer: SuiObjectArg[] = [];\n await Promise.all(\n SUPPORT_SCOIN.map(async (sCoinName) => {\n /**\n * First check marketCoin inside mini wallet\n * Then check stakedMarketCoin inside spool\n */\n const sCoins: SuiObjectArg[] = [];\n let toDestroyMarketCoin: SuiObjectArg | undefined;\n\n // check market coin in mini wallet\n try {\n const marketCoins = await this.utils.selectCoinIds(\n Number.MAX_SAFE_INTEGER,\n this.utils.parseMarketCoinType(sCoinName as SupportSCoin),\n this.params.walletAddress,\n ); // throw error no coins found\n\n const mergedMarketCoin = marketCoins[0];\n if (marketCoins.length > 1) {\n txBlock.mergeCoins(mergedMarketCoin, marketCoins.slice(1));\n }\n\n toDestroyMarketCoin = mergedMarketCoin;\n } catch (e: any) {\n // Ignore\n const errMsg = e.toString() as string;\n if (!errMsg.includes('No valid coins found for the transaction')) {\n throw e;\n }\n }\n\n // if market coin found, mint sCoin\n if (toDestroyMarketCoin) {\n // mint new sCoin\n const sCoin = scoinNormalMethod.mintSCoin(sCoinName as SupportSCoin, toDestroyMarketCoin);\n\n // check if current sCoin exist\n try {\n const existSCoins = await this.utils.selectCoinIds(\n Number.MAX_SAFE_INTEGER,\n this.utils.parseSCoinType(sCoinName as SupportSCoin),\n this.params.walletAddress,\n ); // throw error on no coins found\n txBlock.mergeCoins(sCoin, existSCoins);\n } catch (e: any) {\n console.log(e);\n }\n sCoins.push(sCoin);\n }\n\n // check for staked market coin in spool\n if (SUPPORT_SPOOLS.includes(sCoinName as SupportStakeMarketCoins)) {\n try {\n const sCoin = await spoolQuickMethod.unstakeQuick(\n Number.MAX_SAFE_INTEGER,\n sCoinName as SupportStakeMarketCoins,\n );\n if (sCoin) {\n sCoins.push(sCoin);\n }\n } catch (e: any) {\n console.log(e);\n }\n }\n\n if (sCoins.length > 0) {\n const mergedSCoin = sCoins[0];\n if (sCoins.length > 1) {\n txBlock.mergeCoins(\n mergedSCoin as TransactionObjectArgument,\n sCoins.slice(1) as TransactionObjectArgument[],\n );\n }\n\n toTransfer.push(mergedSCoin);\n }\n }),\n );\n\n if (toTransfer.length > 0) {\n txBlock.transferObjects(toTransfer as TransactionObjectArgument[], this.params.walletAddress);\n }\n\n return txBlock;\n }\n\n public async migrateLendingWusdcToUsdcNative(\n poolCoinName: SupportPoolCoins,\n amount: number,\n slippage: number,\n validSwapAmount: string,\n unstakeAccount: { id: string; coin: number }[],\n ): Promise<TransactionBlock> {\n const txBlock = new TransactionBlock();\n const quickMethod = await generateCoreQuickMethod({\n builder: this.builder,\n txBlock,\n });\n const spoolQuickMethod = await generateSpoolQuickMethod({ builder: this.builder, txBlock });\n const sender = this.params.walletAddress;\n const withdrawCoins = [];\n\n const stakeMarketCoinName = this.utils.parseMarketCoinName(poolCoinName) as SupportStakeMarketCoins;\n const marketCoinType = this.utils.parseMarketCoinType(stakeMarketCoinName);\n const coins = await this.utils.selectCoinsMarketCoin(marketCoinType, sender);\n const coinIds = coins.map((value) => value.objectId);\n\n txBlock.setSender(sender);\n for (let i = 0; i < unstakeAccount.length; i++) {\n const account = unstakeAccount[i];\n const [marketCoin] = await spoolQuickMethod.unstakeQuick(account.coin, stakeMarketCoinName, account.id);\n if (marketCoin) {\n // If user has market coin object merge it\n if (coinIds.length > 0) {\n txBlock.mergeCoins(marketCoin, coinIds);\n }\n const wdCoin = quickMethod.normalMethod.withdraw(marketCoin, poolCoinName);\n withdrawCoins.push(wdCoin);\n }\n }\n\n // burn scoin then withdraw wusdc\n if (amount > 0) {\n const wdCoin = await quickMethod.withdrawQuick(amount, poolCoinName);\n withdrawCoins.push(wdCoin);\n }\n\n // Merge withdraw coins to one object\n if (withdrawCoins.length > 1) {\n txBlock.mergeCoins(withdrawCoins[0], withdrawCoins.slice(1));\n }\n const [coinSwap] = txBlock.splitCoins(withdrawCoins[0], [txBlock.pure(validSwapAmount)]);\n txBlock.transferObjects([withdrawCoins[0]], sender);\n\n const { swapResult: coinB, accountCap } = await this.deepbookSwap.swapToken({\n baseCoinName: 'wusdc',\n quoteCoinName: 'usdc',\n tokenObjectIn: coinSwap,\n tx: txBlock,\n });\n if (typeof accountCap === 'string') {\n txBlock.transferObjects([accountCap], sender);\n }\n\n SlippageTxBuilder.check_slippage(txBlock, coinB, slippage, validSwapAmount, this.query.utils.parseCoinType('usdc'));\n\n const mintedMarketCoin = quickMethod.normalMethod.deposit(coinB, 'usdc');\n await spoolQuickMethod.stakeQuick(mintedMarketCoin, 'susdc');\n return txBlock;\n }\n}\n","import type { SuiClient } from '@mysten/sui.js/client';\nimport { TransactionBlock } from '@mysten/sui.js/transactions';\n\nimport { ScallopAddress } from './scallopAddress';\nimport { ScallopQuery } from './scallopQuery';\nimport { ScallopUtils } from './scallopUtils';\nimport type {\n ScallopInstanceParams,\n ScallopBuilderParams,\n ScallopTxBlock,\n SupportMarketCoins,\n SupportAssetCoins,\n SupportSCoin,\n} from '../types';\n\n/**\n * @description\n * It provides methods for operating the transaction block, making it more convenient to organize transaction combinations.\n *\n * @example\n * ```typescript\n * const scallopBuilder = new ScallopBuilder(<parameters>);\n * await scallopBuilder.init();\n * const txBlock = scallopBuilder.<builder functions>();\n * ```\n */\nexport class ScallopBuilder {\n public readonly params: ScallopBuilderParams;\n\n public readonly isTestnet: boolean;\n\n public address: ScallopAddress;\n\n public query: ScallopQuery;\n\n public utils: ScallopUtils;\n\n public client: SuiClient;\n\n public constructor(params: ScallopBuilderParams, instance: Omit<ScallopInstanceParams, 'builder'>) {\n this.params = params;\n this.client = params.client;\n\n const { address, query, utils } = instance;\n this.address = address;\n this.query = query;\n this.utils = utils;\n this.isTestnet = params.networkType ? params.networkType === 'testnet' : false;\n }\n\n /**\n * Create a scallop txBlock instance that enhances transaction block.\n *\n * @param txBlock - Scallop txBlock, txBlock created by SuiKit, or original transaction block.\n * @return Scallop txBlock.\n */\n public createTxBlock(txBlock?: ScallopTxBlock | TransactionBlock) {\n return new TransactionBlock(txBlock);\n }\n\n /**\n * Specifying the sender's amount of coins to get coins args from transaction result.\n *\n * @param txBlock - Scallop txBlock or txBlock created by SuiKit .\n * @param assetCoinName - Specific support asset coin name.\n * @param amount - Amount of coins to be selected.\n * @param sender - Sender address.\n * @return Take coin and left coin.\n */\n public async selectCoin(\n txBlock: ScallopTxBlock,\n assetCoinName: SupportAssetCoins,\n amount: number,\n sender: string = this.params.walletAddress,\n ) {\n const coinType = this.utils.parseCoinType(assetCoinName);\n const coins = await this.utils.selectCoinIds(amount, coinType, sender);\n const [takeCoin, leftCoin] = this.utils.takeAmountFromCoins(txBlock, coins, amount);\n return { takeCoin, leftCoin };\n }\n\n /**\n * Specifying the sender's amount of market coins to get coins args from transaction result.\n *\n * @param txBlock - Scallop txBlock or txBlock created by SuiKit .\n * @param marketCoinName - Specific support market coin name.\n * @param amount - Amount of coins to be selected.\n * @param sender - Sender address.\n * @return Take coin and left coin.\n */\n public async selectMarketCoin(\n txBlock: TransactionBlock,\n marketCoinName: SupportMarketCoins,\n amount: number,\n sender: string = this.params.walletAddress,\n ) {\n const marketCoinType = this.utils.parseMarketCoinType(marketCoinName);\n const coins = await this.utils.selectCoins(amount, marketCoinType, sender);\n const totalAmount = coins.reduce((prev, coin) => {\n // eslint-disable-next-line no-param-reassign\n prev += Number(coin.balance);\n return prev;\n }, 0);\n const coinIds = coins.map((value) => value.objectId);\n const [takeCoin, leftCoin] = this.utils.takeAmountFromCoins(txBlock, coinIds, Math.min(amount, totalAmount));\n return { takeCoin, leftCoin, totalAmount };\n }\n\n /**\n * Specifying the sender's amount of sCoins to get coins args from transaction result.\n *\n * @param txBlock - Scallop txBlock or txBlock created by SuiKit .\n * @param marketCoinName - Specific support sCoin name.\n * @param amount - Amount of coins to be selected.\n * @param sender - Sender address.\n * @return Take coin and left coin.\n */\n public async selectSCoin(\n txBlock: TransactionBlock,\n sCoinName: SupportSCoin,\n amount: number,\n sender: string = this.params.walletAddress,\n ) {\n const sCoinType = this.utils.parseSCoinType(sCoinName);\n const coins = await this.utils.selectCoins(amount, sCoinType, sender);\n const coinIds = coins.map((coin) => coin.objectId);\n const totalAmount = coins.reduce((prev, coin) => prev + Number(coin.balance), 0);\n const [takeCoin, leftCoin] = this.utils.takeAmountFromCoins(txBlock, coinIds, Math.min(totalAmount, amount));\n return {\n takeCoin,\n leftCoin,\n totalAmount,\n };\n }\n}\n","import type { SuiObjectResponse, SuiObjectData } from '@mysten/sui.js/client';\nimport { TransactionBlock } from '@mysten/sui.js/transactions';\nimport BigNumber from 'bignumber.js';\n\nimport { SUPPORT_POOLS, PROTOCOL_OBJECT_ID } from '../constants';\nimport type { ScallopQuery } from '../models';\nimport {\n SupportAssetCoins,\n SupportPoolCoins,\n Obligation,\n CoinAmounts,\n MarketCoinAmounts,\n SupportMarketCoins,\n SuiAddressArg,\n ObligationQueryInterface,\n} from '../types';\n\n/**\n * Query all owned obligations.\n *\n * @param query - The Scallop query instance.\n * @param ownerAddress - The owner address.\n * @return Owned obligations.\n */\nexport const getObligations = async (query: ScallopQuery, ownerAddress: string) => {\n const owner = ownerAddress;\n const protocolObjectId = query.address.get('core.object') || PROTOCOL_OBJECT_ID;\n const keyObjectsResponse: SuiObjectResponse[] = [];\n let hasNextPage = false;\n let nextCursor: string | null = null;\n do {\n const paginatedKeyObjectsResponse = await query.client.getOwnedObjects({\n owner,\n filter: {\n StructType: `${protocolObjectId}::obligation::ObligationKey`,\n },\n cursor: nextCursor,\n });\n keyObjectsResponse.push(...paginatedKeyObjectsResponse.data);\n if (paginatedKeyObjectsResponse.hasNextPage && paginatedKeyObjectsResponse.nextCursor) {\n hasNextPage = true;\n nextCursor = paginatedKeyObjectsResponse.nextCursor;\n } else {\n hasNextPage = false;\n }\n } while (hasNextPage);\n\n const keyObjectIds: string[] = keyObjectsResponse\n .map((ref: any) => ref?.data?.objectId)\n .filter((id: any) => id !== undefined);\n const keyObjects = await query.client.multiGetObjects({\n ids: keyObjectIds,\n options: { showContent: true, showType: true },\n });\n const obligations: Obligation[] = [];\n for (let i = 0; i < keyObjects.length; i++) {\n const keyId = keyObjects[i].data.objectId;\n const { content } = keyObjects[i].data;\n if (content && 'fields' in content) {\n const fields = content.fields as any;\n const obligationId = String(fields.ownership.fields.of);\n const locked = await getObligationLocked(query, obligationId);\n obligations.push({ id: obligationId, keyId, locked });\n }\n }\n return obligations;\n};\n\n/**\n * Query obligation locked status.\n *\n * @param query - The Scallop query instance.\n * @param obligationId - The obligation id.\n * @return Obligation locked status.\n */\nexport const getObligationLocked = async (query: ScallopQuery, obligationId: string) => {\n const obligationObjectResponse = await query.client.getObject({\n id: obligationId,\n options: {\n showContent: true,\n },\n });\n let obligationLocked = false;\n if (\n obligationObjectResponse.data &&\n obligationObjectResponse?.data?.content?.dataType === 'moveObject' &&\n 'lock_key' in obligationObjectResponse.data.content.fields\n ) {\n obligationLocked = Boolean(obligationObjectResponse.data.content.fields.lock_key);\n }\n\n return obligationLocked;\n};\n\n/**\n * Query all owned coin amount.\n *\n * @param query - The Scallop query instance.\n * @param assetCoinNames - Specific an array of support asset coin name.\n * @param ownerAddress - The owner address.\n * @return All owned coin amounts.\n */\nexport const getCoinAmounts = async (\n query: ScallopQuery,\n ownerAddress: string,\n assetCoinNames?: SupportAssetCoins[],\n) => {\n const updatedAssetCoinNames = assetCoinNames || [...SUPPORT_POOLS];\n const owner = ownerAddress;\n const coinObjectsResponse: SuiObjectResponse[] = [];\n let hasNextPage = false;\n let nextCursor: string | null = null;\n do {\n const paginatedCoinObjectsResponse = await query.client.getOwnedObjects({\n owner,\n filter: {\n MatchAny: updatedAssetCoinNames.map((assetCoinName) => {\n const coinType = query.utils.parseCoinType(assetCoinName);\n return { StructType: `0x2::coin::Coin<${coinType}>` };\n }),\n },\n options: {\n showType: true,\n showContent: true,\n },\n cursor: nextCursor,\n });\n\n coinObjectsResponse.push(...paginatedCoinObjectsResponse.data);\n if (paginatedCoinObjectsResponse.hasNextPage && paginatedCoinObjectsResponse.nextCursor) {\n hasNextPage = true;\n nextCursor = paginatedCoinObjectsResponse.nextCursor;\n } else {\n hasNextPage = false;\n }\n } while (hasNextPage);\n\n const coinAmounts: CoinAmounts = {};\n const coinObjects = coinObjectsResponse\n .map((response) => response.data)\n .filter((object: any) => object !== undefined && object !== null) as SuiObjectData[];\n coinObjects.forEach((coinObject) => {\n const type = coinObject.type as string;\n if (coinObject.content && 'fields' in coinObject.content) {\n const fields = coinObject.content.fields as any;\n const poolCoinName = query.utils.parseCoinNameFromType<SupportPoolCoins>(type);\n if (poolCoinName) {\n coinAmounts[poolCoinName as SupportPoolCoins] = BigNumber(coinAmounts[poolCoinName as SupportPoolCoins] ?? 0)\n .plus(fields.balance)\n .toNumber();\n }\n }\n });\n return coinAmounts;\n};\n\n/**\n * Query owned coin amount.\n *\n * @param query - The Scallop query instance.\n * @param assetCoinName - Specific support asset coin name.\n * @param ownerAddress - The owner address.\n * @return Owned coin amount.\n */\nexport const getCoinAmount = async (query: ScallopQuery, assetCoinName: SupportAssetCoins, ownerAddress: string) => {\n const owner = ownerAddress;\n const coinType = query.utils.parseCoinType(assetCoinName);\n const coinObjectsResponse: SuiObjectResponse[] = [];\n let hasNextPage = false;\n let nextCursor: string | null = null;\n do {\n const paginatedCoinObjectsResponse = await query.client.getOwnedObjects({\n owner,\n filter: { StructType: `0x2::coin::Coin<${coinType}>` },\n options: {\n showContent: true,\n },\n cursor: nextCursor,\n });\n\n coinObjectsResponse.push(...paginatedCoinObjectsResponse.data);\n if (paginatedCoinObjectsResponse.hasNextPage && paginatedCoinObjectsResponse.nextCursor) {\n hasNextPage = true;\n nextCursor = paginatedCoinObjectsResponse.nextCursor;\n } else {\n hasNextPage = false;\n }\n } while (hasNextPage);\n\n let coinAmount = 0;\n const coinObjects = coinObjectsResponse\n .map((response) => response.data)\n .filter((object: any) => object !== undefined && object !== null) as SuiObjectData[];\n coinObjects.forEach((coinObject) => {\n if (coinObject.content && 'fields' in coinObject.content) {\n const fields = coinObject.content.fields as any;\n coinAmount = BigNumber(coinAmount).plus(fields.balance).toNumber();\n }\n });\n return coinAmount;\n};\n\n/**\n * Query all owned market coins (sCoin) amount.\n *\n * @param query - The Scallop query instance.\n * @param marketCoinNames - Specific an array of support market coin name.\n * @param ownerAddress - The owner address.\n * @return All owned market coins amount.\n */\nexport const getMarketCoinAmounts = async (\n query: ScallopQuery,\n ownerAddress: string,\n marketCoinNames?: SupportMarketCoins[],\n) => {\n const updatedMarketCoinNames =\n marketCoinNames || [...SUPPORT_POOLS].map((poolCoinName) => query.utils.parseMarketCoinName(poolCoinName));\n const owner = ownerAddress;\n const marketCoinObjectsResponse: SuiObjectResponse[] = [];\n let hasNextPage = false;\n let nextCursor: string | null = null;\n do {\n const paginatedMarketCoinObjectsResponse = await query.client.getOwnedObjects({\n owner,\n filter: {\n MatchAny: updatedMarketCoinNames.map((marketCoinName) => {\n const marketCoinType = query.utils.parseMarketCoinType(marketCoinName);\n return { StructType: `0x2::coin::Coin<${marketCoinType}>` };\n }),\n },\n options: {\n showType: true,\n showContent: true,\n },\n cursor: nextCursor,\n });\n\n marketCoinObjectsResponse.push(...paginatedMarketCoinObjectsResponse.data);\n if (paginatedMarketCoinObjectsResponse.hasNextPage && paginatedMarketCoinObjectsResponse.nextCursor) {\n hasNextPage = true;\n nextCursor = paginatedMarketCoinObjectsResponse.nextCursor;\n } else {\n hasNextPage = false;\n }\n } while (hasNextPage);\n\n const marketCoinAmounts: MarketCoinAmounts = {};\n const marketCoinObjects = marketCoinObjectsResponse\n .map((response) => response.data)\n .filter((object: any) => object !== undefined && object !== null) as SuiObjectData[];\n marketCoinObjects.forEach((marketCoinObject) => {\n const type = marketCoinObject.type as string;\n if (marketCoinObject.content && 'fields' in marketCoinObject.content) {\n const fields = marketCoinObject.content.fields as any;\n const marketCoinName = query.utils.parseCoinNameFromType<SupportMarketCoins>(type);\n if (marketCoinName) {\n marketCoinAmounts[marketCoinName as SupportMarketCoins] = BigNumber(\n marketCoinAmounts[marketCoinName as SupportMarketCoins] ?? 0,\n )\n .plus(fields.balance)\n .toNumber();\n }\n }\n });\n return marketCoinAmounts;\n};\n\n/**\n * Query owned market coin (sCoin) amount.\n *\n * @param query - The Scallop query instance.\n * @param marketCoinNames - Specific support market coin name.\n * @param ownerAddress - The owner address.\n * @return Owned market coin amount.\n */\nexport const getMarketCoinAmount = async (\n query: ScallopQuery,\n marketCoinName: SupportMarketCoins,\n ownerAddress: string,\n) => {\n const owner = ownerAddress;\n const marketCoinType = query.utils.parseMarketCoinType(marketCoinName);\n const marketCoinObjectsResponse: SuiObjectResponse[] = [];\n let hasNextPage = false;\n let nextCursor: string | null = null;\n do {\n const paginatedMarketCoinObjectsResponse = await query.client.getOwnedObjects({\n owner,\n filter: { StructType: `0x2::coin::Coin<${marketCoinType}>` },\n options: {\n showContent: true,\n },\n cursor: nextCursor,\n });\n\n marketCoinObjectsResponse.push(...paginatedMarketCoinObjectsResponse.data);\n if (paginatedMarketCoinObjectsResponse.hasNextPage && paginatedMarketCoinObjectsResponse.nextCursor) {\n hasNextPage = true;\n nextCursor = paginatedMarketCoinObjectsResponse.nextCursor;\n } else {\n hasNextPage = false;\n }\n } while (hasNextPage);\n\n let marketCoinAmount = 0;\n const marketCoinObjects = marketCoinObjectsResponse\n .map((response) => response.data)\n .filter((object: any) => object !== undefined && object !== null) as SuiObjectData[];\n marketCoinObjects.forEach((marketCoinObject) => {\n if (marketCoinObject.content && 'fields' in marketCoinObject.content) {\n const fields = marketCoinObject.content.fields as any;\n marketCoinAmount = BigNumber(marketCoinAmount).plus(fields.balance).toNumber();\n }\n });\n return marketCoinAmount;\n};\n\n/**\n * Query obligation data.\n *\n * @description\n * Use inspectTxn call to obtain the data provided in the scallop contract query module.\n *\n * @param query - The Scallop query instance.\n * @param obligationId - The obligation id.\n * @return Obligation data.\n */\nexport const queryObligation = async (query: ScallopQuery, obligationId: SuiAddressArg) => {\n const packageId = query.address.get('core.packages.query.id');\n const queryTarget = `${packageId}::obligation_query::obligation_data` as `${string}::${string}::${string}`;\n const txBlock = new TransactionBlock();\n txBlock.moveCall({\n target: queryTarget,\n arguments: [txBlock.object(obligationId as string)],\n });\n const queryResult = await query.client.devInspectTransactionBlock({\n transactionBlock: txBlock,\n sender: query.params.walletAddress,\n });\n return queryResult.events[0].parsedJson as ObligationQueryInterface;\n};\n","import type { SuiObjectResponse } from '@mysten/sui.js/client';\nimport { normalizeStructTag } from '@mysten/sui.js/utils';\n\nimport type { ScallopQuery } from '../models';\nimport type { StakePool, StakeRewardPool, StakeAccounts, SupportStakeMarketCoins, SupportStakeCoins } from '../types';\n\n/**\n * Get all stake accounts of the owner.\n *\n * @param query - The Scallop query instance.\n * @param ownerAddress - Owner address.\n * @return Stake accounts.\n */\nexport const getStakeAccounts = async (query: ScallopQuery, ownerAddress: string) => {\n const owner = ownerAddress;\n const spoolObjectId = query.address.get('spool.object');\n const stakeAccountType = `${spoolObjectId}::spool_account::SpoolAccount`;\n const stakeObjectsResponse: SuiObjectResponse[] = [];\n let hasNextPage = false;\n let nextCursor: string | null = null;\n do {\n const paginatedStakeObjectsResponse = await query.client.getOwnedObjects({\n owner,\n filter: { StructType: stakeAccountType },\n options: {\n showContent: true,\n showType: true,\n },\n cursor: nextCursor,\n });\n stakeObjectsResponse.push(...paginatedStakeObjectsResponse.data);\n if (paginatedStakeObjectsResponse.hasNextPage && paginatedStakeObjectsResponse.nextCursor) {\n hasNextPage = true;\n nextCursor = paginatedStakeObjectsResponse.nextCursor;\n } else {\n hasNextPage = false;\n }\n } while (hasNextPage);\n\n const stakeAccounts: StakeAccounts = {\n sweth: [],\n ssui: [],\n susdc: [],\n swusdc: [],\n swusdt: [],\n scetus: [],\n safsui: [],\n shasui: [],\n svsui: [],\n };\n\n const stakeMarketCoinTypes: Record<SupportStakeMarketCoins, string> = Object.keys(stakeAccounts).reduce(\n (types, stakeMarketCoinName) => {\n const stakeCoinName = query.utils.parseCoinName<SupportStakeCoins>(stakeMarketCoinName);\n const marketCoinType = query.utils.parseMarketCoinType(stakeCoinName);\n\n const updateTypes = { ...types };\n const newType = `${spoolObjectId}::spool_account::SpoolAccount<${marketCoinType}>`;\n updateTypes[stakeMarketCoinName as SupportStakeMarketCoins] = newType;\n return updateTypes;\n },\n {} as Record<SupportStakeMarketCoins, string>,\n );\n\n const stakeObjectIds: string[] = stakeObjectsResponse\n .map((ref: any) => ref?.data?.objectId)\n .filter((id: any) => id !== undefined);\n const stakeObjects = await query.client.multiGetObjects({\n ids: stakeObjectIds,\n options: { showContent: true, showType: true },\n });\n stakeObjects.forEach((stakeObject) => {\n const id = stakeObject.data.objectId;\n const type = stakeObject.data.type!;\n if (stakeObject.data.content && 'fields' in stakeObject.data.content) {\n const fields = stakeObject.data.content.fields as any;\n const stakePoolId = String(fields.spool_id);\n const stakeType = String(fields.stake_type.fields.name);\n const staked = Number(fields.stakes);\n const index = Number(fields.index);\n const points = Number(fields.points);\n const totalPoints = Number(fields.total_points);\n if (normalizeStructTag(type) === stakeMarketCoinTypes.sweth) {\n stakeAccounts.sweth.push({\n id,\n type: normalizeStructTag(type),\n stakePoolId,\n stakeType: normalizeStructTag(stakeType),\n staked,\n index,\n points,\n totalPoints,\n });\n } else if (normalizeStructTag(type) === stakeMarketCoinTypes.ssui) {\n stakeAccounts.ssui.push({\n id,\n type: normalizeStructTag(type),\n stakePoolId,\n stakeType: normalizeStructTag(stakeType),\n staked,\n index,\n points,\n totalPoints,\n });\n } else if (normalizeStructTag(type) === stakeMarketCoinTypes.swusdc) {\n stakeAccounts.swusdc.push({\n id,\n type: normalizeStructTag(type),\n stakePoolId,\n stakeType: normalizeStructTag(stakeType),\n staked,\n index,\n points,\n totalPoints,\n });\n } else if (normalizeStructTag(type) === stakeMarketCoinTypes.swusdt) {\n stakeAccounts.swusdt.push({\n id,\n type: normalizeStructTag(type),\n stakePoolId,\n stakeType: normalizeStructTag(stakeType),\n staked,\n index,\n points,\n totalPoints,\n });\n } else if (normalizeStructTag(type) === stakeMarketCoinTypes.scetus) {\n stakeAccounts.scetus.push({\n id,\n type: normalizeStructTag(type),\n stakePoolId,\n stakeType: normalizeStructTag(stakeType),\n staked,\n index,\n points,\n totalPoints,\n });\n } else if (normalizeStructTag(type) === stakeMarketCoinTypes.safsui) {\n stakeAccounts.safsui.push({\n id,\n type: normalizeStructTag(type),\n stakePoolId,\n stakeType: normalizeStructTag(stakeType),\n staked,\n index,\n points,\n totalPoints,\n });\n } else if (normalizeStructTag(type) === stakeMarketCoinTypes.shasui) {\n stakeAccounts.shasui.push({\n id,\n type: normalizeStructTag(type),\n stakePoolId,\n stakeType: normalizeStructTag(stakeType),\n staked,\n index,\n points,\n totalPoints,\n });\n } else if (normalizeStructTag(type) === stakeMarketCoinTypes.svsui) {\n stakeAccounts.svsui.push({\n id,\n type: normalizeStructTag(type),\n stakePoolId,\n stakeType: normalizeStructTag(stakeType),\n staked,\n index,\n points,\n totalPoints,\n });\n } else if (normalizeStructTag(type) === stakeMarketCoinTypes.susdc) {\n stakeAccounts.susdc.push({\n id,\n type: normalizeStructTag(type),\n stakePoolId,\n stakeType: normalizeStructTag(stakeType),\n staked,\n index,\n points,\n totalPoints,\n });\n }\n }\n });\n return stakeAccounts;\n};\n\n/**\n * Get stake pool data.\n *\n * @description\n * For backward compatible, it is recommended to use `getSpool` method\n * to get stake pool info in spool data.\n *\n * @param query - The Scallop query instance.\n * @param marketCoinName - Specific support stake market coin name.\n * @return Stake pool data.\n */\nexport const getStakePool = async (query: ScallopQuery, marketCoinName: SupportStakeMarketCoins) => {\n const poolId = query.address.get(`spool.pools.${marketCoinName}.id`);\n let stakePool: StakePool | undefined;\n const stakePoolObjectResponse = await query.client.getObject({\n id: poolId,\n options: {\n showContent: true,\n showType: true,\n },\n });\n if (stakePoolObjectResponse.data) {\n const stakePoolObject = stakePoolObjectResponse.data;\n const id = stakePoolObject.objectId;\n const type = stakePoolObject.type!;\n if (stakePoolObject.content && 'fields' in stakePoolObject.content) {\n const fields = stakePoolObject.content.fields as any;\n const maxPoint = Number(fields.max_distributed_point);\n const distributedPoint = Number(fields.distributed_point);\n const pointPerPeriod = Number(fields.distributed_point_per_period);\n const period = Number(fields.point_distribution_time);\n const maxStake = Number(fields.max_stakes);\n const stakeType = String(fields.stake_type.fields.name);\n const totalStaked = Number(fields.stakes);\n const index = Number(fields.index);\n const createdAt = Number(fields.created_at);\n const lastUpdate = Number(fields.last_update);\n stakePool = {\n id,\n type: normalizeStructTag(type),\n maxPoint,\n distributedPoint,\n pointPerPeriod,\n period,\n maxStake,\n stakeType: normalizeStructTag(stakeType),\n totalStaked,\n index,\n createdAt,\n lastUpdate,\n };\n }\n }\n return stakePool;\n};\n\n/**\n * Get stake reward pool of the owner.\n *\n * @description\n * For backward compatible, it is recommended to use `getSpool` method\n * to get reward info in spool data.\n *\n * @param query - The Scallop query instance.\n * @param marketCoinName - Specific support stake market coin name.\n * @return Stake reward pool.\n */\nexport const getStakeRewardPool = async (query: ScallopQuery, marketCoinName: SupportStakeMarketCoins) => {\n const poolId = query.address.get(`spool.pools.${marketCoinName}.rewardPoolId`);\n let stakeRewardPool: StakeRewardPool | undefined;\n const stakeRewardPoolObjectResponse = await query.client.getObject({\n id: poolId,\n options: {\n showContent: true,\n showType: true,\n },\n });\n if (stakeRewardPoolObjectResponse.data) {\n const stakeRewardPoolObject = stakeRewardPoolObjectResponse.data;\n const id = stakeRewardPoolObject.objectId;\n const type = stakeRewardPoolObject.type!;\n if (stakeRewardPoolObject.content && 'fields' in stakeRewardPoolObject.content) {\n const rewardPoolFields = stakeRewardPoolObject.content.fields as any;\n const stakePoolId = String(rewardPoolFields.spool_id);\n const ratioNumerator = Number(rewardPoolFields.exchange_rate_numerator);\n const ratioDenominator = Number(rewardPoolFields.exchange_rate_denominator);\n const rewards = Number(rewardPoolFields.rewards);\n const claimedRewards = Number(rewardPoolFields.claimed_rewards);\n\n stakeRewardPool = {\n id,\n type: normalizeStructTag(type),\n stakePoolId,\n ratioNumerator,\n ratioDenominator,\n rewards,\n claimedRewards,\n };\n }\n }\n return stakeRewardPool;\n};\n","import { SuiClient } from '@mysten/sui.js/client';\nimport { TransactionBlock } from '@mysten/sui.js/transactions';\nimport { normalizeStructTag } from '@mysten/sui.js/utils';\nimport BigNumber from 'bignumber.js';\n\nimport { SUPPORT_BORROW_INCENTIVE_POOLS } from '../constants';\nimport type { ScallopAddress, ScallopQuery } from '../models';\nimport type {\n BorrowIncentiveAccountsQueryInterface,\n BorrowIncentiveAccounts,\n SupportBorrowIncentiveCoins,\n BorrowIncentivePoolsQueryInterface,\n BorrowIncentivePools,\n OptionalKeys,\n BorrowIncentivePoolPoints,\n SupportBorrowIncentiveRewardCoins,\n} from '../types';\nimport { parseOriginBorrowIncentiveAccountData, parseOriginBorrowIncentivePoolData } from '../utils';\n\n/**\n * Query borrow incentive accounts data.\n *\n * @param query - The Scallop query instance.\n * @param borrowIncentiveCoinNames - Specific an array of support borrow incentive coin name.\n * @return Borrow incentive accounts data.\n */\nexport const queryBorrowIncentiveAccounts = async (\n query: ScallopQuery,\n obligationId: string,\n sender: string,\n borrowIncentiveCoinNames?: SupportBorrowIncentiveCoins[],\n) => {\n const coinName = borrowIncentiveCoinNames || [...SUPPORT_BORROW_INCENTIVE_POOLS];\n const queryPkgId = query.address.get('borrowIncentive.query');\n const incentiveAccountsId = query.address.get('borrowIncentive.incentiveAccounts');\n const queryTarget =\n `${queryPkgId}::incentive_account_query::incentive_account_data` as `${string}::${string}::${string}`;\n const txBlock = new TransactionBlock();\n txBlock.moveCall({\n target: queryTarget,\n arguments: [txBlock.object(incentiveAccountsId), txBlock.object(obligationId)],\n });\n const queryResult = await query.client.devInspectTransactionBlock({\n transactionBlock: txBlock,\n sender,\n });\n const borrowIncentiveAccountsQueryData = queryResult.events[0].parsedJson as BorrowIncentiveAccountsQueryInterface;\n\n const borrowIncentiveAccounts: BorrowIncentiveAccounts = {};\n\n borrowIncentiveAccountsQueryData.pool_records.forEach((accountData) => {\n const parsedBorrowIncentiveAccount = parseOriginBorrowIncentiveAccountData(accountData);\n const { poolType } = parsedBorrowIncentiveAccount;\n const parsedCoinName = query.utils.parseCoinNameFromType<SupportBorrowIncentiveCoins>(poolType);\n if (coinName.length >= 1 && coinName.includes(parsedCoinName)) {\n borrowIncentiveAccounts[parsedCoinName] = parsedBorrowIncentiveAccount;\n }\n }, {} as BorrowIncentiveAccounts);\n return borrowIncentiveAccounts;\n};\n\n/**\n * Query borrow incentive pools data.\n *\n * @param query - The Scallop query instance.\n * @param borrowIncentiveCoinNames - Specific an array of support borrow incentive coin name.\n * @param indexer - Whether to use indexer.\n * @return Borrow incentive pools data.\n */\nexport const queryBorrowIncentivePools = async (query: ScallopQuery, coinNames?: SupportBorrowIncentiveCoins[]) => {\n const borrowIncentiveCoinNames = coinNames || [...SUPPORT_BORROW_INCENTIVE_POOLS];\n const queryPkgId = query.address.get('borrowIncentive.query');\n const incentivePoolsId = query.address.get('borrowIncentive.incentivePools');\n\n const txBlock = new TransactionBlock();\n const queryTarget = `${queryPkgId}::incentive_pools_query::incentive_pools_data` as `${string}::${string}::${string}`;\n txBlock.moveCall({ target: queryTarget, arguments: [txBlock.object(incentivePoolsId)] });\n const queryResult = await query.client.devInspectTransactionBlock({\n transactionBlock: txBlock,\n sender: query.params.walletAddress,\n });\n const borrowIncentivePoolsQueryData = queryResult.events[0].parsedJson as BorrowIncentivePoolsQueryInterface;\n\n const borrowIncentivePools: BorrowIncentivePools = {};\n\n for (let i = 0; i < borrowIncentivePoolsQueryData.incentive_pools.length; i++) {\n const pool = borrowIncentivePoolsQueryData.incentive_pools[i];\n const borrowIncentivePoolPoints: OptionalKeys<Record<'sui' | 'sca', BorrowIncentivePoolPoints>> = {};\n const parsedBorrowIncentivePoolData = parseOriginBorrowIncentivePoolData(pool);\n const poolCoinType = normalizeStructTag(pool.pool_type.name);\n const poolCoinName = query.utils.parseCoinNameFromType<SupportBorrowIncentiveCoins>(poolCoinType);\n\n // Filter pools not yet supported by the SDK.\n if (!borrowIncentiveCoinNames.includes(poolCoinName)) {\n continue;\n }\n // pool points for borrow incentive reward ('sui' and 'sca')\n\n Object.entries(parsedBorrowIncentivePoolData.poolPoints).forEach(([coinName, poolPoint]) => {\n const baseIndexRate = 1_000_000_000;\n const rewardCoinType = normalizeStructTag(poolPoint.pointType);\n const rewardCoinName = query.utils.parseCoinNameFromType<SupportBorrowIncentiveRewardCoins>(rewardCoinType);\n const timeDelta = BigNumber(Math.floor(new Date().getTime() / 1000) - poolPoint.lastUpdate)\n .dividedBy(poolPoint.period)\n .toFixed(0);\n\n const accumulatedPoints = BigNumber.minimum(\n BigNumber(timeDelta).multipliedBy(poolPoint.distributedPointPerPeriod),\n BigNumber(poolPoint.points),\n );\n\n const currentPointIndex = BigNumber(poolPoint.index).plus(\n accumulatedPoints.dividedBy(poolPoint.weightedAmount).isFinite()\n ? BigNumber(baseIndexRate).multipliedBy(accumulatedPoints).dividedBy(poolPoint.weightedAmount)\n : 0,\n );\n borrowIncentivePoolPoints[coinName as SupportBorrowIncentiveRewardCoins] = {\n points: poolPoint.points,\n coinDecimal: query.utils.getCoinDecimal(rewardCoinName),\n distributedPoint: poolPoint.distributedPoint,\n weightedAmount: poolPoint.weightedAmount,\n currentPointIndex: currentPointIndex.toNumber(),\n };\n });\n\n borrowIncentivePools[poolCoinName] = {\n coinName: poolCoinName,\n symbol: query.utils.parseSymbol(poolCoinName),\n coinType: poolCoinType,\n points: borrowIncentivePoolPoints,\n };\n }\n\n return borrowIncentivePools;\n};\n\nexport const getBindedVeScaKey = async (\n {\n address,\n client,\n }: {\n address: ScallopAddress;\n client: SuiClient;\n },\n obligationId: string,\n): Promise<string | null> => {\n const borrowIncentiveObjectId = address.get('borrowIncentive.object');\n const incentiveAccountsId = address.get('borrowIncentive.incentiveAccounts');\n const corePkg = address.get('core.object');\n\n // get IncentiveAccounts object\n const incentiveAccountsObject = await client.getObject({\n id: incentiveAccountsId,\n options: {\n showContent: true,\n },\n });\n if (incentiveAccountsObject?.data?.content?.dataType !== 'moveObject') {\n return null;\n }\n const incentiveAccountsTableId = (incentiveAccountsObject.data.content.fields as any).accounts.fields.id.id;\n\n // Search in the table\n const bindedIncentiveAcc = await client.getDynamicFieldObject({\n parentId: incentiveAccountsTableId,\n name: {\n type: `${borrowIncentiveObjectId}::typed_id::TypedID<${corePkg}::obligation::Obligation>`,\n value: obligationId,\n },\n });\n\n if (bindedIncentiveAcc?.data?.content?.dataType !== 'moveObject') {\n return null;\n }\n const bindedIncentiveAccFields = bindedIncentiveAcc.data.content.fields as any;\n\n return bindedIncentiveAccFields.value.fields.binded_ve_sca_key?.fields.id ?? null;\n};\n","import { TransactionBlock } from '@mysten/sui.js/transactions';\n\nimport {\n MAX_LOCK_DURATION,\n MAX_LOCK_ROUNDS,\n MIN_INITIAL_LOCK_AMOUNT,\n MIN_TOP_UP_AMOUNT,\n UNLOCK_ROUND_DURATION,\n} from '../constants';\nimport { SuiObjectArg } from '../types';\n\n/**\n * Check and get the sender from the transaction block.\n *\n * @param txBlock - TxBlock created by SuiKit.\n * @return Sender of transaction.\n */\nexport const requireSender = (txBlock: TransactionBlock) => {\n const { sender } = txBlock.blockData;\n if (!sender) {\n throw new Error('Sender is required');\n }\n return sender;\n};\n\nexport const checkLockSca = (\n scaAmountOrCoin?: number | SuiObjectArg | undefined,\n lockPeriodInDays?: number,\n newUnlockAtInSecondTimestamp?: number,\n prevUnlockAtInSecondTimestamp?: number,\n) => {\n const isInitialLock = !prevUnlockAtInSecondTimestamp;\n const isLockExpired = !isInitialLock && prevUnlockAtInSecondTimestamp * 1000 <= new Date().getTime();\n if (isInitialLock || isLockExpired) {\n if (scaAmountOrCoin !== undefined && lockPeriodInDays !== undefined) {\n if (lockPeriodInDays <= 0) {\n throw new Error('Lock period must be greater than 0');\n }\n if (typeof scaAmountOrCoin === 'number' && scaAmountOrCoin < MIN_INITIAL_LOCK_AMOUNT) {\n throw new Error(\n `Minimum lock amount for ${isLockExpired ? 'renewing expired veSca' : 'initial lock'} is 10 SCA`,\n );\n }\n const extendLockPeriodInSecond = lockPeriodInDays * UNLOCK_ROUND_DURATION;\n if (extendLockPeriodInSecond > MAX_LOCK_DURATION) {\n throw new Error(`Maximum lock period is ~4 years (${MAX_LOCK_ROUNDS} days)`);\n }\n } else {\n throw new Error(\n `SCA amount and lock period is required for ${isLockExpired ? 'renewing expired veSca' : 'initial lock'}`,\n );\n }\n } else {\n checkVesca(prevUnlockAtInSecondTimestamp);\n if (typeof scaAmountOrCoin === 'number' && scaAmountOrCoin < MIN_TOP_UP_AMOUNT) {\n throw new Error('Minimum top up amount is 1 SCA');\n }\n\n if (!!newUnlockAtInSecondTimestamp && !!prevUnlockAtInSecondTimestamp) {\n const totalLockDuration = newUnlockAtInSecondTimestamp - prevUnlockAtInSecondTimestamp;\n if (totalLockDuration > MAX_LOCK_DURATION - UNLOCK_ROUND_DURATION) {\n throw new Error(`Maximum lock period is ~4 years (${MAX_LOCK_ROUNDS - 1} days)`);\n }\n }\n }\n};\n\nexport const checkExtendLockPeriod = (\n lockPeriodInDays: number,\n newUnlockAtInSecondTimestamp: number,\n prevUnlockAtInSecondTimestamp?: number,\n) => {\n checkVesca(prevUnlockAtInSecondTimestamp);\n\n if (lockPeriodInDays <= 0) {\n throw new Error('Lock period must be greater than 0');\n }\n\n const isInitialLock = !prevUnlockAtInSecondTimestamp;\n const isLockExpired = !isInitialLock && prevUnlockAtInSecondTimestamp * 1000 <= new Date().getTime();\n if (isLockExpired) {\n throw new Error('veSca is expired, use renewExpiredVeScaQuick instead');\n }\n\n if (prevUnlockAtInSecondTimestamp) {\n const totalLockDuration = newUnlockAtInSecondTimestamp - (prevUnlockAtInSecondTimestamp ?? 0);\n if (totalLockDuration > MAX_LOCK_DURATION - UNLOCK_ROUND_DURATION) {\n throw new Error(`Maximum lock period is ~4 years (${MAX_LOCK_ROUNDS - 1} days)`);\n }\n }\n};\n\nexport const checkExtendLockAmount = (scaAmount: number, prevUnlockAtInSecondTimestamp?: number) => {\n checkVesca(prevUnlockAtInSecondTimestamp);\n\n if (scaAmount < MIN_TOP_UP_AMOUNT) {\n throw new Error('Minimum top up amount is 1 SCA');\n }\n\n const isInitialLock = !prevUnlockAtInSecondTimestamp;\n const isLockExpired = !isInitialLock && prevUnlockAtInSecondTimestamp * 1000 <= new Date().getTime();\n if (isLockExpired) {\n throw new Error('veSca is expired, use renewExpiredVeScaQuick instead');\n }\n};\n\nexport const checkRenewExpiredVeSca = (\n scaAmount: number,\n lockPeriodInDays: number,\n prevUnlockAtInSecondTimestamp?: number,\n) => {\n checkVesca(prevUnlockAtInSecondTimestamp);\n\n if (scaAmount < MIN_INITIAL_LOCK_AMOUNT) {\n throw new Error('Minimum lock amount for renewing expired vesca 10 SCA');\n }\n\n const extendLockPeriodInSecond = lockPeriodInDays * UNLOCK_ROUND_DURATION;\n if (extendLockPeriodInSecond >= MAX_LOCK_DURATION - UNLOCK_ROUND_DURATION) {\n throw new Error(`Maximum lock period is ~4 years (${MAX_LOCK_ROUNDS - 1} days)`);\n }\n};\n\nexport const checkVesca = (prevUnlockAtInSecondTimestamp?: number) => {\n if (prevUnlockAtInSecondTimestamp === undefined) {\n throw new Error('veSca not found');\n }\n};\n","import { normalizeStructTag, parseStructTag } from '@mysten/sui.js/utils';\n// eslint-disable-next-line import/no-extraneous-dependencies\nimport BigNumber from 'bignumber.js';\n\nimport type { ScallopUtils } from '../models';\nimport type {\n OriginMarketPoolData,\n ParsedMarketPoolData,\n CalculatedMarketPoolData,\n OriginMarketCollateralData,\n ParsedMarketCollateralData,\n CalculatedMarketCollateralData,\n OriginSpoolData,\n ParsedSpoolData,\n CalculatedSpoolData,\n OriginSpoolRewardPoolData,\n ParsedSpoolRewardPoolData,\n CalculatedSpoolRewardPoolData,\n OriginBorrowIncentivePoolData,\n ParsedBorrowIncentivePoolData,\n OriginBorrowIncentiveAccountData,\n ParsedBorrowIncentiveAccountData,\n SupportPoolCoins,\n SupportCollateralCoins,\n OriginBorrowIncentiveAccountPoolData,\n ParsedBorrowIncentiveAccountPoolData,\n SupportBorrowIncentiveRewardCoins,\n ParsedBorrowIncentivePoolPointData,\n OriginBorrowIncentivePoolPointData,\n} from '../types';\n\n/**\n * Parse origin market pool data to a more readable format.\n *\n * @param originMarketPoolData - Origin market pool data\n * @return Parsed market pool data\n */\nexport const parseOriginMarketPoolData = (originMarketPoolData: OriginMarketPoolData): ParsedMarketPoolData => ({\n coinType: normalizeStructTag(originMarketPoolData.type.name),\n // Parse origin data required for basic calculations.\n maxBorrowRate: Number(originMarketPoolData.maxBorrowRate.value) / 2 ** 32,\n borrowRate: Number(originMarketPoolData.interestRate.value) / 2 ** 32,\n borrowRateScale: Number(originMarketPoolData.interestRateScale),\n borrowIndex: Number(originMarketPoolData.borrowIndex),\n lastUpdated: Number(originMarketPoolData.lastUpdated),\n cashAmount: Number(originMarketPoolData.cash),\n debtAmount: Number(originMarketPoolData.debt),\n marketCoinSupplyAmount: Number(originMarketPoolData.marketCoinSupply),\n reserveAmount: Number(originMarketPoolData.reserve),\n reserveFactor: Number(originMarketPoolData.reserveFactor.value) / 2 ** 32,\n borrowWeight: Number(originMarketPoolData.borrowWeight.value) / 2 ** 32,\n borrowFee: Number(originMarketPoolData.borrowFeeRate.value) / 2 ** 32,\n // Parse origin data required for additional display.\n baseBorrowRate: Number(originMarketPoolData.baseBorrowRatePerSec.value) / 2 ** 32,\n borrowRateOnHighKink: Number(originMarketPoolData.borrowRateOnHighKink.value) / 2 ** 32,\n borrowRateOnMidKink: Number(originMarketPoolData.borrowRateOnMidKink.value) / 2 ** 32,\n highKink: Number(originMarketPoolData.highKink.value) / 2 ** 32,\n midKink: Number(originMarketPoolData.midKink.value) / 2 ** 32,\n minBorrowAmount: Number(originMarketPoolData.minBorrowAmount),\n});\n\nexport const calculateMarketPoolData = (\n utils: ScallopUtils,\n parsedMarketPoolData: ParsedMarketPoolData,\n): CalculatedMarketPoolData => {\n const poolCoinName = utils.parseCoinNameFromType<SupportPoolCoins>(parsedMarketPoolData.coinType);\n const coinDecimal = utils.getCoinDecimal(poolCoinName);\n\n const borrowYearFactor = 24 * 365 * 3600;\n\n const baseBorrowApr = (parsedMarketPoolData.baseBorrowRate * borrowYearFactor) / parsedMarketPoolData.borrowRateScale;\n const borrowAprOnHighKink =\n (parsedMarketPoolData.borrowRateOnHighKink * borrowYearFactor) / parsedMarketPoolData.borrowRateScale;\n const borrowAprOnMidKink =\n (parsedMarketPoolData.borrowRateOnMidKink * borrowYearFactor) / parsedMarketPoolData.borrowRateScale;\n const maxBorrowApr = (parsedMarketPoolData.maxBorrowRate * borrowYearFactor) / parsedMarketPoolData.borrowRateScale;\n const borrowApr = (parsedMarketPoolData.borrowRate * borrowYearFactor) / parsedMarketPoolData.borrowRateScale;\n\n const timeDelta = Math.floor(new Date().getTime() / 1000) - parsedMarketPoolData.lastUpdated;\n const borrowIndexDelta = BigNumber(parsedMarketPoolData.borrowIndex)\n .multipliedBy(BigNumber(timeDelta).multipliedBy(parsedMarketPoolData.borrowRate))\n .dividedBy(parsedMarketPoolData.borrowRateScale);\n const currentBorrowIndex = BigNumber(parsedMarketPoolData.borrowIndex).plus(borrowIndexDelta);\n // How much accumulated interest since `lastUpdate`.\n const growthInterest = BigNumber(currentBorrowIndex).dividedBy(parsedMarketPoolData.borrowIndex).minus(1);\n const increasedDebtAmount = BigNumber(parsedMarketPoolData.debtAmount).multipliedBy(growthInterest);\n const borrowAmount = increasedDebtAmount.plus(parsedMarketPoolData.debtAmount);\n const borrowCoin = borrowAmount.shiftedBy(-1 * coinDecimal);\n const reserveAmount = BigNumber(parsedMarketPoolData.reserveAmount).plus(\n increasedDebtAmount.multipliedBy(parsedMarketPoolData.reserveFactor),\n );\n const reserveCoin = reserveAmount.shiftedBy(-1 * coinDecimal);\n const supplyAmount = BigNumber(borrowAmount).plus(\n Math.max(parsedMarketPoolData.cashAmount - reserveAmount.toNumber(), 0),\n );\n const supplyCoin = supplyAmount.shiftedBy(-1 * coinDecimal);\n let utilizationRate = BigNumber(borrowAmount).dividedBy(supplyAmount);\n utilizationRate = utilizationRate.isFinite() ? utilizationRate : BigNumber(0);\n let supplyApr = BigNumber(borrowApr)\n .multipliedBy(utilizationRate)\n .multipliedBy(1 - parsedMarketPoolData.reserveFactor);\n supplyApr = supplyApr.isFinite() ? supplyApr : BigNumber(0);\n let conversionRate = supplyAmount.dividedBy(parsedMarketPoolData.marketCoinSupplyAmount);\n conversionRate = conversionRate.isFinite() && !conversionRate.isNaN() ? conversionRate : BigNumber(1);\n\n return {\n baseBorrowApr,\n baseBorrowApy: utils.parseAprToApy(baseBorrowApr),\n borrowAprOnHighKink,\n borrowApyOnHighKink: utils.parseAprToApy(borrowAprOnHighKink),\n borrowAprOnMidKink,\n borrowApyOnMidKink: utils.parseAprToApy(borrowAprOnMidKink),\n maxBorrowApr,\n maxBorrowApy: utils.parseAprToApy(maxBorrowApr),\n borrowApr: Math.min(borrowApr, maxBorrowApr),\n borrowApy: Math.min(utils.parseAprToApy(borrowApr), utils.parseAprToApy(maxBorrowApr)),\n borrowIndex: currentBorrowIndex.toNumber(),\n growthInterest: growthInterest.toNumber(),\n supplyAmount: supplyAmount.toNumber(),\n supplyCoin: supplyCoin.toNumber(),\n borrowAmount: borrowAmount.toNumber(),\n borrowCoin: borrowCoin.toNumber(),\n reserveAmount: reserveAmount.toNumber(),\n reserveCoin: reserveCoin.toNumber(),\n utilizationRate: utilizationRate.toNumber(),\n supplyApr: supplyApr.toNumber(),\n supplyApy: utils.parseAprToApy(supplyApr.toNumber()),\n conversionRate: conversionRate.toNumber(),\n };\n};\n\n/**\n * Parse origin market collateral data to a more readable format.\n *\n * @param originMarketCollateralData - Origin market collateral data\n * @return Parsed market collateral data\n */\nexport const parseOriginMarketCollateralData = (\n originMarketCollateralData: OriginMarketCollateralData,\n): ParsedMarketCollateralData => ({\n coinType: normalizeStructTag(originMarketCollateralData.type.name),\n collateralFactor: Number(originMarketCollateralData.collateralFactor.value) / 2 ** 32,\n liquidationFactor: Number(originMarketCollateralData.liquidationFactor.value) / 2 ** 32,\n liquidationDiscount: Number(originMarketCollateralData.liquidationDiscount.value) / 2 ** 32,\n liquidationPanelty: Number(originMarketCollateralData.liquidationPanelty.value) / 2 ** 32,\n liquidationReserveFactor: Number(originMarketCollateralData.liquidationReserveFactor.value) / 2 ** 32,\n maxCollateralAmount: Number(originMarketCollateralData.maxCollateralAmount),\n totalCollateralAmount: Number(originMarketCollateralData.totalCollateralAmount),\n});\n\nexport const calculateMarketCollateralData = (\n utils: ScallopUtils,\n parsedMarketCollateralData: ParsedMarketCollateralData,\n): CalculatedMarketCollateralData => {\n const collateralCoinName = utils.parseCoinNameFromType<SupportCollateralCoins>(parsedMarketCollateralData.coinType);\n const coinDecimal = utils.getCoinDecimal(collateralCoinName);\n\n const maxCollateralCoin = BigNumber(parsedMarketCollateralData.maxCollateralAmount).shiftedBy(-1 * coinDecimal);\n const depositCoin = BigNumber(parsedMarketCollateralData.totalCollateralAmount).shiftedBy(-1 * coinDecimal);\n\n return {\n maxDepositAmount: parsedMarketCollateralData.maxCollateralAmount,\n maxDepositCoin: maxCollateralCoin.toNumber(),\n depositAmount: parsedMarketCollateralData.totalCollateralAmount,\n depositCoin: depositCoin.toNumber(),\n };\n};\n\n/**\n * Parse origin spool data to a more readable format.\n *\n * @param originSpoolData - Origin spool data\n * @return Parsed spool data\n */\nexport const parseOriginSpoolData = (originSpoolData: OriginSpoolData): ParsedSpoolData => ({\n stakeType: normalizeStructTag(originSpoolData.stakeType.fields.name),\n maxPoint: Number(originSpoolData.maxDistributedPoint),\n distributedPoint: Number(originSpoolData.distributedPoint),\n pointPerPeriod: Number(originSpoolData.distributedPointPerPeriod),\n period: Number(originSpoolData.pointDistributionTime),\n maxStake: Number(originSpoolData.maxStake),\n staked: Number(originSpoolData.stakes),\n index: Number(originSpoolData.index),\n createdAt: Number(originSpoolData.createdAt),\n lastUpdate: Number(originSpoolData.lastUpdate),\n});\n\nexport const calculateSpoolData = (\n parsedSpoolData: ParsedSpoolData,\n stakeMarketCoinPrice: number,\n stakeMarketCoinDecimal: number,\n): CalculatedSpoolData => {\n const baseIndexRate = 1_000_000_000;\n\n const distributedPointPerSec = BigNumber(parsedSpoolData.pointPerPeriod).dividedBy(parsedSpoolData.period);\n\n const pointPerSec = BigNumber(parsedSpoolData.pointPerPeriod).dividedBy(parsedSpoolData.period);\n const remainingPeriod = BigNumber(parsedSpoolData.maxPoint)\n .minus(parsedSpoolData.distributedPoint)\n .dividedBy(pointPerSec);\n const startDate = parsedSpoolData.createdAt;\n const endDate = remainingPeriod.plus(parsedSpoolData.lastUpdate).integerValue().toNumber();\n\n const timeDelta = BigNumber(Math.floor(new Date().getTime() / 1000) - parsedSpoolData.lastUpdate)\n .dividedBy(parsedSpoolData.period)\n .toFixed(0);\n const remainingPoints = BigNumber(parsedSpoolData.maxPoint).minus(parsedSpoolData.distributedPoint);\n const accumulatedPoints = BigNumber.minimum(\n BigNumber(timeDelta).multipliedBy(parsedSpoolData.pointPerPeriod),\n remainingPoints,\n );\n\n const currentPointIndex = BigNumber(parsedSpoolData.index).plus(\n accumulatedPoints.dividedBy(parsedSpoolData.staked).isFinite()\n ? BigNumber(baseIndexRate).multipliedBy(accumulatedPoints).dividedBy(parsedSpoolData.staked)\n : 0,\n );\n const currentTotalDistributedPoint = BigNumber(parsedSpoolData.distributedPoint).plus(accumulatedPoints);\n\n const stakedAmount = BigNumber(parsedSpoolData.staked);\n const stakedCoin = stakedAmount.shiftedBy(-1 * stakeMarketCoinDecimal);\n const stakedValue = stakedCoin.multipliedBy(stakeMarketCoinPrice);\n\n return {\n distributedPointPerSec: distributedPointPerSec.toNumber(),\n accumulatedPoints: accumulatedPoints.toNumber(),\n currentPointIndex: currentPointIndex.toNumber(),\n currentTotalDistributedPoint: currentTotalDistributedPoint.toNumber(),\n startDate: new Date(startDate * 1000),\n endDate: new Date(endDate * 1000),\n stakedAmount: stakedAmount.toNumber(),\n stakedCoin: stakedCoin.toNumber(),\n stakedValue: stakedValue.toNumber(),\n };\n};\n\n/**\n * Parse origin spool reward pool data to a more readable format.\n *\n * @param originRewardPoolData - Origin reward pool data\n * @return Parsed spool reward pool data\n */\nexport const parseOriginSpoolRewardPoolData = (\n originSpoolRewardPoolData: OriginSpoolRewardPoolData,\n): ParsedSpoolRewardPoolData => ({\n claimedRewards: Number(originSpoolRewardPoolData.claimed_rewards),\n exchangeRateDenominator: Number(originSpoolRewardPoolData.exchange_rate_denominator),\n exchangeRateNumerator: Number(originSpoolRewardPoolData.exchange_rate_numerator),\n rewards: Number(originSpoolRewardPoolData.rewards),\n spoolId: String(originSpoolRewardPoolData.spool_id),\n});\n\nexport const calculateSpoolRewardPoolData = (\n parsedSpoolData: ParsedSpoolData,\n parsedSpoolRewardPoolData: ParsedSpoolRewardPoolData,\n calculatedSpoolData: CalculatedSpoolData,\n rewardCoinPrice: number,\n rewardCoinDecimal: number,\n): CalculatedSpoolRewardPoolData => {\n const rateYearFactor = 365 * 24 * 60 * 60;\n\n const rewardPerSec = BigNumber(calculatedSpoolData.distributedPointPerSec)\n .multipliedBy(parsedSpoolRewardPoolData.exchangeRateNumerator)\n .dividedBy(parsedSpoolRewardPoolData.exchangeRateDenominator);\n const totalRewardAmount = BigNumber(parsedSpoolData.maxPoint)\n .multipliedBy(parsedSpoolRewardPoolData.exchangeRateNumerator)\n .dividedBy(parsedSpoolRewardPoolData.exchangeRateDenominator);\n const totalRewardCoin = totalRewardAmount.shiftedBy(-1 * rewardCoinDecimal);\n const totalRewardValue = totalRewardCoin.multipliedBy(rewardCoinPrice);\n const remaindRewardAmount = BigNumber(parsedSpoolRewardPoolData.rewards);\n const remaindRewardCoin = remaindRewardAmount.shiftedBy(-1 * rewardCoinDecimal);\n const remaindRewardValue = remaindRewardCoin.multipliedBy(rewardCoinPrice);\n const claimedRewardAmount = BigNumber(parsedSpoolRewardPoolData.claimedRewards);\n const claimedRewardCoin = claimedRewardAmount.shiftedBy(-1 * rewardCoinDecimal);\n const claimedRewardValue = claimedRewardCoin.multipliedBy(rewardCoinPrice);\n\n const rewardValueForYear = BigNumber(rewardPerSec)\n .shiftedBy(-1 * rewardCoinDecimal)\n .multipliedBy(rateYearFactor)\n .multipliedBy(rewardCoinPrice);\n\n let rewardRate = rewardValueForYear.dividedBy(calculatedSpoolData.stakedValue).isFinite()\n ? rewardValueForYear.dividedBy(calculatedSpoolData.stakedValue).toNumber()\n : Infinity;\n\n if (parsedSpoolData.maxPoint === parsedSpoolData.distributedPoint) {\n rewardRate = Infinity;\n }\n\n return {\n rewardApr: rewardRate,\n totalRewardAmount: totalRewardAmount.toNumber(),\n totalRewardCoin: totalRewardCoin.toNumber(),\n totalRewardValue: totalRewardValue.toNumber(),\n remaindRewardAmount: remaindRewardAmount.toNumber(),\n remaindRewardCoin: remaindRewardCoin.toNumber(),\n remaindRewardValue: remaindRewardValue.toNumber(),\n claimedRewardAmount: claimedRewardAmount.toNumber(),\n claimedRewardCoin: claimedRewardCoin.toNumber(),\n claimedRewardValue: claimedRewardValue.toNumber(),\n rewardPerSec: rewardPerSec.toNumber(),\n };\n};\n\n/**\n * Parse origin borrow incentive pool data to a more readable format.\n *\n * @param originBorrowIncentivePoolData - Origin borrow incentive pool data\n * @return Parsed borrow incentive pool data\n */\nexport const parseOriginBorrowIncentivesPoolPointData = (\n originBorrowIncentivePoolPointData: OriginBorrowIncentivePoolPointData,\n): ParsedBorrowIncentivePoolPointData => ({\n pointType: normalizeStructTag(originBorrowIncentivePoolPointData.point_type.name),\n distributedPointPerPeriod: Number(originBorrowIncentivePoolPointData.distributed_point_per_period),\n period: Number(originBorrowIncentivePoolPointData.point_distribution_time),\n distributedPoint: Number(originBorrowIncentivePoolPointData.distributed_point),\n points: Number(originBorrowIncentivePoolPointData.points),\n index: Number(originBorrowIncentivePoolPointData.index),\n baseWeight: Number(originBorrowIncentivePoolPointData.base_weight),\n weightedAmount: Number(originBorrowIncentivePoolPointData.weighted_amount),\n lastUpdate: Number(originBorrowIncentivePoolPointData.last_update),\n});\nexport const parseOriginBorrowIncentivePoolData = (\n originBorrowIncentivePoolData: OriginBorrowIncentivePoolData,\n): ParsedBorrowIncentivePoolData => ({\n poolType: normalizeStructTag(originBorrowIncentivePoolData.pool_type.name),\n minStakes: Number(originBorrowIncentivePoolData.min_stakes),\n maxStakes: Number(originBorrowIncentivePoolData.max_stakes),\n staked: Number(originBorrowIncentivePoolData.stakes),\n createdAt: Number(originBorrowIncentivePoolData.created_at),\n poolPoints: originBorrowIncentivePoolData.points.reduce(\n (acc, point) => {\n const parsed = parseOriginBorrowIncentivesPoolPointData(point);\n const name = parseStructTag(parsed.pointType).name.toLowerCase() as SupportBorrowIncentiveRewardCoins;\n acc[name] = parsed;\n return acc;\n },\n {} as Record<SupportBorrowIncentiveRewardCoins, ParsedBorrowIncentivePoolPointData>,\n ),\n});\n\n/**\n * Parse origin borrow incentive reward pool data to a more readable format.\n *\n * @param originBorrowIncentiveRewardPoolData - Origin borrow incentive reward pool data\n * @return Parsed borrow incentive reward pool data\n */\n\nexport const minBigNumber = (...args: BigNumber.Value[]) =>\n BigNumber(args.reduce((min, current) => (new BigNumber(current).lt(min) ? current : min)));\n\nexport const maxBigNumber = (...args: BigNumber.Value[]) =>\n BigNumber(args.reduce((max, current) => (new BigNumber(current).gt(max) ? current : max)));\n\n/**\n * Dynamically adjust the decrease or increase ratio according to the amout\n * @param amount - The amount required to calculate factor.\n * @param scaleStep - The scale step required to determine the factor..\n * @param type - The type of the calculation.\n * @return The estimated factor\n * */\nexport const estimatedFactor = (amount: number, scaleStep: number, type: 'increase' | 'decrease') => {\n const amountOfDigits = Math.max(1, Math.floor(Math.log10(Math.abs(amount)) + 1));\n\n const adjustScale = Math.max(Math.floor((amountOfDigits - 1) / scaleStep), 1) + 1;\n\n let adjustFactor = 10 ** -adjustScale;\n adjustFactor = type === 'increase' ? 1 - adjustFactor : 1 + adjustFactor;\n\n return adjustFactor;\n};\n\nexport const parseOriginBorrowIncentiveAccountPoolPointData = (\n originBorrowIncentiveAccountPoolPointData: OriginBorrowIncentiveAccountPoolData,\n): ParsedBorrowIncentiveAccountPoolData => ({\n pointType: normalizeStructTag(originBorrowIncentiveAccountPoolPointData.point_type.name),\n weightedAmount: Number(originBorrowIncentiveAccountPoolPointData.weighted_amount),\n points: Number(originBorrowIncentiveAccountPoolPointData.points),\n totalPoints: Number(originBorrowIncentiveAccountPoolPointData.total_points),\n index: Number(originBorrowIncentiveAccountPoolPointData.index),\n});\n\n/**\n * Parse origin borrow incentive account data to a more readable format.\n *\n * @param originBorrowIncentiveAccountData - Origin borrow incentive account data\n * @return Parsed borrow incentive account data\n */\nexport const parseOriginBorrowIncentiveAccountData = (\n originBorrowIncentiveAccountData: OriginBorrowIncentiveAccountData,\n): ParsedBorrowIncentiveAccountData => ({\n poolType: normalizeStructTag(originBorrowIncentiveAccountData.pool_type.name),\n debtAmount: Number(originBorrowIncentiveAccountData.debt_amount),\n pointList: originBorrowIncentiveAccountData.points_list.reduce(\n (acc, point) => {\n const parsed = parseOriginBorrowIncentiveAccountPoolPointData(point);\n const name = parseStructTag(parsed.pointType).name.toLowerCase() as SupportBorrowIncentiveRewardCoins;\n acc[name] = parsed;\n return acc;\n },\n {} as Record<SupportBorrowIncentiveRewardCoins, ParsedBorrowIncentiveAccountPoolData>,\n ),\n});\n","import { SUPPORT_POOLS, SUPPORT_COLLATERALS, SUPPORT_SPOOLS_REWARDS, MAX_LOCK_DURATION } from '../constants';\nimport type { SupportAssetCoins, SupportCoins, SupportMarketCoins } from '../types';\n\nexport const isMarketCoin = (coinName: SupportCoins): coinName is SupportMarketCoins => {\n const assetCoinName = coinName.slice(1).toLowerCase() as SupportAssetCoins;\n return (\n coinName.charAt(0).toLowerCase() === 's' &&\n [...new Set([...SUPPORT_POOLS, ...SUPPORT_COLLATERALS, ...SUPPORT_SPOOLS_REWARDS])].includes(assetCoinName)\n );\n};\n\nexport const parseAssetSymbol = (coinName: SupportAssetCoins): string => {\n switch (coinName) {\n case 'afsui':\n return 'afSUI';\n case 'hasui':\n return 'haSUI';\n case 'vsui':\n return 'vSUI';\n default:\n return coinName.toUpperCase();\n }\n};\n\n/**\n * Find the closest unlock round timestamp (12AM) to the given unlock at timestamp in seconds.\n *\n * @param unlockAtInSecondTimestamp - Unlock at in seconds timestamp to find the closest round.\n * @returns Closest round (12AM) in seconds timestamp.\n */\nexport const findClosestUnlockRound = (unlockAtInSecondTimestamp: number) => {\n const unlockDate = new Date(unlockAtInSecondTimestamp * 1000);\n const closestTwelveAM = new Date(unlockAtInSecondTimestamp * 1000);\n\n closestTwelveAM.setUTCHours(0, 0, 0, 0); // Set the time to the next 12 AM UTC\n\n // If the current time is past 12 AM, set the date to the next day\n if (unlockDate.getUTCHours() >= 0) {\n closestTwelveAM.setUTCDate(closestTwelveAM.getUTCDate() + 1);\n }\n\n const now = new Date().getTime();\n // check if unlock period > 4 years\n if (closestTwelveAM.getTime() - now > MAX_LOCK_DURATION * 1000) {\n closestTwelveAM.setUTCDate(closestTwelveAM.getUTCDate() - 1);\n }\n return Math.floor(closestTwelveAM.getTime() / 1000);\n};\n","import type { ScallopQuery } from '../models';\nimport type { SupportAssetCoins } from '../types';\n\n/**\n * Get price from pyth fee object.\n *\n * @param query - The Scallop query instance.\n * @param assetCoinName - Specific support asset coin name.\n * @return Asset coin price.\n */\nexport const getPythPrice = async (query: ScallopQuery, assetCoinName: SupportAssetCoins) => {\n const pythFeedObjectId = query.address.get(`core.coins.${assetCoinName}.oracle.pyth.feedObject`);\n const priceFeedObjectResponse = await query.client.getObject({\n id: pythFeedObjectId,\n options: {\n showContent: true,\n },\n });\n\n if (priceFeedObjectResponse.data) {\n const priceFeedPoolObject = priceFeedObjectResponse.data;\n if (priceFeedPoolObject.content && 'fields' in priceFeedPoolObject.content) {\n const fields = priceFeedPoolObject.content.fields as any;\n const expoMagnitude = Number(fields.price_info.fields.price_feed.fields.price.fields.expo.fields.magnitude);\n const expoNegative = Number(fields.price_info.fields.price_feed.fields.price.fields.expo.fields.negative);\n const priceMagnitude = Number(fields.price_info.fields.price_feed.fields.price.fields.price.fields.magnitude);\n const priceNegative = Number(fields.price_info.fields.price_feed.fields.price.fields.price.fields.negative);\n\n return priceMagnitude * 10 ** ((expoNegative ? -1 : 1) * expoMagnitude) * (priceNegative ? -1 : 1);\n }\n }\n\n return 0;\n};\n","import type { SuiObjectResponse, SuiObjectData } from '@mysten/sui.js/client';\nimport BigNumber from 'bignumber.js';\n\nimport type { ScallopQuery } from '../models';\nimport { Vesca } from '../types';\n\n/**\n * Query all owned veSca key.\n *\n * @param query - The Scallop query instance.\n * @param ownerAddress - The owner address.\n * @return Owned veSca key.\n */\nexport const getVescaKeys = async (query: ScallopQuery, ownerAddress?: string) => {\n const owner = ownerAddress;\n const veScaPkgId = query.address.get('vesca.id');\n const veScaKeyType = `${veScaPkgId}::ve_sca::VeScaKey`;\n const keyObjectsResponse: SuiObjectResponse[] = [];\n let hasNextPage = false;\n let nextCursor: string | null | undefined = null;\n do {\n const paginatedKeyObjectsResponse = await query.client.getOwnedObjects({\n owner,\n filter: {\n StructType: veScaKeyType,\n },\n cursor: nextCursor,\n });\n keyObjectsResponse.push(...paginatedKeyObjectsResponse.data);\n if (paginatedKeyObjectsResponse.hasNextPage && paginatedKeyObjectsResponse.nextCursor) {\n hasNextPage = true;\n nextCursor = paginatedKeyObjectsResponse.nextCursor;\n } else {\n hasNextPage = false;\n }\n } while (hasNextPage);\n\n const keyObjectDatas = keyObjectsResponse\n .map((objResponse) => objResponse.data)\n .filter((data) => !!data) as SuiObjectData[];\n return keyObjectDatas;\n};\n\n/**\n * Query all owned veSca.\n *\n * @param query - The Scallop query instance.\n * @param ownerAddress - The owner address.\n * @return Owned veScas.\n */\nexport const getVeScas = async (query: ScallopQuery, ownerAddress?: string) => {\n const keyObjectDatas = await getVescaKeys(query, ownerAddress);\n const keyObjectId: string[] = keyObjectDatas.map((data) => data.objectId);\n\n const veScas: Vesca[] = [];\n for (let i = 0; i < keyObjectId.length; i++) {\n const veSca = await getVeSca(query, keyObjectId[i]);\n if (veSca) {\n veScas.push(veSca);\n }\n }\n return veScas;\n};\n\n/**\n * Get veSca data.\n *\n * @param query - The Scallop query instance.\n * @param veScaKeyId - The vesca key id.\n * @param ownerAddress - The owner address.\n * @returns Vesca data.\n */\nexport const getVeSca = async (query: ScallopQuery, veScaKeyId?: string, ownerAddress?: string) => {\n const tableId = query.address.get(`vesca.tableId`);\n const veScaKeyIdValue = veScaKeyId || (await getVescaKeys(query, ownerAddress))[0].objectId;\n\n let vesca: Vesca | undefined;\n\n const veScaDynamicFieldObjectResponse = await query.client.getDynamicFieldObject({\n parentId: tableId,\n name: {\n type: '0x2::object::ID',\n value: veScaKeyIdValue,\n },\n });\n const veScaDynamicFieldObject = veScaDynamicFieldObjectResponse.data;\n if (\n veScaDynamicFieldObject &&\n veScaDynamicFieldObject.content &&\n veScaDynamicFieldObject.content.dataType === 'moveObject' &&\n 'fields' in veScaDynamicFieldObject.content\n ) {\n const dynamicFields = (veScaDynamicFieldObject.content.fields as any).value.fields;\n vesca = {\n id: veScaDynamicFieldObject.objectId,\n keyId: veScaKeyIdValue,\n lockedScaAmount: BigNumber(dynamicFields.locked_sca_amount).toNumber(),\n lockedScaCoin: BigNumber(dynamicFields.locked_sca_amount).shiftedBy(-9).toNumber(),\n unlockAt: BigNumber(dynamicFields.unlock_at).toNumber(),\n } as Vesca;\n }\n\n return vesca;\n};\n","import { SuiClient } from '@mysten/sui.js/client';\n\nimport { ScallopAddress } from './scallopAddress';\nimport { ScallopUtils } from './scallopUtils';\nimport { SUPPORT_SPOOLS } from '../constants';\nimport {\n getObligations,\n getStakeAccounts,\n getStakePool,\n getStakeRewardPool,\n getPythPrice,\n queryBorrowIncentiveAccounts,\n getCoinAmounts,\n getCoinAmount,\n getMarketCoinAmounts,\n getMarketCoinAmount,\n queryObligation,\n} from '../queries';\nimport {\n ScallopQueryParams,\n ScallopInstanceParams,\n SupportStakeMarketCoins,\n SupportAssetCoins,\n SupportMarketCoins,\n StakePools,\n StakeRewardPools,\n SupportBorrowIncentiveCoins,\n SuiAddressArg,\n} from '../types';\n\n/**\n * @description\n * It provides methods for getting on-chain data from the Scallop contract.\n *\n * @example\n * ```typescript\n * const scallopQuery = new ScallopQuery(<parameters>);\n * await scallopQuery.init();\n * scallopQuery.<query functions>();\n * await scallopQuery.<query functions>();\n * ```\n */\nexport class ScallopQuery {\n public readonly params: ScallopQueryParams;\n\n public address: ScallopAddress;\n\n public client: SuiClient;\n\n public utils: ScallopUtils;\n\n public constructor(params: ScallopQueryParams, instance?: Omit<ScallopInstanceParams, 'query' | 'builder'>) {\n this.params = params;\n this.client = params.client;\n\n const { address, utils } = instance;\n this.address = address;\n this.utils = utils;\n }\n\n /* ==================== Core Query Methods ==================== */\n /**\n * Get obligations data.\n *\n * @param ownerAddress - The owner address.\n * @return Obligations data.\n */\n public async getObligations(ownerAddress: string = this.params.walletAddress) {\n return getObligations(this, ownerAddress);\n }\n\n /**\n * Get all asset coin amounts.\n *\n * @param assetCoinNames - Specific an array of support asset coin name.\n * @param ownerAddress - The owner address.\n * @return All coin amounts.\n */\n public async getCoinAmounts(ownerAddress: string, assetCoinNames?: SupportAssetCoins[]) {\n return getCoinAmounts(this, ownerAddress, assetCoinNames);\n }\n\n /**\n * Get asset coin amount.\n *\n * @param assetCoinName - Specific support asset coin name.\n * @param ownerAddress - The owner address.\n * @return Coin amount.\n */\n public async getCoinAmount(assetCoinName: SupportAssetCoins, ownerAddress: string = this.params.walletAddress) {\n return getCoinAmount(this, assetCoinName, ownerAddress);\n }\n\n /**\n * Get all market coin amounts.\n *\n * @param coinNames - Specific an array of support market coin name.\n * @param ownerAddress - The owner address.\n * @return All market market coin amounts.\n */\n public async getMarketCoinAmounts(ownerAddress: string, marketCoinNames?: SupportMarketCoins[]) {\n return getMarketCoinAmounts(this, ownerAddress, marketCoinNames);\n }\n\n /**\n * Get market coin amount.\n *\n * @param coinNames - Specific support market coin name.\n * @param ownerAddress - The owner address.\n * @return Market market coin amount.\n */\n public async getMarketCoinAmount(\n marketCoinName: SupportMarketCoins,\n ownerAddress: string = this.params.walletAddress,\n ) {\n return getMarketCoinAmount(this, marketCoinName, ownerAddress);\n }\n\n /**\n * Get price from pyth fee object.\n *\n * @param assetCoinName - Specific support asset coin name.\n * @return Asset coin price.\n */\n public async getPriceFromPyth(assetCoinName: SupportAssetCoins) {\n return getPythPrice(this, assetCoinName);\n }\n\n /* ==================== Spool Query Methods ==================== */\n\n /**\n * Get stake accounts data for all stake pools (spools).\n *\n * @param ownerAddress - The owner address.\n * @return All Stake accounts data.\n */\n public async getAllStakeAccounts(ownerAddress: string = this.params.walletAddress) {\n return getStakeAccounts(this, ownerAddress);\n }\n\n /**\n * Get stake accounts data for specific stake pool (spool).\n *\n * @param stakeMarketCoinName - Specific support stake market coin name.\n * @param ownerAddress - The owner address.\n * @return Stake accounts data.\n */\n public async getStakeAccounts(\n stakeMarketCoinName: SupportStakeMarketCoins,\n ownerAddress: string = this.params.walletAddress,\n ) {\n const allStakeAccount = await this.getAllStakeAccounts(ownerAddress);\n return allStakeAccount[stakeMarketCoinName] ?? [];\n }\n\n /**\n * Get stake pools (spools) data.\n *\n * @description\n * For backward compatible, it is recommended to use `getSpools` method\n * to get all spools data.\n *\n * @param stakeMarketCoinNames - Specific an array of support stake market coin name.\n * @return Stake pools data.\n */\n public async getStakePools(stakeMarketCoinNames: SupportStakeMarketCoins[] = [...SUPPORT_SPOOLS]) {\n const stakePools: StakePools = {};\n for (let i = 0; i < stakeMarketCoinNames.length; i++) {\n const stakeMarketCoinName = stakeMarketCoinNames[i];\n const stakePool = await getStakePool(this, stakeMarketCoinName);\n\n if (stakePool) {\n stakePools[stakeMarketCoinName] = stakePool;\n }\n }\n return stakePools;\n }\n\n /**\n * Get stake pool (spool) data.\n *\n * @description\n * For backward compatible, it is recommended to use `getSpool` method\n * to get all spool data.\n *\n * @param stakeMarketCoinName - Specific support stake market coin name.\n * @return Stake pool data.\n */\n public async getStakePool(stakeMarketCoinName: SupportStakeMarketCoins) {\n return getStakePool(this, stakeMarketCoinName);\n }\n\n /**\n * Get stake reward pools data.\n *\n * @description\n * For backward compatible, it is recommended to use `getSpools` method\n * to get all spools data.\n *\n * @param stakeMarketCoinNames - Specific an array of stake market coin name.\n * @return Stake reward pools data.\n */\n public async getStakeRewardPools(stakeMarketCoinNames: SupportStakeMarketCoins[] = [...SUPPORT_SPOOLS]) {\n const stakeRewardPools: StakeRewardPools = {};\n for (let i = 0; i < stakeMarketCoinNames.length; i++) {\n const stakeRewardPool = await getStakeRewardPool(this, stakeMarketCoinNames[i]);\n\n if (stakeRewardPool) {\n stakeRewardPools[stakeMarketCoinNames[i]] = stakeRewardPool;\n }\n }\n return stakeRewardPools;\n }\n\n /**\n * Get stake reward pool data.\n *\n * @description\n * For backward compatible, it is recommended to use `getSpool` method\n * to get spool data.\n *\n * @param marketCoinName - Specific support stake market coin name.\n * @return Stake reward pool data.\n */\n public async getStakeRewardPool(stakeMarketCoinName: SupportStakeMarketCoins) {\n return getStakeRewardPool(this, stakeMarketCoinName);\n }\n\n /**\n * Get borrow incentive accounts data.\n *\n * @param coinNames - Specific support borrow incentive coin name.\n * @param ownerAddress - The owner address.\n * @return Borrow incentive accounts data.\n */\n public async getBorrowIncentiveAccounts(\n obligationId: string,\n walletAddress: string = this.params.walletAddress,\n coinNames?: SupportBorrowIncentiveCoins[],\n ) {\n return queryBorrowIncentiveAccounts(this, obligationId, walletAddress, coinNames);\n }\n\n /**\n * Get all asset coin names in the obligation record by obligation id.\n *\n * @description\n * This can often be used to determine which assets in an obligation require\n * price updates before interacting with specific instructions of the Scallop contract.\n *\n * @param obligationId - The obligation id.\n * @return Asset coin Names.\n */\n public async getObligationCoinNames(obligationId: SuiAddressArg) {\n const obligation = await queryObligation(this, obligationId);\n const collateralCoinTypes = obligation.collaterals.map((collateral) => `0x${collateral.type.name}`);\n const debtCoinTypes = obligation.debts.map((debt) => `0x${debt.type.name}`);\n const obligationCoinTypes = [...new Set([...collateralCoinTypes, ...debtCoinTypes])];\n const obligationCoinNames = obligationCoinTypes.map((coinType) => this.utils.parseCoinNameFromType(coinType));\n return obligationCoinNames;\n }\n}\n","import { SuiClient } from '@mysten/sui.js/client';\nimport { TransactionBlock } from '@mysten/sui.js/transactions';\nimport { SUI_TYPE_ARG, normalizeStructTag } from '@mysten/sui.js/utils';\n\nimport { ScallopAddress } from './scallopAddress';\nimport {\n PROTOCOL_OBJECT_ID,\n spoolRewardCoins,\n borrowIncentiveRewardCoins,\n coinDecimals,\n wormholeCoinIds,\n voloCoinIds,\n coinIds,\n UNLOCK_ROUND_DURATION,\n MAX_LOCK_DURATION,\n sCoinIds,\n SUPPORT_SCOIN,\n} from '../constants';\nimport type {\n ScallopUtilsParams,\n SupportCoins,\n SupportAssetCoins,\n SupportMarketCoins,\n SupportStakeMarketCoins,\n SupportBorrowIncentiveCoins,\n CoinWrappedType,\n SupportPoolCoins,\n SuiTxArg,\n SupportSCoin,\n} from '../types';\nimport { findClosestUnlockRound, isMarketCoin, parseAssetSymbol } from '../utils';\n\n/**\n * @description\n * Integrates some helper functions frequently used in interactions with the Scallop contract.\n *\n * @example\n * ```typescript\n * const scallopUtils = new ScallopUtils(<parameters>);\n * await scallopUtils.init();\n * scallopUtils.<utils functions>();\n * await scallopUtils.<utils functions>();\n * ```\n */\nexport class ScallopUtils {\n public readonly params: ScallopUtilsParams;\n\n public readonly isTestnet: boolean;\n\n private _address: ScallopAddress;\n\n public client: SuiClient;\n\n public constructor(params: ScallopUtilsParams, address: ScallopAddress) {\n this.params = params;\n this.client = params.client;\n\n this._address = address;\n }\n\n /**\n * Convert coin name to symbol.\n *\n * @param coinName - Specific support coin name.\n * @return Symbol string.\n */\n public parseSymbol(coinName: SupportCoins) {\n if (isMarketCoin(coinName)) {\n const assetCoinName = coinName.slice(1).toLowerCase() as SupportAssetCoins;\n return coinName.slice(0, 1).toLowerCase() + parseAssetSymbol(assetCoinName);\n }\n return parseAssetSymbol(coinName);\n }\n\n /**\n * Convert coin name to coin type.\n *\n * @description\n * The Coin type of wormhole is fixed `coin:Coin`. Here using package id\n * to determine and return the type.\n *\n * @param coinPackageId - Package id of coin.\n * @param coinName - Specific support coin name.\n * @return Coin type.\n */\n public parseCoinType(coinName: SupportCoins) {\n const validCoinName = isMarketCoin(coinName) ? this.parseCoinName(coinName) : coinName;\n const coinPackageId = coinIds[validCoinName as SupportPoolCoins];\n const wormHolePackageIds = [\n wormholeCoinIds.wusdc,\n wormholeCoinIds.wusdt,\n wormholeCoinIds.weth,\n wormholeCoinIds.wbtc,\n wormholeCoinIds.wsol,\n wormholeCoinIds.wapt,\n ];\n if (wormHolePackageIds.includes(coinPackageId)) {\n return `${coinPackageId}::coin::COIN`;\n }\n if (coinName === 'vsui') {\n return `${voloCoinIds.vsui}::cert::CERT`;\n }\n return `${coinPackageId}::${validCoinName}::${validCoinName.toUpperCase()}`;\n }\n\n /**\n * Convert coin name to market coin type.\n *\n * @param coinPackageId - Package id of coin.\n * @param coinName - Specific support coin name.\n * @return Market coin type.\n */\n public parseMarketCoinType(coinName: SupportCoins) {\n const protocolObjectId = this._address.get('core.object') || PROTOCOL_OBJECT_ID;\n const coinType = this.parseCoinType(coinName);\n return `${protocolObjectId}::reserve::MarketCoin<${coinType}>`;\n }\n\n /**\n * Convert coin type to coin name.\n *\n * @description\n * The coin name cannot be obtained directly from the wormhole type. Here\n * the package id is used to determine and return a specific name.\n *\n * @param coinType - Specific support coin type.\n * @return Coin Name.\n */\n public parseCoinNameFromType<T extends SupportAssetCoins>(\n coinType: string,\n ): T extends SupportAssetCoins ? T : SupportAssetCoins;\n public parseCoinNameFromType<T extends SupportMarketCoins>(\n coinType: string,\n ): T extends SupportMarketCoins ? T : SupportMarketCoins;\n public parseCoinNameFromType<T extends SupportCoins>(coinType: string): T extends SupportCoins ? T : SupportCoins;\n public parseCoinNameFromType(coinType: string) {\n let type = normalizeStructTag(coinType);\n const coinTypeRegex = /((0x[^:]+::[^:]+::[^<>]+))(?![^<>]*<)/;\n const coinTypeMatch = coinType.match(coinTypeRegex);\n const isMarketCoinType = coinType.includes('reserve::MarketCoin');\n type = coinTypeMatch?.[1] || coinType;\n\n const wormHoleCoinTypeMap: Record<string, SupportAssetCoins> = {\n [`${wormholeCoinIds.wusdc}::coin::COIN`]: 'wusdc',\n [`${wormholeCoinIds.wusdt}::coin::COIN`]: 'wusdt',\n [`${wormholeCoinIds.weth}::coin::COIN`]: 'weth',\n [`${wormholeCoinIds.wbtc}::coin::COIN`]: 'wbtc',\n [`${wormholeCoinIds.wsol}::coin::COIN`]: 'wsol',\n [`${wormholeCoinIds.wapt}::coin::COIN`]: 'wapt',\n };\n const voloCoinTypeMap: Record<string, SupportAssetCoins> = {\n [`${voloCoinIds.vsui}::cert::CERT`]: 'vsui',\n };\n\n const assetCoinName =\n wormHoleCoinTypeMap[type] || voloCoinTypeMap[type] || (type.split('::')[2].toLowerCase() as SupportAssetCoins);\n\n return isMarketCoinType ? this.parseMarketCoinName(assetCoinName) : assetCoinName;\n }\n\n /**\n * Convert marke coin name to coin name.\n *\n * @param marketCoinName - Specific support market coin name.\n * @return Coin Name.\n */\n public parseCoinName<T extends SupportAssetCoins>(marketCoinName: string) {\n return marketCoinName.slice(1) as T;\n }\n\n /**\n * Convert coin name to market coin name.\n *\n * @param coinName - Specific support coin name.\n * @return Market coin name.\n */\n public parseMarketCoinName<T extends SupportMarketCoins>(coinName: SupportCoins) {\n return `s${coinName}` as T;\n }\n\n /**\n * Get reward type of spool.\n *\n * @param stakeMarketCoinName - Support stake market coin.\n * @return Spool reward coin name.\n */\n public getSpoolRewardCoinName = (stakeMarketCoinName: SupportStakeMarketCoins) =>\n spoolRewardCoins[stakeMarketCoinName];\n\n /**\n * Get reward type of borrow incentive pool.\n *\n * @param borrowIncentiveCoinName - Support borrow incentive coin.\n * @return Borrow incentive reward coin name.\n */\n public getBorrowIncentiveRewardCoinName = (borrowIncentiveCoinName: SupportBorrowIncentiveCoins) =>\n borrowIncentiveRewardCoins[borrowIncentiveCoinName];\n\n /**\n * Get coin decimal.\n *\n * return Coin decimal.\n */\n public getCoinDecimal(coinName: SupportCoins) {\n return coinDecimals[coinName];\n }\n\n /**\n * Get coin wrapped type.\n *\n * return Coin wrapped type.\n */\n public getCoinWrappedType(assetCoinName: SupportAssetCoins): CoinWrappedType {\n return assetCoinName === 'wusdc' ||\n assetCoinName === 'wusdt' ||\n assetCoinName === 'weth' ||\n assetCoinName === 'wbtc' ||\n assetCoinName === 'wapt' ||\n assetCoinName === 'wsol'\n ? {\n from: 'Wormhole',\n type: 'Portal from Ethereum',\n }\n : undefined;\n }\n\n /**\n * Convert sCoin name into sCoin type\n * @param sCoinName\n * @returns sCoin type\n */\n public parseSCoinType(sCoinName: SupportSCoin) {\n return sCoinIds[sCoinName];\n }\n\n /**\n * Convert sCoin name into its underlying coin type\n * @param sCoinName\n * @returns coin type\n */\n public parseUnderlyingSCoinType(sCoinName: SupportSCoin) {\n const coinName = this.parseCoinName(sCoinName);\n return this.parseCoinType(coinName);\n }\n\n /**\n * Get sCoin treasury id from sCoin name\n * @param sCoinName\n * @returns sCoin treasury id\n */\n public getSCoinTreasury(sCoinName: SupportSCoin) {\n return this._address.get(`scoin.coins.${sCoinName}.treasury`);\n }\n\n /**\n * Select coin id that add up to the given amount as transaction arguments.\n *\n * @param ownerAddress - The address of the owner.\n * @param amount - The amount that including coin decimals.\n * @param coinType - The coin type, default is 0x2::SUI::SUI.\n * @return The selected transaction coin arguments.\n */\n public async selectCoins(amount: number, coinType: string = SUI_TYPE_ARG, ownerAddress?: string) {\n const address = ownerAddress;\n\n const selectedCoins: {\n objectId: string;\n digest: string;\n version: string;\n balance: string;\n }[] = [];\n let totalAmount = 0;\n let hasNext = true;\n let nextCursor: string | null | undefined = null;\n while (hasNext && totalAmount < amount) {\n const coins = await this.client.getCoins({\n owner: address,\n coinType,\n cursor: nextCursor,\n });\n // Sort the coins by balance in descending order\n coins.data.sort((a, b) => parseInt(b.balance, 10) - parseInt(a.balance, 10));\n for (let i = 0; i < coins.data.length; i++) {\n selectedCoins.push({\n objectId: coins.data[i].coinObjectId,\n digest: coins.data[i].digest,\n version: coins.data[i].version,\n balance: coins.data[i].balance,\n });\n totalAmount += parseInt(coins.data[i].balance, 10);\n if (totalAmount >= amount) {\n break;\n }\n }\n nextCursor = coins.nextCursor;\n hasNext = coins.hasNextPage;\n }\n\n if (!selectedCoins.length) {\n throw new Error('No valid coins found for the transaction.');\n }\n return selectedCoins;\n }\n\n /**\n * Select coin id that add up to the given amount as transaction arguments.\n *\n * @param ownerAddress - The address of the owner.\n * @param amount - The amount that including coin decimals.\n * @param coinType - The coin type, default is 0x2::SUI::SUI.\n * @return The selected transaction coin arguments.\n */\n public async selectCoinsMarketCoin(coinType: string = SUI_TYPE_ARG, ownerAddress?: string) {\n const address = ownerAddress;\n\n const selectedCoins: {\n objectId: string;\n digest: string;\n version: string;\n balance: string;\n }[] = [];\n let hasNext = true;\n let nextCursor: string | null | undefined = null;\n while (hasNext) {\n const coins = await this.client.getCoins({\n owner: address,\n coinType,\n cursor: nextCursor,\n });\n // Sort the coins by balance in descending order\n coins.data.sort((a, b) => parseInt(b.balance, 10) - parseInt(a.balance, 10));\n for (let i = 0; i < coins.data.length; i++) {\n selectedCoins.push({\n objectId: coins.data[i].coinObjectId,\n digest: coins.data[i].digest,\n version: coins.data[i].version,\n balance: coins.data[i].balance,\n });\n if (selectedCoins.length > 50) {\n break;\n }\n }\n nextCursor = coins.nextCursor;\n hasNext = coins.hasNextPage;\n }\n\n return selectedCoins;\n }\n\n public async selectCoinIds(amount: number, coinType: string = SUI_TYPE_ARG, ownerAddress?: string) {\n const selectedCoins = await this.selectCoins(amount, coinType, ownerAddress);\n return selectedCoins.map((coin) => coin.objectId);\n }\n\n /**\n * Convert apr to apy.\n *\n * @param apr The annual percentage rate (APR).\n * @param compoundFrequency How often interest is compounded per year. Default is daily (365 times a year).\n * @return The equivalent annual percentage yield (APY) for the given APR and compounding frequency.\n */\n public parseAprToApy(apr: number, compoundFrequency = 365) {\n return (1 + apr / compoundFrequency) ** compoundFrequency - 1;\n }\n\n /**\n * Convert apr to apy.\n *\n * @param apr The equivalent annual percentage yield (APY).\n * @param compoundFrequency How often interest is compounded per year. Default is daily (365 times a year).\n * @return The equivalent annual percentage rate (APR) for the given APY and compounding frequency.\n */\n public parseApyToApr(apy: number, compoundFrequency = 365) {\n return ((1 + apy) ** (1 / compoundFrequency) - 1) * compoundFrequency;\n }\n\n public takeAmountFromCoins(txBlock: TransactionBlock, coinObjectId: string[], amount: SuiTxArg) {\n const coinObjects = coinObjectId.map((objectId) => txBlock.object(objectId));\n const mergedCoin = coinObjects[0];\n if (coinObjects.length > 1) {\n txBlock.mergeCoins(mergedCoin, coinObjects.slice(1));\n }\n const [sendCoin] = txBlock.splitCoins(mergedCoin, [txBlock.pure(amount)]);\n return [sendCoin, mergedCoin];\n }\n\n /**\n * Give extend lock period to get unlock at in seconds timestamp.\n *\n * @description\n * - When the user without remaining unlock period, If the extended unlock day is not specified,\n * the unlock period will be increased by one day by default.\n * - When the given extended day plus the user's remaining unlock period exceeds the maximum\n * unlock period, the maximum unlock period is used as unlock period.\n *\n * @param extendLockPeriodInDay The extend lock period in day.\n * @param unlockAtInSecondTimestamp The unlock timestamp from veSca object.\n * @return New unlock at in seconds timestamp.\n */\n public getUnlockAt(extendLockPeriodInDay?: number, unlockAtInSecondTimestamp?: number) {\n const now = Math.floor(new Date().getTime() / 1000);\n const remainingLockPeriod = unlockAtInSecondTimestamp ? Math.max(unlockAtInSecondTimestamp - now, 0) : 0;\n\n let newUnlockAtInSecondTimestamp = 0;\n\n if (remainingLockPeriod === 0) {\n const lockPeriod = (extendLockPeriodInDay ?? 1) * UNLOCK_ROUND_DURATION;\n newUnlockAtInSecondTimestamp = Math.min(now + lockPeriod, now + MAX_LOCK_DURATION);\n } else {\n const lockPeriod = Math.min(\n extendLockPeriodInDay\n ? extendLockPeriodInDay * UNLOCK_ROUND_DURATION + remainingLockPeriod\n : remainingLockPeriod,\n MAX_LOCK_DURATION,\n );\n newUnlockAtInSecondTimestamp = now + lockPeriod;\n }\n return findClosestUnlockRound(newUnlockAtInSecondTimestamp);\n }\n\n /**\n * Convert coin name to sCoin name.\n *\n * @param coinName - Specific support coin name.\n * @return sCoin name.\n */\n public parseSCoinName<T extends SupportSCoin>(coinName: SupportCoins | SupportMarketCoins) {\n // need more check because sbtc, ssol and sapt has no sCoin type\n if (isMarketCoin(coinName) && SUPPORT_SCOIN.includes(coinName as SupportSCoin)) {\n return coinName as T;\n }\n const marketCoinName = `s${coinName}`;\n if (SUPPORT_SCOIN.includes(marketCoinName as SupportSCoin)) {\n return marketCoinName as T;\n }\n return undefined;\n }\n}\n","import { TransactionBlock } from '@mysten/sui.js/transactions';\nimport { SUI_CLOCK_OBJECT_ID, SUI_TYPE_ARG } from '@mysten/sui.js/utils';\n\nimport { OLD_BORROW_INCENTIVE_PROTOCOL_ID } from '../constants';\nimport type { ScallopBuilder } from '../models';\nimport { getObligations, getObligationLocked, getVeSca, getVeScas, getBindedVeScaKey } from '../queries';\nimport type {\n BorrowIncentiveIds,\n GenerateBorrowIncentiveNormalMethod,\n GenerateBorrowIncentiveQuickMethod,\n VescaIds,\n SuiAddressArg,\n} from '../types';\nimport { requireSender } from '../utils';\n\n/**\n * Check and get veSCA data from transaction block.\n *\n * @description\n * If the veScaKey id is provided, directly return it.\n * Otherwise, automatically get veScaKey from the sender.\n *\n * @param builder - Scallop builder instance.\n * @param txBlock - TxBlock created by SuiKit.\n * @param veScaKey - veSCA key.\n * @return veSCA key, ID, locked amount and unlock at timestamp.\n */\n\nexport const requireVeSca = async (\n ...params: [builder: ScallopBuilder, SuiTxBlock: TransactionBlock, veScaKey?: SuiAddressArg]\n) => {\n const [builder, txBlock, veScaKey] = params;\n if (params.length === 3 && veScaKey && typeof veScaKey === 'string') {\n const veSca = await getVeSca(builder.query, veScaKey);\n\n if (!veSca) {\n return undefined;\n }\n\n return veSca;\n }\n\n const sender = requireSender(txBlock);\n const veScas = await getVeScas(builder.query, sender);\n if (veScas.length === 0) {\n return undefined;\n }\n\n return veScas[0];\n};\n\n/**\n * Check veSca bind status\n * @param query\n * @param veScaKey\n * @returns\n */\nexport const getBindedObligationId = async (builder: ScallopBuilder, veScaKey: string) => {\n const borrowIncentiveObjId = builder.address.get('borrowIncentive.object');\n const incentivePoolsId = builder.address.get('borrowIncentive.incentivePools');\n const veScaPkgId = builder.address.get('vesca.id');\n\n const { client } = builder;\n\n // get incentive pools\n const incentivePoolsResponse = await client.getObject({\n id: incentivePoolsId,\n options: {\n showContent: true,\n },\n });\n\n if (incentivePoolsResponse.data?.content?.dataType !== 'moveObject') {\n return false;\n }\n const incentivePoolFields = incentivePoolsResponse.data.content.fields as any;\n const veScaBindTableId = incentivePoolFields.ve_sca_bind.fields.id.id as string;\n\n // check if veSca is inside the bind table\n const keyType = `${borrowIncentiveObjId}::typed_id::TypedID<${veScaPkgId}::ve_sca::VeScaKey>`;\n const veScaBindTableResponse = await client.getDynamicFieldObject({\n parentId: veScaBindTableId,\n name: {\n type: keyType,\n value: veScaKey,\n },\n });\n\n if (veScaBindTableResponse.data?.content?.dataType !== 'moveObject') {\n return false;\n }\n const veScaBindTableFields = veScaBindTableResponse.data.content.fields as any;\n // get obligationId pair\n const obligationId = veScaBindTableFields.value.fields.id as string;\n\n return obligationId;\n};\n\n/**\n * Check and get Obligation information from transaction block.\n *\n * @description\n * If the obligation id is provided, direactly return it.\n * If both obligation id and key is provided, direactly return them.\n * Otherwise, automatically get obligation id and key from the sender.\n *\n * @param builder - Scallop builder instance.\n * @param txBlock - TxBlock created by SuiKit.\n * @param obligationId - Obligation id.\n * @param obligationKey - Obligation key.\n * @return Obligation id and key.\n */\nconst requireObligationInfo = async (\n ...params: [builder: ScallopBuilder, txBlock: TransactionBlock, obligationId?: string, obligationKey?: string]\n) => {\n const [builder, txBlock, obligationId, obligationKey] = params;\n if (params.length === 4 && obligationId && obligationKey && typeof obligationId === 'string') {\n const obligationLocked = await getObligationLocked(builder.query, obligationId);\n return { obligationId, obligationKey, obligationLocked };\n }\n const sender = requireSender(txBlock);\n const obligations = await getObligations(builder.query, sender);\n if (obligations.length === 0) {\n throw new Error(`No obligation found for sender ${sender}`);\n }\n const selectedObligation =\n obligations.find((obligation) => obligation.id === obligationId || obligation.keyId === obligationKey) ??\n obligations[0];\n\n return {\n obligationId: selectedObligation.id,\n obligationKey: selectedObligation.keyId,\n obligationLocked: selectedObligation.locked,\n };\n};\n\n/**\n * Generate borrow incentive normal methods.\n *\n * @param builder - Scallop builder instance.\n * @param txBlock - TxBlock created by SuiKit .\n * @return Borrow incentive normal methods.\n */\nexport const generateBorrowIncentiveNormalMethod: GenerateBorrowIncentiveNormalMethod = async ({\n builder,\n txBlock,\n}) => {\n const borrowIncentiveIds: BorrowIncentiveIds = {\n borrowIncentivePkg: builder.address.get('borrowIncentive.id'),\n query: builder.address.get('borrowIncentive.query'),\n incentivePools: builder.address.get('borrowIncentive.incentivePools'),\n incentiveAccounts: builder.address.get('borrowIncentive.incentiveAccounts'),\n obligationAccessStore: builder.address.get('core.obligationAccessStore'),\n config: builder.address.get('borrowIncentive.config'),\n };\n const OldBorrowIncentiveContract = {\n id: '0xc63072e7f5f4983a2efaf5bdba1480d5e7d74d57948e1c7cc436f8e22cbeb410',\n incentivePools: '0x64972b713ccec45ec3964809e477cea6f97350c0c50ca3aec85bb631639266ec',\n incentiveAccounts: '0x3c0b707068bdcea8bb859d751ad3e2149a9f83c13fcf4054ef91372a00bccdd3',\n };\n const veScaIds: Omit<VescaIds, 'pkgId'> = {\n table: builder.address.get('vesca.table'),\n treasury: builder.address.get('vesca.treasury'),\n config: builder.address.get('vesca.config'),\n };\n\n return {\n stakeObligation: (obligationId, obligationKey) => {\n txBlock.moveCall({\n target: `${borrowIncentiveIds.borrowIncentivePkg}::user::stake`,\n arguments: [\n txBlock.object(borrowIncentiveIds.config),\n txBlock.object(borrowIncentiveIds.incentivePools),\n txBlock.object(borrowIncentiveIds.incentiveAccounts),\n txBlock.object(obligationKey as string),\n txBlock.object(obligationId as string),\n txBlock.object(borrowIncentiveIds.obligationAccessStore),\n txBlock.object(SUI_CLOCK_OBJECT_ID),\n ],\n });\n },\n stakeObligationWithVesca: (obligationId, obligationKey, veScaKey) => {\n txBlock.moveCall({\n target: `${borrowIncentiveIds.borrowIncentivePkg}::user::stake_with_ve_sca`,\n arguments: [\n txBlock.object(borrowIncentiveIds.config),\n txBlock.object(borrowIncentiveIds.incentivePools),\n txBlock.object(borrowIncentiveIds.incentiveAccounts),\n txBlock.object(obligationKey as string),\n txBlock.object(obligationId as string),\n txBlock.object(borrowIncentiveIds.obligationAccessStore),\n txBlock.object(veScaIds.config),\n txBlock.object(veScaIds.treasury),\n txBlock.object(veScaIds.table),\n txBlock.object(veScaKey as string),\n txBlock.object(SUI_CLOCK_OBJECT_ID),\n ],\n });\n },\n unstakeObligation: (obligationId, obligationKey) => {\n txBlock.moveCall({\n target: `${borrowIncentiveIds.borrowIncentivePkg}::user::unstake`,\n arguments: [\n txBlock.object(borrowIncentiveIds.config),\n txBlock.object(borrowIncentiveIds.incentivePools),\n txBlock.object(borrowIncentiveIds.incentiveAccounts),\n txBlock.object(obligationKey as string),\n txBlock.object(obligationId as string),\n txBlock.object(SUI_CLOCK_OBJECT_ID),\n ],\n });\n },\n oldUnstakeObligation: (obligationId, obligationKey) => {\n txBlock.moveCall({\n target: `${borrowIncentiveIds.borrowIncentivePkg}::user::unstake`,\n arguments: [\n txBlock.object(OldBorrowIncentiveContract.incentivePools),\n txBlock.object(OldBorrowIncentiveContract.incentiveAccounts),\n txBlock.object(obligationKey as string),\n txBlock.object(obligationId as string),\n txBlock.object(SUI_CLOCK_OBJECT_ID),\n ],\n typeArguments: [SUI_TYPE_ARG],\n });\n },\n claimBorrowIncentive: (obligationId, obligationKey, rewardCoinName) => {\n const rewardType = builder.utils.parseCoinType(rewardCoinName);\n return txBlock.moveCall({\n target: `${borrowIncentiveIds.borrowIncentivePkg}::user::redeem_rewards`,\n arguments: [\n txBlock.object(borrowIncentiveIds.config),\n txBlock.object(borrowIncentiveIds.incentivePools),\n txBlock.object(borrowIncentiveIds.incentiveAccounts),\n txBlock.object(obligationKey as string),\n txBlock.object(obligationId as string),\n txBlock.object(SUI_CLOCK_OBJECT_ID),\n ],\n typeArguments: [rewardType],\n });\n },\n oldClaimBorrowIncentive(obligationId, obligationKey, rewardCoinName) {\n const rewardType = builder.utils.parseCoinType(rewardCoinName);\n return txBlock.moveCall({\n target: `${OldBorrowIncentiveContract.id}::user::redeem_rewards`,\n arguments: [\n txBlock.object(OldBorrowIncentiveContract.incentivePools),\n txBlock.object(OldBorrowIncentiveContract.incentiveAccounts),\n txBlock.object(obligationKey as string),\n txBlock.object(obligationId as string),\n txBlock.object(SUI_CLOCK_OBJECT_ID),\n ],\n typeArguments: [rewardType],\n });\n },\n };\n};\n\n/**\n * Generate spool quick methods.\n *\n * @description\n * The quick methods are the same as the normal methods, but they will automatically\n * help users organize transaction blocks, include get stake account info, and transfer\n * coins to the sender. So, they are all asynchronous methods.\n *\n * @param builder - Scallop builder instance.\n * @param txBlock - TxBlock created by SuiKit .\n * @return Spool quick methods.\n */\nexport const generateBorrowIncentiveQuickMethod: GenerateBorrowIncentiveQuickMethod = async ({ builder, txBlock }) => {\n const normalMethod = await generateBorrowIncentiveNormalMethod({ builder, txBlock });\n return {\n normalMethod,\n stakeObligationQuick: async (obligation, obligationKey) => {\n const {\n obligationId: obligationArg,\n obligationKey: obligationtKeyArg,\n obligationLocked,\n } = await requireObligationInfo(builder, txBlock, obligation as string, obligationKey as string);\n\n const unstakeObligationBeforeStake = !!txBlock.blockData.transactions.find(\n (txn) =>\n txn.kind === 'MoveCall' &&\n (txn.target === `${OLD_BORROW_INCENTIVE_PROTOCOL_ID}::user::unstake` ||\n txn.target === `${builder.address.get('borrowIncentive.id')}::user::unstake`),\n );\n\n if (!obligationLocked || unstakeObligationBeforeStake) {\n normalMethod.stakeObligation(obligationArg, obligationtKeyArg);\n }\n },\n unstakeObligationQuick: async (obligation, obligationKey) => {\n const {\n obligationId: obligationArg,\n obligationKey: obligationtKeyArg,\n obligationLocked,\n } = await requireObligationInfo(builder, txBlock, obligation as string, obligationKey as string);\n\n if (obligationLocked) {\n normalMethod.unstakeObligation(obligationArg, obligationtKeyArg);\n }\n },\n stakeObligationWithVeScaQuick: async (obligation, obligationKey, veScaKey) => {\n const {\n obligationId: obligationArg,\n obligationKey: obligationtKeyArg,\n obligationLocked,\n } = await requireObligationInfo(builder, txBlock, obligation as string, obligationKey as string);\n\n const unstakeObligationBeforeStake = !!txBlock.blockData.transactions.find(\n async (txn) =>\n txn.kind === 'MoveCall' &&\n (txn.target === `${OLD_BORROW_INCENTIVE_PROTOCOL_ID}::user::unstake` ||\n txn.target === `${builder.address.get('borrowIncentive.id')}::user::unstake`),\n );\n\n if (!obligationLocked || unstakeObligationBeforeStake) {\n const bindedVeScaKey = await getBindedVeScaKey(\n { address: builder.address, client: builder.client },\n obligationArg,\n );\n if (veScaKey && veScaKey !== bindedVeScaKey) {\n throw new Error('Binded veScaKey is not equal to the provided veScaKey');\n }\n if (bindedVeScaKey) {\n normalMethod.stakeObligationWithVesca(obligationArg, obligationtKeyArg, bindedVeScaKey);\n } else {\n normalMethod.stakeObligation(obligationArg, obligationtKeyArg);\n }\n }\n },\n claimBorrowIncentiveQuick: (rewardCoinName, obligation, obligationKey) =>\n normalMethod.claimBorrowIncentive(obligation, obligationKey, rewardCoinName),\n };\n};\n","import { TransactionArgument, TransactionBlock } from '@mysten/sui.js/transactions';\nimport { SUI_CLOCK_OBJECT_ID } from '@mysten/sui.js/utils';\n\nimport { updateOracles } from './oracle';\nimport { generateSCoinNormalMethod } from './sCoinBuilder';\nimport type { ScallopBuilder } from '../models';\nimport { getObligations } from '../queries';\nimport type {\n CoreIds,\n GenerateCoreNormalMethod,\n ScallopTxBlock,\n GenerateCoreQuickMethod,\n SuiAddressArg,\n} from '../types';\nimport { requireSender } from '../utils';\n\n/**\n * Check and get Obligation information from transaction block.\n *\n * @description\n * If the obligation id is provided, direactly return it.\n * If both obligation id and key is provided, direactly return them.\n * Otherwise, automatically get obligation id and key from the sender.\n *\n * @param builder - Scallop builder instance.\n * @param txBlock - TxBlock created by SuiKit.\n * @param obligationId - Obligation id.\n * @param obligationKey - Obligation key.\n * @return Obligation id and key.\n */\nconst requireObligationInfo = async (\n ...params: [\n txBlock: TransactionBlock,\n builder: ScallopBuilder,\n obligationId?: SuiAddressArg,\n obligationKey?: SuiAddressArg,\n ]\n) => {\n const [txBlock, builder, obligationId, obligationKey] = params;\n if (params.length === 3 && obligationId) {\n return { obligationId };\n }\n if (params.length === 4 && obligationId && obligationKey) {\n return { obligationId, obligationKey };\n }\n const sender = requireSender(txBlock);\n const obligations = await getObligations(builder.query, sender);\n if (obligations.length === 0) {\n throw new Error(`No obligation found for sender ${sender}`);\n }\n return {\n obligationId: obligations[0].id,\n obligationKey: obligations[0].keyId,\n };\n};\n\n/**\n * Generate core normal methods.\n *\n * @param builder - Scallop builder instance.\n * @param txBlock - TxBlock created by SuiKit.\n * @return Core normal methods.\n */\nexport const generateCoreNormalMethod: GenerateCoreNormalMethod = async ({ builder, txBlock }) => {\n const coreIds: CoreIds = {\n protocolPkg: builder.address.get('core.packages.protocol.id'),\n market: builder.address.get('core.market'),\n version: builder.address.get('core.version'),\n coinDecimalsRegistry: builder.address.get('core.coinDecimalsRegistry'),\n xOracle: builder.address.get('core.oracles.xOracle'),\n };\n\n const referralPkgId = builder.address.get('referral.id');\n const referralWitnessType = `${referralPkgId}::scallop_referral_program::REFERRAL_WITNESS`;\n\n return {\n openObligation: () =>\n txBlock.moveCall({\n target: `${coreIds.protocolPkg}::open_obligation::open_obligation`,\n arguments: [txBlock.object(coreIds.version)],\n }),\n returnObligation: (obligation, obligationHotPotato) =>\n txBlock.moveCall({\n target: `${coreIds.protocolPkg}::open_obligation::return_obligation`,\n arguments: [\n txBlock.object(coreIds.version),\n txBlock.object(obligation as string),\n txBlock.object(obligationHotPotato as string),\n ],\n }),\n openObligationEntry: () =>\n txBlock.moveCall({\n target: `${coreIds.protocolPkg}::open_obligation::open_obligation_entry`,\n arguments: [txBlock.object(coreIds.version)],\n }),\n addCollateral: (obligation, coin, collateralCoinName) => {\n const coinType = builder.utils.parseCoinType(collateralCoinName);\n return txBlock.moveCall({\n target: `${coreIds.protocolPkg}::deposit_collateral::deposit_collateral`,\n arguments: [\n txBlock.object(coreIds.version),\n txBlock.object(obligation as string),\n txBlock.object(coreIds.market),\n typeof coin !== 'string' ? (coin as TransactionArgument) : txBlock.pure(coin),\n ],\n typeArguments: [coinType],\n });\n },\n takeCollateral: (obligation, obligationKey, amount, collateralCoinName) => {\n const coinType = builder.utils.parseCoinType(collateralCoinName);\n return txBlock.moveCall({\n target: `${coreIds.protocolPkg}::withdraw_collateral::withdraw_collateral`,\n arguments: [\n txBlock.object(coreIds.version),\n txBlock.object(obligation as string),\n txBlock.object(obligationKey as string),\n txBlock.object(coreIds.market),\n txBlock.object(coreIds.coinDecimalsRegistry),\n txBlock.pure(amount),\n txBlock.object(coreIds.xOracle),\n txBlock.object(SUI_CLOCK_OBJECT_ID),\n ],\n typeArguments: [coinType],\n });\n },\n deposit: (coin, poolCoinName) => {\n const coinType = builder.utils.parseCoinType(poolCoinName);\n return txBlock.moveCall({\n target: `${coreIds.protocolPkg}::mint::mint`,\n arguments: [\n txBlock.object(coreIds.version),\n txBlock.object(coreIds.market),\n typeof coin !== 'string' ? (coin as TransactionArgument) : txBlock.pure(coin),\n txBlock.object(SUI_CLOCK_OBJECT_ID),\n ],\n typeArguments: [coinType],\n });\n },\n depositEntry: (coin, poolCoinName) => {\n const coinType = builder.utils.parseCoinType(poolCoinName);\n return txBlock.moveCall({\n target: `${coreIds.protocolPkg}::mint::mint_entry`,\n arguments: [\n txBlock.object(coreIds.version),\n txBlock.object(coreIds.market),\n typeof coin !== 'string' ? (coin as TransactionArgument) : txBlock.pure(coin),\n txBlock.object(SUI_CLOCK_OBJECT_ID),\n ],\n typeArguments: [coinType],\n });\n },\n withdraw: (marketCoin, poolCoinName) => {\n const coinType = builder.utils.parseCoinType(poolCoinName);\n return txBlock.moveCall({\n target: `${coreIds.protocolPkg}::redeem::redeem`,\n arguments: [\n txBlock.object(coreIds.version),\n txBlock.object(coreIds.market),\n typeof marketCoin !== 'string' ? (marketCoin as TransactionArgument) : txBlock.pure(marketCoin),\n txBlock.object(SUI_CLOCK_OBJECT_ID),\n ],\n typeArguments: [coinType],\n });\n },\n withdrawEntry: (marketCoin, poolCoinName) => {\n const coinType = builder.utils.parseCoinType(poolCoinName);\n return txBlock.moveCall({\n target: `${coreIds.protocolPkg}::redeem::redeem_entry`,\n arguments: [\n txBlock.object(coreIds.version),\n txBlock.object(coreIds.market),\n typeof marketCoin !== 'string' ? (marketCoin as TransactionArgument) : txBlock.pure(marketCoin),\n txBlock.object(SUI_CLOCK_OBJECT_ID),\n ],\n typeArguments: [coinType],\n });\n },\n borrow: (obligation, obligationKey, amount, poolCoinName) => {\n const coinType = builder.utils.parseCoinType(poolCoinName);\n return txBlock.moveCall({\n target: `${coreIds.protocolPkg}::borrow::borrow`,\n arguments: [\n txBlock.object(coreIds.version),\n txBlock.object(obligation as string),\n txBlock.object(obligationKey as string),\n txBlock.object(coreIds.market),\n txBlock.object(coreIds.coinDecimalsRegistry),\n txBlock.pure(amount),\n txBlock.object(coreIds.xOracle),\n txBlock.object(SUI_CLOCK_OBJECT_ID),\n ],\n typeArguments: [coinType],\n });\n },\n borrowEntry: (obligation, obligationKey, amount, poolCoinName) => {\n const coinType = builder.utils.parseCoinType(poolCoinName);\n return txBlock.moveCall({\n target: `${coreIds.protocolPkg}::borrow::borrow_entry`,\n arguments: [\n txBlock.object(coreIds.version),\n txBlock.object(obligation as string),\n txBlock.object(obligationKey as string),\n txBlock.object(coreIds.market),\n txBlock.object(coreIds.coinDecimalsRegistry),\n txBlock.pure(amount),\n txBlock.object(coreIds.xOracle),\n txBlock.object(SUI_CLOCK_OBJECT_ID),\n ],\n typeArguments: [coinType],\n });\n },\n borrowWithReferral: (obligation, obligationKey, borrowReferral, amount, poolCoinName) => {\n const coinType = builder.utils.parseCoinType(poolCoinName);\n return txBlock.moveCall({\n target: `${coreIds.protocolPkg}::borrow::borrow_with_referral`,\n arguments: [\n txBlock.object(coreIds.version),\n txBlock.object(obligation as string),\n txBlock.object(obligationKey as string),\n txBlock.object(coreIds.market),\n txBlock.object(coreIds.coinDecimalsRegistry),\n txBlock.object(borrowReferral as string),\n txBlock.pure(amount),\n txBlock.object(coreIds.xOracle),\n txBlock.object(SUI_CLOCK_OBJECT_ID),\n ],\n typeArguments: [coinType, referralWitnessType],\n });\n },\n repay: (obligation, coin, poolCoinName) => {\n const coinType = builder.utils.parseCoinType(poolCoinName);\n return txBlock.moveCall({\n target: `${coreIds.protocolPkg}::repay::repay`,\n arguments: [\n txBlock.object(coreIds.version),\n txBlock.object(obligation as string),\n txBlock.object(coreIds.market),\n typeof coin !== 'string' ? (coin as TransactionArgument) : txBlock.pure(coin),\n txBlock.object(SUI_CLOCK_OBJECT_ID),\n ],\n typeArguments: [coinType],\n });\n },\n borrowFlashLoan: (amount, poolCoinName) => {\n const coinType = builder.utils.parseCoinType(poolCoinName);\n return txBlock.moveCall({\n target: `${coreIds.protocolPkg}::flash_loan::borrow_flash_loan`,\n arguments: [txBlock.object(coreIds.version), txBlock.object(coreIds.market), txBlock.pure(amount)],\n typeArguments: [coinType],\n });\n },\n repayFlashLoan: (coin, loan, poolCoinName) => {\n const coinType = builder.utils.parseCoinType(poolCoinName);\n return txBlock.moveCall({\n target: `${coreIds.protocolPkg}::flash_loan::repay_flash_loan`,\n arguments: [\n txBlock.object(coreIds.version),\n txBlock.object(coreIds.market),\n txBlock.pure(coin),\n txBlock.object(loan as string),\n ],\n typeArguments: [coinType],\n });\n },\n };\n};\n\n/**\n * Generate core quick methods.\n *\n * @description\n * The quick methods are the same as the normal methods, but they will automatically\n * help users organize transaction blocks, include query obligation info, and transfer\n * coins to the sender. So, they are all asynchronous methods.\n *\n * @param builder - Scallop builder instance.\n * @param txBlock - TxBlock created by SuiKit.\n * @return Core quick methods.\n */\nexport const generateCoreQuickMethod: GenerateCoreQuickMethod = async ({ builder, txBlock }) => {\n const normalMethod = await generateCoreNormalMethod({ builder, txBlock });\n const scoinNormalMethod = await generateSCoinNormalMethod({ builder, txBlock });\n return {\n normalMethod,\n addCollateralQuick: async (amount, collateralCoinName, obligationId) => {\n const sender = requireSender(txBlock);\n const { obligationId: obligationArg } = await requireObligationInfo(txBlock, builder, obligationId);\n\n if (collateralCoinName === 'sui') {\n const [suiCoin] = txBlock.splitCoins(txBlock.gas, [amount]);\n normalMethod.addCollateral(obligationArg, suiCoin, collateralCoinName);\n } else {\n const { leftCoin, takeCoin } = await builder.selectCoin(\n txBlock as ScallopTxBlock,\n collateralCoinName,\n amount,\n sender,\n );\n normalMethod.addCollateral(obligationArg, takeCoin, collateralCoinName);\n txBlock.transferObjects([leftCoin], sender);\n }\n },\n takeCollateralQuick: async (amount, collateralCoinName, obligationId, obligationKey) => {\n const obligationInfo = await requireObligationInfo(txBlock, builder, obligationId, obligationKey);\n const updateCoinNames = await builder.query.getObligationCoinNames(obligationInfo.obligationId);\n await updateOracles(builder, txBlock, updateCoinNames);\n return normalMethod.takeCollateral(\n obligationInfo.obligationId,\n obligationInfo.obligationKey as SuiAddressArg,\n amount,\n collateralCoinName,\n );\n },\n depositQuick: async (amount, poolCoinName, walletAddress) => {\n if (poolCoinName === 'sui') {\n const [suiCoin] = txBlock.splitCoins(txBlock.gas, [amount]);\n return normalMethod.deposit(suiCoin, poolCoinName);\n }\n const { leftCoin, takeCoin } = await builder.selectCoin(\n txBlock as ScallopTxBlock,\n poolCoinName,\n amount,\n walletAddress as string,\n );\n txBlock.transferObjects([leftCoin], walletAddress as string);\n return normalMethod.deposit(takeCoin, poolCoinName);\n },\n withdrawQuick: async (amount, poolCoinName) => {\n const sender = requireSender(txBlock);\n const marketCoinName = builder.utils.parseMarketCoinName(poolCoinName);\n // check if user has sCoin instead of marketCoin\n try {\n const sCoinName = builder.utils.parseSCoinName(poolCoinName);\n if (!sCoinName) {\n throw new Error(`No sCoin for ${poolCoinName}`);\n }\n const {\n leftCoin,\n takeCoin,\n totalAmount: sCoinAmount,\n } = await builder.selectSCoin(txBlock, sCoinName, amount, sender);\n txBlock.transferObjects([leftCoin], sender);\n const marketCoin = scoinNormalMethod.burnSCoin(sCoinName, takeCoin);\n\n const txResult = normalMethod.withdraw(marketCoin, poolCoinName);\n\n // check amount\n const amountLeft = amount - sCoinAmount;\n try {\n if (amountLeft > 0) {\n // sCoin is not enough, try market coin\n const { leftCoin: leftMarketCoin, takeCoin: takeMarketCoin } = await builder.selectMarketCoin(\n txBlock,\n marketCoinName,\n amountLeft,\n sender,\n );\n txBlock.transferObjects([leftMarketCoin], sender);\n txBlock.mergeCoins(txResult, [normalMethod.withdraw(takeMarketCoin, poolCoinName)]);\n }\n } catch (e) {\n // ignore\n }\n return txResult;\n } catch (e) {\n // no sCoin found\n const { leftCoin, takeCoin } = await builder.selectMarketCoin(txBlock, marketCoinName, amount, sender);\n txBlock.transferObjects([leftCoin], sender);\n return normalMethod.withdraw(takeCoin, poolCoinName);\n }\n },\n borrowQuick: async (amount, poolCoinName, obligationId, obligationKey) => {\n const obligationInfo = await requireObligationInfo(txBlock, builder, obligationId, obligationKey);\n const obligationCoinNames = await builder.query.getObligationCoinNames(obligationInfo.obligationId);\n const updateCoinNames = [...obligationCoinNames, poolCoinName];\n await updateOracles(builder, txBlock, updateCoinNames);\n return normalMethod.borrow(\n obligationInfo.obligationId,\n obligationInfo.obligationKey as SuiAddressArg,\n amount,\n poolCoinName,\n );\n },\n borrowWithReferralQuick: async (amount, poolCoinName, borrowReferral, obligationId, obligationKey) => {\n const obligationInfo = await requireObligationInfo(txBlock, builder, obligationId, obligationKey);\n const obligationCoinNames = await builder.query.getObligationCoinNames(obligationInfo.obligationId);\n const updateCoinNames = [...obligationCoinNames, poolCoinName];\n await updateOracles(builder, txBlock, updateCoinNames);\n return normalMethod.borrowWithReferral(\n obligationInfo.obligationId,\n obligationInfo.obligationKey as SuiAddressArg,\n borrowReferral,\n amount,\n poolCoinName,\n );\n },\n repayQuick: async (amount, poolCoinName, obligationId, walletAddress) => {\n const obligationInfo = await requireObligationInfo(txBlock, builder, obligationId);\n\n if (poolCoinName === 'sui') {\n const [suiCoin] = txBlock.splitCoins(txBlock.gas, [amount]);\n return normalMethod.repay(obligationInfo.obligationId, suiCoin, poolCoinName);\n }\n const { leftCoin, takeCoin } = await builder.selectCoin(\n txBlock as ScallopTxBlock,\n poolCoinName,\n amount,\n walletAddress as string,\n );\n txBlock.transferObjects([leftCoin], walletAddress as string);\n return normalMethod.repay(obligationInfo.obligationId, takeCoin, poolCoinName);\n },\n updateAssetPricesQuick: async (assetCoinNames) => updateOracles(builder, txBlock, assetCoinNames),\n };\n};\n","import type { TransactionArgument, TransactionBlock } from '@mysten/sui.js/transactions';\nimport { SUI_CLOCK_OBJECT_ID } from '@mysten/sui.js/utils';\n// eslint-disable-next-line import/no-extraneous-dependencies\nimport axios from 'axios';\n\nimport { SUPPORT_COLLATERALS, SUPPORT_POOLS } from '../constants';\nimport { PYTH_ENDPOINTS } from '../constants/pyth';\nimport type { ScallopBuilder } from '../models';\nimport { PythClient } from '../models/pythClient';\nimport type { SupportAssetCoins, SupportOracleType } from '../types';\n\nexport const getLatestVaas = async (endpoint: string, priceIds: string[]) => {\n const response = await axios.get(`${endpoint}/api/latest_vaas`, {\n params: {\n ids: priceIds,\n },\n });\n const latestVaas = response.data;\n return latestVaas.map((vaa: string) => Buffer.from(vaa, 'base64'));\n};\n\n/**\n * Update the price of the oracle for multiple coin.\n *\n * @param builder - The scallop builder.\n * @param txBlock - TxBlock created by SuiKit.\n * @param assetCoinNames - Specific an array of support asset coin name.\n */\nexport const updateOracles = async (\n builder: ScallopBuilder,\n txBlock: TransactionBlock,\n assetCoinNames?: SupportAssetCoins[],\n) => {\n const coinNames = assetCoinNames ?? [...new Set([...SUPPORT_POOLS, ...SUPPORT_COLLATERALS])];\n const rules: SupportOracleType[] = builder.isTestnet ? ['pyth'] : ['pyth'];\n if (rules.includes('pyth')) {\n const pythClient = new PythClient(\n builder.client as any,\n builder.address.get('core.oracles.pyth.state'),\n builder.address.get('core.oracles.pyth.wormholeState'),\n );\n const priceIds: string[] = [];\n await Promise.all(\n coinNames.map(async (assetCoinName) =>\n priceIds.push(builder.address.get(`core.coins.${assetCoinName}.oracle.pyth.feed`)),\n ),\n );\n\n // iterate through the endpoints\n const endpoints = builder.params.pythEndpoints ?? PYTH_ENDPOINTS[builder.isTestnet ? 'testnet' : 'mainnet'];\n try {\n const priceUpdateData = await getLatestVaas(endpoints[0], priceIds);\n await pythClient.updatePriceFeeds(txBlock as any, priceUpdateData, priceIds);\n } catch (e) {\n console.warn(`Failed to update price feeds with endpoint ${endpoints[0]}: ${e}`);\n }\n }\n\n // Remove duplicate coin names.\n const updateAssetCoinNames = [...new Set(coinNames)];\n for (let i = 0; i < updateAssetCoinNames.length; i++) {\n await updateOracle(builder, txBlock, updateAssetCoinNames[i], rules);\n }\n};\n\n/**\n * Update the price of the oracle for specific coin.\n *\n * @param builder - The scallop builder.\n * @param txBlock - TxBlock created by SuiKit.\n * @param assetCoinName - Specific support asset coin name.\n */\nconst updateOracle = async (\n builder: ScallopBuilder,\n txBlock: TransactionBlock,\n assetCoinName: SupportAssetCoins,\n rules: SupportOracleType[],\n) => {\n const coinType = builder.utils.parseCoinType(assetCoinName);\n\n updatePrice(\n txBlock,\n rules,\n builder.address.get('core.packages.xOracle.id'),\n builder.address.get('core.oracles.xOracle'),\n builder.address.get('core.packages.pyth.id'),\n builder.address.get('core.oracles.pyth.registry'),\n builder.address.get('core.oracles.pyth.state'),\n builder.address.get(`core.coins.${assetCoinName}.oracle.pyth.feedObject`),\n builder.address.get('core.packages.switchboard.id'),\n builder.address.get('core.oracles.switchboard.registry'),\n builder.address.get(`core.coins.${assetCoinName}.oracle.switchboard`),\n builder.address.get('core.packages.supra.id'),\n builder.address.get('core.oracles.supra.registry'),\n builder.address.get(`core.oracles.supra.holder`),\n coinType,\n );\n};\n\n/**\n * Construct a transaction block for update the price.\n *\n * @param txBlock - The transaction block.\n * @param rules - The oracle rules.\n * @param xOraclePackageId - The xOracle package id.\n * @param xOracleId - The xOracle Id from xOracle package.\n * @param pythPackageId - The pyth package id.\n * @param pythRegistryId - The registry id from pyth package.\n * @param pythStateId - The price state id from pyth package.\n * @param pythFeedObjectId - The feed object id from pyth package.\n * @param switchboardPackageId - The switchboard package id.\n * @param switchboardRegistryId - The registry id from switchboard package.\n * @param switchboardAggregatorId - The aggregator id from switchboard package.\n * @param supraPackageId - The supra package id.\n * @param supraRegistryId - The registry id from supra package.\n * @param supraHolderId - The holder id from supra package.\n * @param coinType - The type of coin.\n * @return TxBlock created by SuiKit.\n */\nconst updatePrice = (\n txBlock: TransactionBlock,\n rules: SupportOracleType[],\n xOraclePackageId: string,\n xOracleId: TransactionArgument | string,\n pythPackageId: string,\n pythRegistryId: TransactionArgument | string,\n pythStateId: TransactionArgument | string,\n pythFeedObjectId: TransactionArgument | string,\n switchboardPackageId: string,\n switchboardRegistryId: TransactionArgument | string,\n switchboardAggregatorId: TransactionArgument | string,\n supraPackageId: string,\n supraRegistryId: TransactionArgument | string,\n supraHolderId: TransactionArgument | string,\n coinType: string,\n) => {\n const request = priceUpdateRequest(txBlock, xOraclePackageId, xOracleId, coinType);\n if (rules.includes('pyth')) {\n updatePythPrice(txBlock, pythPackageId, request, pythStateId, pythFeedObjectId, pythRegistryId, coinType);\n }\n if (rules.includes('switchboard')) {\n updateSwitchboardPrice(\n txBlock,\n switchboardPackageId,\n request,\n switchboardAggregatorId,\n switchboardRegistryId,\n coinType,\n );\n }\n if (rules.includes('supra')) {\n updateSupraPrice(txBlock, supraPackageId, request, supraHolderId, supraRegistryId, coinType);\n }\n confirmPriceUpdateRequest(txBlock, xOraclePackageId, xOracleId, request, coinType);\n return txBlock;\n};\n\n/**\n * Construct a transaction block for request price update.\n *\n * @param txBlock - The transaction block.\n * @param packageId - The xOracle package id.\n * @param xOracleId - The xOracle Id from xOracle package.\n * @param coinType - The type of coin.\n * @return TxBlock created by SuiKit.\n */\nconst priceUpdateRequest = (\n txBlock: TransactionBlock,\n packageId: string,\n xOracleId: TransactionArgument | string,\n coinType: string,\n) => {\n const validXOracleId = typeof xOracleId === 'string' ? txBlock.object(xOracleId) : xOracleId;\n const target = `${packageId}::x_oracle::price_update_request` as `${string}::${string}::${string}`;\n const typeArgs = [coinType];\n return txBlock.moveCall({ target, arguments: [validXOracleId], typeArguments: typeArgs });\n};\n\n/**\n * Construct a transaction block for confirm price update request.\n *\n * @param txBlock - The transaction block.\n * @param packageId - The xOracle package id.\n * @param xOracleId - The xOracle Id from xOracle package.\n * @param request - The result of the request.\n * @param coinType - The type of coin.\n * @return TxBlock created by SuiKit.\n */\nconst confirmPriceUpdateRequest = (\n txBlock: TransactionBlock,\n packageId: string,\n xOracleId: TransactionArgument | string,\n request: TransactionArgument,\n coinType: string,\n) => {\n const target = `${packageId}::x_oracle::confirm_price_update_request` as `${string}::${string}::${string}`;\n const typeArgs = [coinType];\n const validXOracleId = typeof xOracleId === 'string' ? txBlock.object(xOracleId) : xOracleId;\n txBlock.moveCall({\n target,\n arguments: [validXOracleId, request, txBlock.object(SUI_CLOCK_OBJECT_ID)],\n typeArguments: typeArgs,\n });\n return txBlock;\n};\n\n/**\n * Construct a transaction block for update supra price.\n *\n * @param txBlock - The transaction block.\n * @param packageId - The supra package id.\n * @param request - The result of the request.\n * @param holderId - The holder id from supra package.\n * @param registryId - The registry id from supra package.\n * @param coinType - The type of coin.\n * @return TxBlock created by SuiKit.\n */\nconst updateSupraPrice = (\n txBlock: TransactionBlock,\n packageId: string,\n request: TransactionArgument,\n holderId: TransactionArgument | string,\n registryId: TransactionArgument | string,\n coinType: string,\n) => {\n const validHolderId = typeof holderId === 'string' ? txBlock.object(holderId) : holderId;\n const validRegistryId = typeof registryId === 'string' ? txBlock.object(registryId) : registryId;\n txBlock.moveCall({\n target: `${packageId}::rule::set_price`,\n arguments: [request, validHolderId, validRegistryId, txBlock.object(SUI_CLOCK_OBJECT_ID)],\n typeArguments: [coinType],\n });\n};\n\n/**\n * Construct a transaction block for update switchboard price.\n *\n * @param txBlock - The transaction block.\n * @param packageId - The switchboard package id.\n * @param request - The result of the request.\n * @param aggregatorId - The aggregator id from switchboard package.\n * @param registryId - The registry id from switchboard package.\n * @param coinType - The type of coin.\n * @return TxBlock created by SuiKit.\n */\nconst updateSwitchboardPrice = (\n txBlock: TransactionBlock,\n packageId: string,\n request: TransactionArgument,\n aggregatorId: TransactionArgument | string,\n registryId: TransactionArgument | string,\n coinType: string,\n) => {\n const validAggregatorId = typeof aggregatorId === 'string' ? txBlock.object(aggregatorId) : aggregatorId;\n const validRegistryId = typeof registryId === 'string' ? txBlock.object(registryId) : registryId;\n txBlock.moveCall({\n target: `${packageId}::rule::set_price`,\n arguments: [request, validAggregatorId, validRegistryId, txBlock.object(SUI_CLOCK_OBJECT_ID)],\n typeArguments: [coinType],\n });\n};\n\n/**\n * Construct a transaction block for update pyth price.\n *\n * @param txBlock - The transaction block.\n * @param packageId - The pyth package id.\n * @param request - The result of the request.\n * @param stateId - The price state id from pyth package.\n * @param wormholeStateId - The whormhole state id from pyth package.\n * @param feedObjectId - The feed object id from pyth package.\n * @param vaaFromFeeId - The vaa from pyth api with feed id.\n * @param registryId - The registry id from pyth package.\n * @param coinType - The type of coin.\n * @return TxBlock created by SuiKit.\n */\nconst updatePythPrice = (\n txBlock: TransactionBlock,\n packageId: string,\n request: TransactionArgument | string,\n stateId: TransactionArgument | string,\n feedObjectId: TransactionArgument | string,\n registryId: TransactionArgument | string,\n coinType: string,\n) => {\n const validRequest = typeof request === 'string' ? txBlock.object(request) : request;\n const validStateId = typeof stateId === 'string' ? txBlock.object(stateId) : stateId;\n const validFeedObjectId = typeof feedObjectId === 'string' ? txBlock.object(feedObjectId) : feedObjectId;\n const validRegistryId = typeof registryId === 'string' ? txBlock.object(registryId) : registryId;\n\n txBlock.moveCall({\n target: `${packageId}::rule::set_price`,\n arguments: [validRequest, validStateId, validFeedObjectId, validRegistryId, txBlock.object(SUI_CLOCK_OBJECT_ID)],\n typeArguments: [coinType],\n });\n};\n","export const PYTH_ENDPOINTS: {\n [k in 'mainnet' | 'testnet']: Readonly<string[]>;\n} = {\n testnet: ['https://hermes-beta.pyth.network'],\n mainnet: ['https://hermes.pyth.network', 'https://scallop.rpc.p2p.world'],\n} as const;\n","import { bcs } from '@mysten/sui.js/bcs';\nimport { SuiClient } from '@mysten/sui.js/client';\nimport { TransactionBlock } from '@mysten/sui.js/transactions';\nimport { SUI_CLOCK_OBJECT_ID } from '@mysten/sui.js/utils';\n\nconst MAX_ARGUMENT_SIZE = 16 * 1024;\n\nexport class PythClient {\n provider: SuiClient;\n\n pythStateId: string;\n\n wormholeStateId: string;\n\n private pythPackageId: any;\n\n private wormholePackageId: any;\n\n private priceTableInfo: { id: string; fieldType: string };\n\n private priceFeedObjectIdCache: Map<string, string> = new Map();\n\n private baseUpdateFee: any;\n\n constructor(provider: SuiClient, pythStateId: string, wormholeStateId: string) {\n this.provider = provider;\n this.pythStateId = pythStateId;\n this.wormholeStateId = wormholeStateId;\n this.pythPackageId = undefined;\n this.wormholePackageId = undefined;\n }\n\n async getBaseUpdateFee() {\n if (this.baseUpdateFee === undefined) {\n const result = await this.provider.getObject({\n id: this.pythStateId,\n options: { showContent: true },\n });\n if (!result.data || !result.data.content || result.data.content.dataType !== 'moveObject') {\n throw new Error('Unable to fetch pyth state object');\n }\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n this.baseUpdateFee = result.data.content.fields.base_update_fee;\n }\n return this.baseUpdateFee;\n }\n\n /**\n * getPackageId returns the latest package id that the object belongs to. Use this to\n * fetch the latest package id for a given object id and handle package upgrades automatically.\n * @param objectId\n * @returns package id\n */\n async getPackageId(objectId: string) {\n const state = await this.provider\n .getObject({\n id: objectId,\n options: {\n showContent: true,\n },\n })\n .then((result) => {\n if (result.data?.content?.dataType === 'moveObject') {\n return result.data.content.fields;\n }\n throw new Error(`Cannot fetch package id for object ${objectId}`);\n });\n if ('upgrade_cap' in state) {\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n return state.upgrade_cap.fields.package;\n }\n throw new Error('upgrade_cap not found');\n }\n\n /**\n * Adds the commands for calling wormhole and verifying the vaas and returns the verified vaas.\n * @param vaas array of vaas to verify\n * @param tx transaction block to add commands to\n */\n async verifyVaas(vaas: Buffer[], tx: TransactionBlock) {\n const wormholePackageId = await this.getWormholePackageId();\n const verifiedVaas: {\n index: number;\n resultIndex: number;\n kind: 'NestedResult';\n }[] = [];\n vaas.forEach((vaa) => {\n const [verifiedVaa] = tx.moveCall({\n target: `${wormholePackageId}::vaa::parse_and_verify`,\n arguments: [\n tx.object(this.wormholeStateId),\n tx.pure(\n bcs\n .ser('vector<u8>', Array.from(vaa), {\n maxSize: MAX_ARGUMENT_SIZE,\n })\n .toBytes(),\n ),\n tx.object(SUI_CLOCK_OBJECT_ID),\n ],\n });\n verifiedVaas.push(verifiedVaa);\n });\n return verifiedVaas;\n }\n\n /**\n * Adds the necessary commands for updating the pyth price feeds to the transaction block.\n * @param tx transaction block to add commands to\n * @param updates array of price feed updates received from the price service\n * @param feedIds array of feed ids to update (in hex format)\n */\n async updatePriceFeeds(tx: TransactionBlock, updates: Buffer[], feedIds: string[]) {\n const packageId = await this.getPythPackageId();\n let priceUpdatesHotPotato;\n if (updates.length > 1) {\n throw new Error('SDK does not support sending multiple accumulator messages in a single transaction');\n }\n const vaa = this.extractVaaBytesFromAccumulatorMessage(updates[0]);\n const verifiedVaas = await this.verifyVaas([vaa], tx);\n [priceUpdatesHotPotato] = tx.moveCall({\n target: `${packageId}::pyth::create_authenticated_price_infos_using_accumulator`,\n arguments: [\n tx.object(this.pythStateId),\n tx.pure(\n bcs\n .ser('vector<u8>', Array.from(updates[0]), {\n maxSize: MAX_ARGUMENT_SIZE,\n })\n .toBytes(),\n ),\n verifiedVaas[0],\n tx.object(SUI_CLOCK_OBJECT_ID),\n ],\n });\n const priceInfoObjects = [];\n const baseUpdateFee = await this.getBaseUpdateFee();\n const coins = tx.splitCoins(\n tx.gas,\n feedIds.map(() => tx.pure(baseUpdateFee)),\n );\n let coinId = 0;\n for (let i = 0; i < feedIds.length; i++) {\n const priceInfoObjectId = await this.getPriceFeedObjectId(feedIds[i]);\n if (!priceInfoObjectId) {\n throw new Error(`Price feed ${feedIds[0]} not found, please create it first`);\n }\n priceInfoObjects.push(priceInfoObjectId);\n [priceUpdatesHotPotato] = tx.moveCall({\n target: `${packageId}::pyth::update_single_price_feed`,\n arguments: [\n tx.object(this.pythStateId),\n priceUpdatesHotPotato,\n tx.object(priceInfoObjectId),\n coins[coinId],\n tx.object(SUI_CLOCK_OBJECT_ID),\n ],\n });\n coinId++;\n }\n tx.moveCall({\n target: `${packageId}::hot_potato_vector::destroy`,\n arguments: [priceUpdatesHotPotato],\n typeArguments: [`${packageId}::price_info::PriceInfo`],\n });\n return priceInfoObjects;\n }\n\n async createPriceFeed(tx: TransactionBlock, updates: Buffer[]) {\n const packageId = await this.getPythPackageId();\n if (updates.length > 1) {\n throw new Error('SDK does not support sending multiple accumulator messages in a single transaction');\n }\n const vaa = this.extractVaaBytesFromAccumulatorMessage(updates[0]);\n const verifiedVaas = await this.verifyVaas([vaa], tx);\n tx.moveCall({\n target: `${packageId}::pyth::create_price_feeds_using_accumulator`,\n arguments: [\n tx.object(this.pythStateId),\n tx.pure(\n bcs\n .ser('vector<u8>', Array.from(updates[0]), {\n maxSize: MAX_ARGUMENT_SIZE,\n })\n .toBytes(),\n ),\n verifiedVaas[0],\n tx.object(SUI_CLOCK_OBJECT_ID),\n ],\n });\n }\n\n /**\n * Get the packageId for the wormhole package if not already cached\n */\n async getWormholePackageId() {\n if (!this.wormholePackageId) {\n this.wormholePackageId = await this.getPackageId(this.wormholeStateId);\n }\n return this.wormholePackageId;\n }\n\n /**\n * Get the packageId for the pyth package if not already cached\n */\n async getPythPackageId() {\n if (!this.pythPackageId) {\n this.pythPackageId = await this.getPackageId(this.pythStateId);\n }\n return this.pythPackageId;\n }\n\n /**\n * Get the priceFeedObjectId for a given feedId if not already cached\n * @param feedId\n */\n async getPriceFeedObjectId(feedId: string) {\n const normalizedFeedId = feedId.replace('0x', '');\n if (!this.priceFeedObjectIdCache.has(normalizedFeedId)) {\n const { id: tableId, fieldType } = await this.getPriceTableInfo();\n const result = await this.provider.getDynamicFieldObject({\n parentId: tableId,\n name: {\n type: `${fieldType}::price_identifier::PriceIdentifier`,\n value: {\n bytes: Array.from(Buffer.from(normalizedFeedId, 'hex')),\n },\n },\n });\n if (!result.data || !result.data.content) {\n return undefined;\n }\n if (result.data.content.dataType !== 'moveObject') {\n throw new Error('Price feed type mismatch');\n }\n this.priceFeedObjectIdCache.set(\n normalizedFeedId,\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n result.data.content.fields.value,\n );\n }\n return this.priceFeedObjectIdCache.get(normalizedFeedId);\n }\n\n /**\n * Fetches the price table object id for the current state id if not cached\n * @returns price table object id\n */\n async getPriceTableInfo() {\n if (this.priceTableInfo === undefined) {\n const result = await this.provider.getDynamicFieldObject({\n parentId: this.pythStateId,\n name: {\n type: 'vector<u8>',\n value: 'price_info',\n },\n });\n if (!result.data || !result.data.type) {\n throw new Error('Price Table not found, contract may not be initialized');\n }\n let type = result.data.type.replace('0x2::table::Table<', '');\n type = type.replace('::price_identifier::PriceIdentifier, 0x2::object::ID>', '');\n this.priceTableInfo = { id: result.data.objectId, fieldType: type };\n }\n return this.priceTableInfo;\n }\n\n /**\n * Obtains the vaa bytes embedded in an accumulator message.\n * @param accumulatorMessage - the accumulator price update message\n * @returns vaa bytes as a uint8 array\n */\n extractVaaBytesFromAccumulatorMessage(accumulatorMessage: Buffer): Buffer {\n // the first 6 bytes in the accumulator message encode the header, major, and minor bytes\n // we ignore them, since we are only interested in the VAA bytes\n const trailingPayloadSize = accumulatorMessage.readUint8(6);\n const vaaSizeOffset =\n 7 + // header bytes (header(4) + major(1) + minor(1) + trailing payload size(1))\n trailingPayloadSize + // trailing payload (variable number of bytes)\n 1; // proof_type (1 byte)\n const vaaSize = accumulatorMessage.readUint16BE(vaaSizeOffset);\n const vaaOffset = vaaSizeOffset + 2;\n return accumulatorMessage.subarray(vaaOffset, vaaOffset + vaaSize);\n }\n}\n","import { TransactionArgument } from '@mysten/sui.js/transactions';\n\nimport { SUPPORT_SCOIN } from '../constants';\nimport { GenerateSCoinNormalMethod, GenerateSCoinQuickMethod, SCoinPkgIds, sCoinTreasuryIds } from '../types';\n\nexport const generateSCoinNormalMethod: GenerateSCoinNormalMethod = async ({ builder, txBlock }) => {\n const sCoinPkgIds: SCoinPkgIds = {\n pkgId: builder.address.get('scoin.id'),\n };\n\n const treasuryIds: sCoinTreasuryIds = {};\n await Promise.all(\n SUPPORT_SCOIN.map(async (sCoinName) => {\n const treasuryId = builder.utils.getSCoinTreasury(sCoinName);\n treasuryIds[sCoinName] = treasuryId;\n }),\n );\n\n return {\n mintSCoin: (marketCoinName, marketCoin) =>\n txBlock.moveCall({\n target: `${sCoinPkgIds.pkgId}::s_coin_converter::mint_s_coin`,\n arguments: [\n txBlock.object(treasuryIds[marketCoinName]),\n typeof marketCoin !== 'string' ? (marketCoin as TransactionArgument) : txBlock.pure(marketCoin),\n ],\n typeArguments: [\n builder.utils.parseSCoinType(marketCoinName),\n builder.utils.parseUnderlyingSCoinType(marketCoinName),\n ],\n }),\n burnSCoin: (sCoinName, sCoin) =>\n txBlock.moveCall({\n target: `${sCoinPkgIds.pkgId}::s_coin_converter::burn_s_coin`,\n arguments: [\n txBlock.object(treasuryIds[sCoinName]),\n typeof sCoin !== 'string' ? (sCoin as TransactionArgument) : txBlock.pure(sCoin),\n ],\n typeArguments: [builder.utils.parseSCoinType(sCoinName), builder.utils.parseUnderlyingSCoinType(sCoinName)],\n }),\n };\n};\n\nexport const generateSCoinQuickMethod: GenerateSCoinQuickMethod = async ({ builder, txBlock }) => ({\n mintSCoinQuick: async (marketCoinName, amount, walletAddress) => {\n const { leftCoin, takeCoin } = await builder.selectMarketCoin(txBlock, marketCoinName, amount, walletAddress);\n\n txBlock.transferObjects([leftCoin], walletAddress);\n return txBlock.mintSCoin(marketCoinName, takeCoin);\n },\n burnSCoinQuick: async (sCoinName, amount, walletAddress) => {\n const { leftCoin, takeCoin } = await builder.selectSCoin(txBlock, sCoinName, amount, walletAddress);\n\n txBlock.transferObjects([leftCoin], walletAddress);\n return txBlock.burnSCoin(sCoinName, takeCoin);\n },\n});\n","import { TransactionObjectArgument } from '@mysten/sui.js/transactions';\nimport { SUI_CLOCK_OBJECT_ID } from '@mysten/sui.js/utils';\n\nimport { SUPPORT_POOLS } from '../constants';\nimport {\n SupportCoins,\n SupportPoolCoins,\n GenerateReferralNormalMethod,\n GenerateReferralQuickMethod,\n ReferralIds,\n SuiObjectArg,\n} from '../types';\n\nexport const generateReferralNormalMethod: GenerateReferralNormalMethod = async ({ builder, txBlock }) => {\n const referralIds: ReferralIds = {\n referralPgkId: builder.address.get('referral.id'),\n referralBindings: builder.address.get('referral.referralBindings'),\n referralRevenuePool: builder.address.get('referral.referralRevenuePool'),\n authorizedWitnessList: builder.address.get('referral.authorizedWitnessList'),\n referralTiers: builder.address.get('referral.referralTiers'),\n version: builder.address.get('referral.version'),\n };\n\n const veScaTable = builder.address.get('vesca.table');\n\n return {\n bindToReferral: (veScaKeyId: string) =>\n txBlock.moveCall({\n target: `${referralIds.referralPgkId}::referral_bindings::bind_ve_sca_referrer`,\n arguments: [\n txBlock.object(referralIds.referralBindings),\n txBlock.pure(veScaKeyId),\n txBlock.object(veScaTable),\n txBlock.object(SUI_CLOCK_OBJECT_ID),\n ],\n typeArguments: [],\n }),\n claimReferralTicket: (poolCoinName: SupportCoins) => {\n const coinType = builder.utils.parseCoinType(poolCoinName);\n return txBlock.moveCall({\n target: `${referralIds.referralPgkId}::scallop_referral_program::claim_ve_sca_referral_ticket`,\n arguments: [\n txBlock.object(referralIds.version),\n txBlock.object(veScaTable),\n txBlock.object(referralIds.referralBindings),\n txBlock.object(referralIds.authorizedWitnessList),\n txBlock.object(referralIds.referralTiers),\n txBlock.object(SUI_CLOCK_OBJECT_ID),\n ],\n typeArguments: [coinType],\n });\n },\n burnReferralTicket: (ticket: SuiObjectArg, poolCoinName: SupportCoins) => {\n const coinType = builder.utils.parseCoinType(poolCoinName);\n return txBlock.moveCall({\n target: `${referralIds.referralPgkId}::scallop_referral_program::burn_ve_sca_referral_ticket`,\n arguments: [\n txBlock.object(referralIds.version),\n txBlock.object(ticket as string),\n txBlock.object(referralIds.referralRevenuePool),\n txBlock.object(SUI_CLOCK_OBJECT_ID),\n ],\n typeArguments: [coinType],\n });\n },\n claimReferralRevenue: (veScaKey: SuiObjectArg, poolCoinName: SupportCoins) => {\n const coinType = builder.utils.parseCoinType(poolCoinName);\n return txBlock.moveCall({\n target: `${referralIds.referralPgkId}::referral_revenue_pool::claim_revenue_with_ve_sca_key`,\n arguments: [\n txBlock.object(referralIds.version),\n txBlock.object(referralIds.referralRevenuePool),\n txBlock.object(veScaKey as string),\n txBlock.object(SUI_CLOCK_OBJECT_ID),\n ],\n typeArguments: [coinType],\n });\n },\n };\n};\n\nexport const generateReferralQuickMethod: GenerateReferralQuickMethod = async ({ builder, txBlock }) => {\n const normalMethod = await generateReferralNormalMethod({ builder, txBlock });\n return {\n claimReferralRevenueQuick: async (\n veScaKey: SuiObjectArg,\n walletAddress: string,\n coinNames: SupportPoolCoins[] = [...SUPPORT_POOLS],\n ) => {\n const objToTransfer: SuiObjectArg[] = [];\n for (let i = 0; i < coinNames.length; i++) {\n if (coinNames[i] === 'sui') {\n const rewardCoin = normalMethod.claimReferralRevenue(veScaKey, coinNames[i]);\n objToTransfer.push(rewardCoin);\n } else {\n const rewardCoin = normalMethod.claimReferralRevenue(veScaKey, coinNames[i]);\n try {\n // get the matching user coin if exists\n const coins = await builder.utils.selectCoinIds(\n Infinity,\n builder.utils.parseCoinType(coinNames[i]),\n walletAddress,\n );\n txBlock.mergeCoins(rewardCoin, coins.slice(0, 500));\n } catch (e) {\n // ignore\n } finally {\n objToTransfer.push(rewardCoin);\n }\n }\n }\n if (objToTransfer.length > 0) {\n txBlock.transferObjects(objToTransfer as (string | TransactionObjectArgument)[], txBlock.pure(walletAddress));\n }\n },\n };\n};\n","import { TransactionArgument, TransactionBlock } from '@mysten/sui.js/transactions';\n\nexport const SlippageContract = {\n packageId: '0x5857d185897aaff40ae37b2eecc895efc1a9dff1b210c4fb894eabbce4ac2603',\n} as const;\n\nexport const SlippageTxBuilder = {\n check_slippage: (\n tx: TransactionBlock,\n resultCoin: TransactionArgument,\n slippage: number,\n expectedAmount: number | string,\n coinType: string,\n ) =>\n tx.moveCall({\n target: `${SlippageContract.packageId}::slippage_check::check_slippage`,\n arguments: [resultCoin, tx.pure(slippage), tx.pure(expectedAmount)],\n typeArguments: [coinType],\n }),\n} as const;\n","import { TransactionBlock } from '@mysten/sui.js/transactions';\nimport type { TransactionResult } from '@mysten/sui.js/transactions';\nimport { SUI_CLOCK_OBJECT_ID } from '@mysten/sui.js/utils';\n\nimport { generateSCoinNormalMethod } from './sCoinBuilder';\nimport { SUPPORT_SPOOLS } from '../constants';\nimport { spoolRewardCoins } from '../constants/enum';\nimport type { ScallopBuilder } from '../models';\nimport { getStakeAccounts } from '../queries/spoolQuery';\nimport type {\n SpoolIds,\n GenerateSpoolNormalMethod,\n GenerateSpoolQuickMethod,\n SupportStakeMarketCoins,\n SuiAddressArg,\n StakePoolIds,\n RewardPoolIds,\n StakeMarketCoinTypes,\n} from '../types';\nimport { requireSender } from '../utils';\n\nconst stakeHelper = async (\n builder: ScallopBuilder,\n txBlock: TransactionBlock,\n stakeAccount: SuiAddressArg,\n coinName: SupportStakeMarketCoins,\n amount: number,\n sender: string,\n isSCoin = false,\n) => {\n const scoinNormalMethod = await generateSCoinNormalMethod({ builder, txBlock });\n const spoolNormalMethod = await generateSpoolNormalMethod({ builder, txBlock });\n try {\n const { takeCoin, leftCoin, totalAmount } = isSCoin\n ? await builder.selectSCoin(txBlock, coinName, amount, sender)\n : await builder.selectMarketCoin(txBlock, coinName, amount, sender);\n if (isSCoin) {\n const marketCoin = scoinNormalMethod.burnSCoin(coinName, takeCoin);\n spoolNormalMethod.stake(stakeAccount, marketCoin, coinName);\n } else {\n spoolNormalMethod.stake(stakeAccount, takeCoin, coinName);\n }\n txBlock.transferObjects([leftCoin], sender);\n return totalAmount;\n } catch (e) {\n return 0;\n }\n};\n\n/**\n * Check and get stake account id from transaction block.\n *\n * @description\n * If the stake account id is provided, directly return it.\n * Otherwise, automatically get all stake account id from the sender.\n *\n * @param builder - Scallop builder instance.\n * @param txBlock - TxBlock created by SuiKit.\n * @param stakeMarketCoinName - The name of the market coin supported for staking.\n * @param stakeAccountId - Stake account id.\n * @return Stake account ids.\n */\nconst requireStakeAccountIds = async (\n ...params: [\n builder: ScallopBuilder,\n txBlock: TransactionBlock,\n stakeMarketCoinName: SupportStakeMarketCoins,\n stakeAccountId?: SuiAddressArg,\n ]\n) => {\n const [builder, txBlock, stakeMarketCoinName, stakeAccountId] = params;\n if (params.length === 4 && stakeAccountId) {\n return [stakeAccountId];\n }\n const sender = requireSender(txBlock);\n const stakeAccounts = await getStakeAccounts(builder.query, sender);\n return stakeAccounts[stakeMarketCoinName].map((account) => account.id);\n};\n\n/**\n * Check and get stake accounts information from transaction block.\n *\n * @description\n * If the stake account id is provided, directly return its account.\n * Otherwise, automatically get all stake account from the sender.\n *\n * @param builder - Scallop builder instance.\n * @param txBlock - TxBlock created by SuiKit.\n * @param stakeMarketCoinName - The name of the market coin supported for staking.\n * @param stakeAccountId - Stake account id.\n * @return Stake accounts.\n */\nconst requireStakeAccounts = async (\n ...params: [\n builder: ScallopBuilder,\n txBlock: TransactionBlock,\n stakeMarketCoinName: SupportStakeMarketCoins,\n stakeAccountId?: SuiAddressArg,\n ]\n) => {\n const [builder, txBlock, stakeMarketCoinName, stakeAccountId] = params;\n const sender = requireSender(txBlock);\n const stakeAccounts = await getStakeAccounts(builder.query, sender);\n if (stakeAccounts[stakeMarketCoinName].length === 0) {\n throw new Error(`No stake account found for sender ${sender}`);\n }\n\n const specificStakeAccounts = stakeAccountId\n ? stakeAccounts[stakeMarketCoinName].filter((account) => account.id === stakeAccountId)\n : stakeAccounts[stakeMarketCoinName];\n\n return specificStakeAccounts;\n};\n\n/**\n * Generate spool normal methods.\n *\n * @param builder - Scallop builder instance.\n * @param txBlock - TxBlock created by SuiKit .\n * @return Spool normal methods.\n */\nexport const generateSpoolNormalMethod: GenerateSpoolNormalMethod = async ({ builder, txBlock }) => {\n const spoolIds: SpoolIds = {\n spoolPkg: builder.address.get('spool.id'),\n };\n const stakePoolIds: StakePoolIds = {};\n const rewardPoolIds: RewardPoolIds = {};\n const stakeMarketCoinTypes: StakeMarketCoinTypes = {};\n SUPPORT_SPOOLS.forEach((stakeMarketCoinName) => {\n const spoolId = builder.address.get(`spool.pools.${stakeMarketCoinName}.id`);\n const rewardId = builder.address.get(`spool.pools.${stakeMarketCoinName}.rewardPoolId`);\n const marketCoinType = builder.utils.parseMarketCoinType(stakeMarketCoinName);\n stakePoolIds[stakeMarketCoinName] = spoolId;\n rewardPoolIds[stakeMarketCoinName] = rewardId;\n stakeMarketCoinTypes[stakeMarketCoinName] = marketCoinType;\n });\n return {\n createStakeAccount: (stakeMarketCoinName) => {\n const marketCoinType = stakeMarketCoinTypes[stakeMarketCoinName];\n const stakePoolId = stakePoolIds[stakeMarketCoinName];\n return txBlock.moveCall({\n target: `${spoolIds.spoolPkg}::user::new_spool_account`,\n arguments: [txBlock.object(stakePoolId), txBlock.object(SUI_CLOCK_OBJECT_ID)],\n typeArguments: [marketCoinType],\n });\n },\n stake: (stakeAccount, coin, stakeMarketCoinName) => {\n const marketCoinType = stakeMarketCoinTypes[stakeMarketCoinName];\n const stakePoolId = stakePoolIds[stakeMarketCoinName];\n txBlock.moveCall({\n target: `${spoolIds.spoolPkg}::user::stake`,\n arguments: [\n txBlock.object(stakePoolId),\n txBlock.object(stakeAccount as string),\n typeof coin === 'string' ? txBlock.pure(coin) : (coin as any),\n txBlock.object(SUI_CLOCK_OBJECT_ID),\n ],\n typeArguments: [marketCoinType],\n });\n },\n unstake: (stakeAccount, amount, stakeMarketCoinName) => {\n const marketCoinType = stakeMarketCoinTypes[stakeMarketCoinName];\n const stakePoolId = stakePoolIds[stakeMarketCoinName];\n return txBlock.moveCall({\n target: `${spoolIds.spoolPkg}::user::unstake`,\n arguments: [\n txBlock.object(stakePoolId),\n txBlock.object(stakeAccount as string),\n txBlock.pure(amount),\n txBlock.object(SUI_CLOCK_OBJECT_ID),\n ],\n typeArguments: [marketCoinType],\n });\n },\n claim: (stakeAccount, stakeMarketCoinName) => {\n const stakePoolId = stakePoolIds[stakeMarketCoinName];\n const rewardPoolId = rewardPoolIds[stakeMarketCoinName];\n const marketCoinType = stakeMarketCoinTypes[stakeMarketCoinName];\n const rewardCoinName = spoolRewardCoins[stakeMarketCoinName];\n const rewardCoinType = builder.utils.parseCoinType(rewardCoinName);\n return txBlock.moveCall({\n target: `${spoolIds.spoolPkg}::user::redeem_rewards`,\n arguments: [\n txBlock.object(stakePoolId),\n txBlock.object(rewardPoolId),\n txBlock.object(stakeAccount as string),\n txBlock.object(SUI_CLOCK_OBJECT_ID),\n ],\n typeArguments: [marketCoinType, rewardCoinType],\n });\n },\n };\n};\n\n/**\n * Generate spool quick methods.\n *\n * @description\n * The quick methods are the same as the normal methods, but they will automatically\n * help users organize transaction blocks, include get stake account info, and transfer\n * coins to the sender. So, they are all asynchronous methods.\n *\n * @param builder - Scallop builder instance.\n * @param txBlock - TxBlock created by SuiKit .\n * @return Spool quick methods.\n */\nexport const generateSpoolQuickMethod: GenerateSpoolQuickMethod = async ({ builder, txBlock }) => {\n const normalMethod = await generateSpoolNormalMethod({ builder, txBlock });\n const scoinMethod = await generateSCoinNormalMethod({ builder, txBlock });\n return {\n normalMethod,\n stakeQuick: async (amountOrMarketCoin, stakeMarketCoinName, stakeAccountId) => {\n const sender = requireSender(txBlock);\n const stakeAccountIds = await requireStakeAccountIds(builder, txBlock, stakeMarketCoinName, stakeAccountId);\n const createdStakeAccount = [];\n if (stakeAccountIds.length === 0) {\n const stakeAccount = normalMethod.createStakeAccount(stakeMarketCoinName);\n createdStakeAccount.push(stakeAccount);\n }\n\n if (typeof amountOrMarketCoin === 'number') {\n // try stake market coin\n const stakedMarketCoinAmount = await stakeHelper(\n builder,\n txBlock,\n stakeAccountIds.length > 0 ? stakeAccountIds[0] : createdStakeAccount[0],\n stakeMarketCoinName,\n amountOrMarketCoin,\n sender,\n );\n\n // eslint-disable-next-line no-param-reassign\n amountOrMarketCoin -= stakedMarketCoinAmount;\n // no market coin, try sCoin\n if (!stakedMarketCoinAmount) {\n await stakeHelper(\n builder,\n txBlock,\n stakeAccountIds.length > 0 ? stakeAccountIds[0] : createdStakeAccount[0],\n stakeMarketCoinName,\n amountOrMarketCoin,\n sender,\n true,\n );\n }\n } else {\n normalMethod.stake(\n stakeAccountIds.length > 0 ? stakeAccountIds[0] : createdStakeAccount[0],\n amountOrMarketCoin,\n stakeMarketCoinName,\n );\n }\n if (createdStakeAccount.length > 0) {\n txBlock.transferObjects(createdStakeAccount, sender);\n }\n },\n unstakeQuick: async (amount, stakeMarketCoinName, stakeAccountId, returnSCoin) => {\n const stakeAccounts = await requireStakeAccounts(builder, txBlock, stakeMarketCoinName, stakeAccountId);\n const toTransfer: TransactionResult[] = [];\n let amountUnstake = amount;\n // eslint-disable-next-line no-restricted-syntax\n for (const account of stakeAccounts) {\n if (account.staked === 0) {\n continue;\n }\n const amountToUnstake = Math.min(amountUnstake, account.staked);\n const marketCoin = normalMethod.unstake(account.id, amountToUnstake, stakeMarketCoinName);\n\n // convert to new sCoin\n if (returnSCoin) {\n const sCoin = scoinMethod.mintSCoin(stakeMarketCoinName, marketCoin);\n toTransfer.push(sCoin);\n } else {\n toTransfer.push(marketCoin);\n }\n\n amountUnstake -= amountToUnstake;\n if (amount <= 0) {\n break;\n }\n }\n if (toTransfer.length > 0) {\n const mergedCoin = toTransfer[0];\n\n if (toTransfer.length > 1) {\n txBlock.mergeCoins(mergedCoin, toTransfer.slice(1));\n }\n return mergedCoin;\n }\n return undefined;\n },\n claimQuick: async (stakeMarketCoinName, stakeAccountId) => {\n const stakeAccountIds = await requireStakeAccountIds(builder, txBlock, stakeMarketCoinName, stakeAccountId);\n const rewardCoins: TransactionResult[] = [];\n stakeAccountIds.forEach((accountId) => {\n const rewardCoin = normalMethod.claim(accountId, stakeMarketCoinName);\n rewardCoins.push(rewardCoin);\n });\n return rewardCoins;\n },\n };\n};\n","import { TransactionArgument, TransactionObjectArgument } from '@mysten/sui.js/transactions';\nimport { SUI_CLOCK_OBJECT_ID } from '@mysten/sui.js/utils';\n\nimport { requireVeSca } from './borrowIncentiveBuilder';\nimport { SCA_COIN_TYPE } from '../constants';\nimport { GenerateVeScaNormalMethod, GenerateVeScaQuickMethod, SuiAddressArg, SuiObjectArg, VescaIds } from '../types';\nimport {\n requireSender,\n checkLockSca,\n checkExtendLockPeriod,\n checkExtendLockAmount,\n checkRenewExpiredVeSca,\n checkVesca,\n} from '../utils';\n\n/**\n * Generate veSCA normal methods.\n *\n * @param builder - Scallop builder instance.\n * @param txBlock - TxBlock created by SuiKit .\n * @return veSCA normal methods.\n */\nexport const generateNormalVeScaMethod: GenerateVeScaNormalMethod = async ({ builder, txBlock }) => {\n const veScaIds: VescaIds = {\n pkgId: builder.address.get('vesca.id'),\n table: builder.address.get('vesca.table'),\n treasury: builder.address.get('vesca.treasury'),\n config: builder.address.get('vesca.config'),\n };\n\n return {\n lockSca: (scaCoin, unlockAtInSecondTimestamp) =>\n txBlock.moveCall({\n target: `${veScaIds.pkgId}::ve_sca::mint_ve_sca_key`,\n arguments: [\n txBlock.object(veScaIds.config),\n txBlock.object(veScaIds.table),\n txBlock.object(veScaIds.treasury),\n typeof scaCoin === 'string' ? txBlock.pure(scaCoin) : (scaCoin as TransactionArgument),\n txBlock.pure(unlockAtInSecondTimestamp),\n txBlock.object(SUI_CLOCK_OBJECT_ID),\n ],\n }),\n extendLockPeriod: (veScaKey, newUnlockAtInSecondTimestamp) => {\n txBlock.moveCall({\n target: `${veScaIds.pkgId}::ve_sca::extend_lock_period`,\n arguments: [\n txBlock.object(veScaIds.config),\n txBlock.object(veScaKey as string),\n txBlock.object(veScaIds.table),\n txBlock.object(veScaIds.treasury),\n txBlock.pure(newUnlockAtInSecondTimestamp),\n txBlock.object(SUI_CLOCK_OBJECT_ID),\n ],\n });\n },\n extendLockAmount: (veScaKey, scaCoin) => {\n txBlock.moveCall({\n target: `${veScaIds.pkgId}::ve_sca::lock_more_sca`,\n arguments: [\n txBlock.object(veScaIds.config),\n txBlock.object(veScaKey as string),\n txBlock.object(veScaIds.table),\n txBlock.object(veScaIds.treasury),\n typeof scaCoin === 'string' ? txBlock.pure(scaCoin) : (scaCoin as TransactionArgument),\n txBlock.object(SUI_CLOCK_OBJECT_ID),\n ],\n });\n },\n renewExpiredVeSca: (veScaKey, scaCoin, newUnlockAtInSecondTimestamp) => {\n txBlock.moveCall({\n target: `${veScaIds.pkgId}::ve_sca::renew_expired_ve_sca`,\n arguments: [\n txBlock.object(veScaIds.config),\n txBlock.object(veScaKey as string),\n txBlock.object(veScaIds.table),\n txBlock.object(veScaIds.treasury),\n typeof scaCoin === 'string' ? txBlock.pure(scaCoin) : (scaCoin as TransactionArgument),\n txBlock.pure(newUnlockAtInSecondTimestamp),\n txBlock.object(SUI_CLOCK_OBJECT_ID),\n ],\n });\n },\n redeemSca: (veScaKey) =>\n txBlock.moveCall({\n target: `${veScaIds.pkgId}::ve_sca::redeem`,\n arguments: [\n txBlock.object(veScaIds.config),\n txBlock.object(veScaKey as string),\n txBlock.object(veScaIds.table),\n txBlock.object(veScaIds.treasury),\n txBlock.object(SUI_CLOCK_OBJECT_ID),\n ],\n }),\n mintEmptyVeSca: () =>\n txBlock.moveCall({\n target: `${veScaIds.pkgId}::ve_sca::mint_ve_sca_placeholder_key`,\n arguments: [txBlock.object(veScaIds.config), txBlock.object(veScaIds.table)],\n typeArguments: [],\n }),\n };\n};\n\n/**\n * Generate veSCA quick methods.\n *\n * @description\n * The quick methods are the same as the normal methods, but they will automatically\n * help users organize transaction blocks, include get veSca info, and transfer\n * coins to the sender. So, they are all asynchronous methods.\n *\n * @param builder - Scallop builder instance.\n * @param txBlock - TxBlock created by SuiKit .\n * @return veSCA quick methods.\n */\nexport const generateQuickVeScaMethod: GenerateVeScaQuickMethod = async ({ builder, txBlock }) => {\n const normalMethod = await generateNormalVeScaMethod({ builder, txBlock });\n return {\n normalMethod,\n lockScaQuick: async (amountOrCoin, lockPeriodInDays, autoCheck = true) => {\n const sender = requireSender(txBlock);\n const veSca = await requireVeSca(builder, txBlock);\n\n let scaCoin: TransactionObjectArgument | SuiObjectArg | undefined;\n const transferObjects = [];\n if (amountOrCoin !== undefined && typeof amountOrCoin === 'number') {\n const coins = await builder.utils.selectCoinIds(amountOrCoin, SCA_COIN_TYPE, sender);\n const [takeCoin, leftCoin] = builder.utils.takeAmountFromCoins(txBlock, coins, amountOrCoin);\n scaCoin = takeCoin;\n transferObjects.push(leftCoin);\n } else {\n // With amountOrCoin is SuiObjectArg, we cannot validate the minimum sca amount for locking and topup\n scaCoin = amountOrCoin as SuiObjectArg;\n }\n\n const newUnlockAt = builder.utils.getUnlockAt(lockPeriodInDays, veSca?.unlockAt);\n if (autoCheck) {\n checkLockSca(amountOrCoin, lockPeriodInDays, newUnlockAt, veSca?.unlockAt);\n }\n console.log(\n new Date(newUnlockAt * 1000).toLocaleString('en-CA', {\n hour12: true,\n }),\n );\n\n const isInitialLock = !veSca?.unlockAt;\n const isLockExpired = !isInitialLock && veSca.unlockAt * 1000 <= new Date().getTime();\n if (isInitialLock || isLockExpired) {\n if (scaCoin) {\n if (isInitialLock) {\n const veScaKey = normalMethod.lockSca(scaCoin, newUnlockAt);\n transferObjects.push(veScaKey);\n } else {\n // user must withdraw current unlocked SCA first if any\n if (veSca.lockedScaAmount !== 0) {\n const unlockedSca = normalMethod.redeemSca(veSca.keyId);\n transferObjects.push(unlockedSca);\n }\n // enforce renew on expired\n normalMethod.renewExpiredVeSca(veSca.keyId, scaCoin, newUnlockAt);\n }\n }\n } else if (!!scaCoin && !!lockPeriodInDays) {\n normalMethod.extendLockPeriod(veSca.keyId, newUnlockAt);\n normalMethod.extendLockAmount(veSca.keyId, scaCoin);\n } else if (lockPeriodInDays) {\n normalMethod.extendLockPeriod(veSca.keyId, newUnlockAt);\n } else if (scaCoin) {\n normalMethod.extendLockAmount(veSca.keyId, scaCoin);\n }\n\n if (transferObjects.length > 0) {\n txBlock.transferObjects(transferObjects, sender);\n }\n },\n extendLockPeriodQuick: async (lockPeriodInDays: number, veScaKey?: SuiAddressArg, autoCheck = true) => {\n const veSca = await requireVeSca(builder, txBlock, veScaKey);\n\n const newUnlockAt = builder.utils.getUnlockAt(lockPeriodInDays);\n if (autoCheck) {\n checkExtendLockPeriod(lockPeriodInDays, newUnlockAt, veSca?.unlockAt);\n }\n\n if (veSca) {\n normalMethod.extendLockPeriod(veSca.keyId, newUnlockAt);\n }\n },\n extendLockAmountQuick: async (scaAmount: number, veScaKey?: SuiAddressArg, autoCheck = true) => {\n const sender = requireSender(txBlock);\n const veSca = await requireVeSca(builder, txBlock, veScaKey);\n\n if (autoCheck) {\n checkExtendLockAmount(scaAmount, veSca?.unlockAt);\n }\n\n if (veSca) {\n const scaCoins = await builder.utils.selectCoinIds(scaAmount, SCA_COIN_TYPE, sender);\n const [takeCoin, leftCoin] = builder.utils.takeAmountFromCoins(txBlock, scaCoins, scaAmount);\n\n normalMethod.extendLockAmount(veSca.keyId, takeCoin);\n txBlock.transferObjects([leftCoin], sender);\n }\n },\n renewExpiredVeScaQuick: async (\n scaAmount: number,\n lockPeriodInDays: number,\n veScaKey?: SuiAddressArg,\n autoCheck = true,\n ) => {\n const sender = requireSender(txBlock);\n const veSca = await requireVeSca(builder, txBlock, veScaKey);\n\n const newUnlockAt = builder.utils.getUnlockAt(lockPeriodInDays, veSca?.unlockAt);\n if (autoCheck) {\n checkRenewExpiredVeSca(scaAmount, lockPeriodInDays, veSca?.unlockAt);\n }\n\n if (veSca) {\n const transferObjects = [];\n if (veSca.lockedScaAmount !== 0) {\n const unlockedSca = normalMethod.redeemSca(veSca.keyId);\n transferObjects.push(unlockedSca);\n }\n const scaCoins = await builder.utils.selectCoinIds(scaAmount, SCA_COIN_TYPE, sender);\n const [takeCoin, leftCoin] = builder.utils.takeAmountFromCoins(txBlock, scaCoins, scaAmount);\n transferObjects.push(leftCoin);\n\n normalMethod.renewExpiredVeSca(veSca.keyId, takeCoin, newUnlockAt);\n txBlock.transferObjects(transferObjects, sender);\n }\n },\n redeemScaQuick: async (veScaKey?: SuiAddressArg) => {\n const sender = requireSender(txBlock);\n const veSca = await requireVeSca(builder, txBlock, veScaKey);\n\n checkVesca(veSca?.unlockAt);\n\n if (veSca) {\n const sca = normalMethod.redeemSca(veSca.keyId);\n txBlock.transferObjects([sca], sender);\n }\n },\n };\n};\n","import { SuiClient } from '@mysten/sui.js/client';\nimport { TransactionBlock, TransactionObjectInput } from '@mysten/sui.js/transactions';\nimport { normalizeStructTag } from '@mysten/sui.js/utils';\n\n// eslint-disable-next-line import/no-cycle\nimport { DeepBookTxBuilder } from './txbuilder';\nimport { ScallopUtils } from '../../models';\n\ntype ConstructorParams = {\n client: SuiClient;\n currentAddress: string;\n scallopUtils: ScallopUtils;\n accountCap?: string;\n};\n\ntype CoinType = 'sui' | 'wusdc' | 'wusdt' | 'usdc';\ntype SwapParams = {\n tx: TransactionBlock;\n tokenObjectIn: TransactionObjectInput;\n baseCoinName: CoinType;\n quoteCoinName: CoinType;\n};\n\nexport class DeepBookSwap {\n private suiClient: SuiClient;\n\n private scallopUtils: ScallopUtils;\n\n private _clientOrderId = 0;\n\n private _accountCap?: string;\n\n private currentAddress: string;\n\n constructor({ client, currentAddress, accountCap, scallopUtils }: ConstructorParams) {\n this.currentAddress = currentAddress;\n this.suiClient = client;\n this._accountCap = accountCap;\n this.scallopUtils = scallopUtils;\n }\n\n private get clientOrderId() {\n const id = this._clientOrderId;\n this._clientOrderId++;\n return id;\n }\n\n private async accountCap(tx: TransactionBlock) {\n if (this._accountCap) {\n return this._accountCap;\n }\n\n try {\n const { data: accountCapsResponse } = await this.suiClient.getOwnedObjects({\n owner: this.currentAddress,\n filter: {\n StructType: normalizeStructTag('0xdee9::custodian_v2::AccountCap'),\n },\n limit: 1,\n });\n\n if (accountCapsResponse.length === 0 || !accountCapsResponse[0].data) {\n // create new accountCap\n const accountCap = DeepBookTxBuilder.createAccount(tx);\n return accountCap;\n }\n return {\n objectId: accountCapsResponse[0].data.objectId,\n version: accountCapsResponse[0].data.version,\n digest: accountCapsResponse[0].data.digest,\n };\n } catch (e) {\n throw new Error('Failed to create account cap');\n }\n }\n\n public async swapToken({ tokenObjectIn, baseCoinName, quoteCoinName, tx }: SwapParams) {\n const accountCap = await this.accountCap(tx);\n return {\n swapResult: DeepBookTxBuilder.swap(\n tx,\n tokenObjectIn,\n baseCoinName,\n quoteCoinName,\n this.clientOrderId,\n accountCap,\n this.scallopUtils,\n ),\n accountCap,\n };\n }\n}\n","import type { TransactionBlock, TransactionObjectInput, TransactionResult } from '@mysten/sui.js/transactions';\nimport { SUI_CLOCK_OBJECT_ID } from '@mysten/sui.js/utils';\n\nimport { DeepBookContract, DeepBookHelperContract, DeepBookModuleAndMethod, DeepBookPools } from './contract';\n// eslint-disable-next-line import/no-cycle\nimport { ScallopUtils } from '../../models';\n\ntype CoinType = 'sui' | 'wusdc' | 'wusdt' | 'usdc';\n\nconst SUI_CLOCK_OBJECT = {\n objectId: SUI_CLOCK_OBJECT_ID,\n initialSharedVersion: '1',\n mutable: false,\n};\n\nconst getDeepBookPool = (coinAName: CoinType, coinBName: CoinType) => {\n if (coinAName === 'sui') {\n switch (coinBName) {\n case 'wusdc':\n return {\n pool: DeepBookPools.pools.sui2usdc,\n aToB: true,\n };\n default:\n throw new Error(`Invalid coin pair: ${coinAName} and ${coinBName}`);\n }\n } else if (coinAName === 'wusdc') {\n switch (coinBName) {\n case 'sui':\n return {\n pool: DeepBookPools.pools.sui2usdc,\n aToB: false,\n };\n case 'wusdt':\n return {\n pool: DeepBookPools.pools.usdt2usdc,\n aToB: false,\n };\n case 'usdc':\n return {\n pool: DeepBookPools.pools.wusdc2usdc,\n aToB: true,\n };\n default:\n throw new Error(`Invalid coin pair: ${coinAName} and ${coinBName}`);\n }\n } else if (coinAName === 'wusdt') {\n switch (coinBName) {\n case 'wusdc':\n return {\n pool: DeepBookPools.pools.usdt2usdc,\n aToB: true,\n };\n default:\n throw new Error(`Invalid coin pair: ${coinAName} and ${coinBName}`);\n }\n } else {\n throw new Error(`Invalid coin pair: ${coinAName} and ${coinBName}`);\n }\n};\n\nexport const DeepBookTxBuilder = {\n createAccount: (tx: TransactionBlock) =>\n tx.moveCall({\n target: `${DeepBookContract.id}::${DeepBookModuleAndMethod.clob_v2.create_account}`,\n arguments: [],\n typeArguments: [],\n }),\n swap: (\n tx: TransactionBlock,\n tokenInObject: TransactionObjectInput,\n baseCoinName: CoinType,\n quoteCoinName: CoinType,\n clientOrderId: number,\n accountCap: TransactionResult | string | { digest: string; objectId: string; version: string | number | bigint },\n scallopUtils: ScallopUtils,\n ) => {\n // determine the pool\n const { pool, aToB } = getDeepBookPool(baseCoinName, quoteCoinName);\n const coinAType = scallopUtils.parseCoinType(baseCoinName);\n const coinBType = scallopUtils.parseCoinType(quoteCoinName);\n const parsedAccountCap =\n // eslint-disable-next-line no-nested-ternary\n typeof accountCap === 'string'\n ? tx.object(accountCap)\n : 'objectId' in accountCap\n ? tx.objectRef(accountCap)\n : tx.object(accountCap);\n if (!pool) {\n throw new Error(`Deepbook: No pool found for ${baseCoinName} to ${quoteCoinName}`);\n }\n if (aToB) {\n return tx.moveCall({\n target: `${DeepBookHelperContract.id}::deepbook::deepbook_base_for_quote`,\n arguments: [\n tx.sharedObjectRef(pool.object),\n tx.pure(clientOrderId),\n parsedAccountCap,\n tx.object(tokenInObject),\n tx.sharedObjectRef(SUI_CLOCK_OBJECT),\n tx.pure(pool.lotsize),\n ],\n typeArguments: [coinAType, coinBType],\n });\n }\n return tx.moveCall({\n target: `${DeepBookHelperContract.id}::deepbook::deepbook_quote_for_base`,\n arguments: [\n tx.sharedObjectRef(pool.object),\n tx.pure(clientOrderId),\n parsedAccountCap,\n tx.sharedObjectRef(SUI_CLOCK_OBJECT),\n tx.object(tokenInObject),\n tx.pure(pool.lotsize),\n ],\n typeArguments: [coinBType, coinAType],\n });\n },\n};\n","type SharedObjectRef = {\n objectId: string;\n initialSharedVersion: string;\n mutable: boolean;\n};\nexport const DeepBookPools = {\n id: '0x000000000000000000000000000000000000000000000000000000000000dee9',\n pools: {\n sui2usdc: {\n object: {\n objectId: '0x4405b50d791fd3346754e8171aaab6bc2ed26c2c46efdd033c14b30ae507ac33',\n initialSharedVersion: '32079148',\n mutable: true,\n } as SharedObjectRef,\n lotsize: 100000000,\n },\n usdt2usdc: {\n object: {\n objectId: '0xd1f0a9baacc1864ab19534e2d4c5d6c14f2e071a1f075e8e7f9d51f2c17dc238',\n initialSharedVersion: '32079148',\n mutable: true,\n } as SharedObjectRef,\n lotsize: 100000,\n },\n wusdc2usdc: {\n object: {\n objectId: '0x39f2f7c126189b9b5cda6b770ab34031dde22307d19842e95ab576873c77fa14',\n initialSharedVersion: '82838334',\n mutable: true,\n } as SharedObjectRef,\n lotsize: 100000,\n },\n },\n} as const;\n\nexport const DeepBookContract = {\n id: '0x000000000000000000000000000000000000000000000000000000000000dee9',\n};\n\nexport const DeepBookHelperContract = {\n id: '0x2c6c36393db063a9534885d22a47caead720272475336470736be28f119971f3',\n};\n\nexport const DeepBookModuleAndMethod = {\n clob_v2: {\n swap_exact_quote_for_base: 'clob_v2::swap_exact_quote_for_base' as `${string}::${string}`,\n swap_exact_base_for_quote: 'clob_v2::swap_exact_base_for_quote' as `${string}::${string}`,\n create_account: 'clob_v2::create_account' as `${string}::${string}`,\n },\n};\n","import { ScallopAddress } from './scallopAddress';\nimport { ScallopBuilder } from './scallopBuilder';\nimport { ScallopClient } from './scallopClient';\nimport { ScallopQuery } from './scallopQuery';\nimport { ScallopUtils } from './scallopUtils';\nimport { ADDRESSES_ID } from '../constants';\nimport type { ScallopParams } from '../types';\n\n/**\n * @argument params - The parameters for the Scallop instance.\n * @argument cacheOptions - The cache options for the QueryClient.\n *\n * @description\n * The main instance that controls interaction with the Scallop contract.\n *\n * @example\n * ```typescript\n * const sdk = new Scallop(<parameters>);\n * const scallopAddress = await sdk.getScallopAddress();\n * const scallopBuilder = await sdk.createScallopBuilder();\n * const scallopClient = await sdk.createScallopClient();\n * const scallopIndexer= await sdk.createScallopIndexer();\n * const scallopUtils= await sdk.createScallopUtils();\n * ```\n */\nexport class Scallop {\n public params: ScallopParams;\n\n public client: ScallopClient;\n\n public builder: ScallopBuilder;\n\n public query: ScallopQuery;\n\n public utils: ScallopUtils;\n\n public address: ScallopAddress;\n\n public constructor(params: ScallopParams) {\n this.params = params;\n this.address = params.address;\n }\n\n public async init() {\n if (!this.address) {\n this.address = new ScallopAddress({\n id: ADDRESSES_ID,\n });\n }\n await this.address.read();\n this.client = new ScallopClient(this.params, this.address);\n\n const { builder, query, utils } = this.client;\n this.builder = builder;\n this.query = query;\n this.utils = utils;\n }\n}\n","import { TransactionType } from '@msafe/sui3-utils';\nimport { SuiClient } from '@mysten/sui/client';\nimport { Transaction } from '@mysten/sui/transactions';\nimport { IdentifierString, WalletAccount } from '@mysten/wallet-standard';\nimport { LENDING_MARKET_ID, LENDING_MARKET_TYPE, SuilendClient } from '@suilend/sdk';\nimport { phantom } from '@suilend/sdk/_generated/_framework/reified';\nimport { LendingMarket, ObligationOwnerCap } from '@suilend/sdk/_generated/suilend/lending-market/structs';\nimport { Obligation } from '@suilend/sdk/_generated/suilend/obligation/structs';\n\nimport { IAppHelperInternal } from '@/apps/interface/sui';\nimport { SuiNetworks } from '@/types';\n\nimport { Decoder } from './decoder';\nimport { BorrowIntention, BorrowIntentionData } from './intentions/borrow';\n// import { ClaimRewardsIntention, ClaimRewardsIntentionData } from './intentions/claimRewards';\nimport { DepositIntention, DepositIntentionData } from './intentions/deposit';\nimport { RepayIntention, RepayIntentionData } from './intentions/repay';\nimport { WithdrawIntention, WithdrawIntentionData } from './intentions/withdraw';\nimport { TransactionSubType } from './types';\n\nconst getSuilendClient = async (suiClient: SuiClient) =>\n SuilendClient.initializeWithLendingMarket(\n await LendingMarket.fetch(suiClient as any, phantom(LENDING_MARKET_TYPE), LENDING_MARKET_ID),\n suiClient as any,\n );\n\nconst getObligationOwnerCaps = async (suiClient: SuiClient, account: WalletAccount, suilendClient: SuilendClient) =>\n SuilendClient.getObligationOwnerCaps(account.address, suilendClient.lendingMarket.$typeArgs, suiClient as any);\n\nconst getObligations = async (\n suiClient: SuiClient,\n suilendClient: SuilendClient,\n obligationOwnerCaps: ObligationOwnerCap<string>[],\n) =>\n Promise.all(\n obligationOwnerCaps.map((ownerCap) =>\n SuilendClient.getObligation(ownerCap.obligationId, suilendClient.lendingMarket.$typeArgs, suiClient as any),\n ),\n );\n\nexport type SuilendIntention = DepositIntention | WithdrawIntention | BorrowIntention | RepayIntention;\n// | ClaimRewardsIntention;\n\nexport type SuilendIntentionData =\n | DepositIntentionData\n | WithdrawIntentionData\n | BorrowIntentionData\n | RepayIntentionData;\n// | ClaimRewardsIntentionData;\n\nexport type IntentionInput = {\n network: SuiNetworks;\n suiClient: SuiClient;\n account: WalletAccount;\n suilendClient: SuilendClient;\n obligationOwnerCaps: ObligationOwnerCap<string>[];\n obligations: Obligation<string>[];\n};\n\nexport class SuilendAppHelper implements IAppHelperInternal<SuilendIntentionData> {\n application = 'Suilend';\n\n supportSDK = '@mysten/sui' as const;\n\n private suilendClient: SuilendClient | undefined;\n\n private obligationOwnerCaps: ObligationOwnerCap<string>[] | undefined;\n\n private obligations: Obligation<string>[] | undefined;\n\n async deserialize(input: {\n transaction: Transaction;\n chain: IdentifierString;\n network: SuiNetworks;\n suiClient: SuiClient;\n account: WalletAccount;\n appContext?: any;\n }): Promise<{ txType: TransactionType; txSubType: string; intentionData: SuilendIntentionData }> {\n const { transaction, suiClient, account } = input;\n\n if (!this.suilendClient) {\n this.suilendClient = await getSuilendClient(suiClient);\n }\n if (!this.obligationOwnerCaps) {\n this.obligationOwnerCaps = await getObligationOwnerCaps(suiClient, account, this.suilendClient);\n }\n if (!this.obligations) {\n this.obligations = await getObligations(suiClient, this.suilendClient, this.obligationOwnerCaps);\n }\n\n const digest = await transaction.getDigest();\n const transactionWithEvents = await suiClient.getTransactionBlock({\n digest,\n options: {\n showEvents: true,\n },\n });\n\n const decoder = new Decoder(transaction, transactionWithEvents.events);\n const result = decoder.decode();\n\n return {\n txType: TransactionType.Other,\n txSubType: result.type,\n intentionData: result.intentionData,\n };\n }\n\n async build(input: {\n network: SuiNetworks;\n txType: TransactionType;\n txSubType: string;\n intentionData: SuilendIntentionData;\n suiClient: SuiClient;\n account: WalletAccount;\n }): Promise<Transaction> {\n const { network, txSubType, intentionData, suiClient, account } = input;\n\n if (!this.suilendClient) {\n this.suilendClient = await getSuilendClient(suiClient);\n }\n if (!this.obligationOwnerCaps) {\n this.obligationOwnerCaps = await getObligationOwnerCaps(suiClient, account, this.suilendClient);\n }\n if (!this.obligations) {\n this.obligations = await getObligations(suiClient, this.suilendClient, this.obligationOwnerCaps);\n }\n\n let intention: SuilendIntention;\n switch (txSubType) {\n case TransactionSubType.DEPOSIT:\n intention = DepositIntention.fromData(intentionData as DepositIntentionData);\n break;\n case TransactionSubType.WITHDRAW:\n intention = WithdrawIntention.fromData(intentionData as WithdrawIntentionData);\n break;\n case TransactionSubType.BORROW:\n intention = BorrowIntention.fromData(intentionData as BorrowIntentionData);\n break;\n case TransactionSubType.REPAY:\n intention = RepayIntention.fromData(intentionData as RepayIntentionData);\n break;\n // case TransactionSubType.CLAIM_REWARDS:\n // intention = ClaimRewardsIntention.fromData(intentionData as ClaimRewardsIntentionData);\n // break;\n default:\n throw new Error('not implemented');\n }\n return intention.build({\n network,\n suiClient,\n account,\n suilendClient: this.suilendClient,\n obligationOwnerCaps: this.obligationOwnerCaps,\n obligations: this.obligations,\n } as IntentionInput);\n }\n}\n","import { TransactionType } from '@msafe/sui3-utils';\nimport { Transaction } from '@mysten/sui/transactions';\nimport { SuiEvent } from '@mysten/sui.js/client';\n\nimport { SuilendIntentionData } from './helper';\nimport { BorrowIntentionData } from './intentions/borrow';\nimport { DepositIntentionData } from './intentions/deposit';\nimport { RepayIntentionData } from './intentions/repay';\nimport { WithdrawIntentionData } from './intentions/withdraw';\nimport { TransactionSubType } from './types';\n\nconst PACKAGE_ID = '0x93b70b8e21d77f695507558839715d900d05e0ee54acf25d176a179112001d7a';\nconst MODULE = 'lending_market';\n\ntype DecodeResult = {\n txType: TransactionType;\n type: TransactionSubType;\n intentionData: SuilendIntentionData;\n};\n\nexport class Decoder {\n constructor(\n public readonly transaction: Transaction,\n public readonly transactionEvents: SuiEvent[],\n ) {}\n\n decode() {\n if (this.isDepositTransaction()) {\n return this.decodeDeposit();\n }\n if (this.isWithdrawTransaction()) {\n return this.decodeWithdraw();\n }\n if (this.isBorrowTransaction()) {\n return this.decodeBorrow();\n }\n if (this.isRepayTransaction()) {\n return this.decodeRepay();\n }\n\n throw new Error(`Unknown transaction type`);\n }\n\n private get commands() {\n return this.transaction\n .getData()\n .commands.filter((command) => command.MoveCall.package === PACKAGE_ID && command.MoveCall.module === MODULE);\n }\n\n private getMoveCallCommand(fn: string) {\n return this.commands.find((command) => command.$kind === 'MoveCall' && command.MoveCall.function === fn);\n }\n\n private getSplitCoinsCommands(indexFilter: (index: number) => boolean = () => true) {\n return this.commands.filter((command, index) => command.$kind === 'SplitCoins' && indexFilter(index));\n }\n\n // is*\n private isDepositTransaction() {\n return (\n !!this.getMoveCallCommand('deposit_liquidity_and_mint_ctokens') &&\n !!this.getMoveCallCommand('deposit_ctokens_into_obligation')\n );\n }\n\n private isWithdrawTransaction() {\n return (\n !!this.getMoveCallCommand('withdraw_ctokens') &&\n !!this.getMoveCallCommand('redeem_ctokens_and_withdraw_liquidity')\n );\n }\n\n private isBorrowTransaction() {\n return !!this.getMoveCallCommand('borrow');\n }\n\n private isRepayTransaction() {\n return !!this.getMoveCallCommand('repay');\n }\n\n // decode*\n private decodeDeposit(): DecodeResult {\n const commands = {\n splitCoins: this.getSplitCoinsCommands()[0],\n deposit_liquidity_and_mint_ctokens: this.getMoveCallCommand('deposit_liquidity_and_mint_ctokens'),\n };\n\n const coinType = commands.deposit_liquidity_and_mint_ctokens.MoveCall.typeArguments[1];\n const value = (commands.splitCoins.SplitCoins.amounts[0] as any).value as string;\n console.log('Decoder.decodeDeposit', coinType, value);\n\n return {\n txType: TransactionType.Other,\n type: TransactionSubType.DEPOSIT,\n intentionData: {\n coinType,\n value,\n } as DepositIntentionData,\n };\n }\n\n private decodeWithdraw(): DecodeResult {\n const commands = {\n withdraw_ctokens: this.getMoveCallCommand('withdraw_ctokens'),\n };\n const events = {\n redeem: this.transactionEvents.find((event) => event.type.endsWith('lending_market::RedeemEvent')),\n };\n\n const coinType = commands.withdraw_ctokens.MoveCall.typeArguments[1];\n const value = (events.redeem.parsedJson as any).liquidity_amount as string;\n console.log('Decoder.decodeWithdraw', coinType, value);\n\n return {\n txType: TransactionType.Other,\n type: TransactionSubType.WITHDRAW,\n intentionData: {\n coinType,\n value,\n } as WithdrawIntentionData,\n };\n }\n\n private decodeBorrow(): DecodeResult {\n const commands = {\n borrow: this.getMoveCallCommand('borrow'),\n };\n\n const coinType = commands.borrow.MoveCall.typeArguments[1];\n const value = (commands.borrow.MoveCall.arguments[4] as any).value as string;\n console.log('Decoder.decodeBorrow', coinType, value);\n\n return {\n txType: TransactionType.Other,\n type: TransactionSubType.BORROW,\n intentionData: {\n coinType,\n value,\n } as BorrowIntentionData,\n };\n }\n\n private decodeRepay(): DecodeResult {\n const commands = {\n splitCoins: this.getSplitCoinsCommands()[0],\n repay: this.getMoveCallCommand('repay'),\n };\n\n const coinType = commands.repay.MoveCall.typeArguments[1];\n const value = (commands.splitCoins.SplitCoins.amounts[0] as any).value as string;\n console.log('Decoder.decodeRepay', coinType, value);\n\n return {\n txType: TransactionType.Other,\n type: TransactionSubType.REPAY,\n intentionData: {\n coinType,\n value,\n } as RepayIntentionData,\n };\n }\n}\n","import { TransactionType } from '@msafe/sui3-utils';\nimport { Transaction } from '@mysten/sui/transactions';\n\nimport { TransactionSubType } from '../types';\nimport { SuilendBaseIntention } from './suilendBaseIntention';\nimport { IntentionInput } from '../helper';\n\nexport interface BorrowIntentionData {\n coinType: string;\n value: string;\n}\n\nexport class BorrowIntention extends SuilendBaseIntention<BorrowIntentionData> {\n txType: TransactionType.Other;\n\n txSubType: TransactionSubType.BORROW;\n\n constructor(public readonly data: BorrowIntentionData) {\n super(data);\n }\n\n async build(input: IntentionInput): Promise<Transaction> {\n const { suiClient, account, suilendClient, obligationOwnerCaps, obligations } = input;\n console.log('BorrowIntention.build', suiClient, account, suilendClient, obligationOwnerCaps, obligations);\n\n const transaction = new Transaction();\n await suilendClient.borrowFromObligation(\n account.address,\n obligationOwnerCaps[0].id,\n obligations[0].id,\n this.data.coinType,\n this.data.value,\n transaction as any,\n );\n\n return transaction;\n }\n\n static fromData(data: BorrowIntentionData) {\n console.log('BorrowIntention.fromData', data);\n return new BorrowIntention(data);\n }\n}\n","import { TransactionType } from '@msafe/sui3-utils';\nimport { Transaction } from '@mysten/sui/transactions';\nimport sortKeys from 'sort-keys-recursive';\n\nimport { BaseIntention } from '@/apps/interface/sui';\n\nimport { IntentionInput } from '../helper';\n\nexport abstract class SuilendBaseIntention<D> implements BaseIntention<D> {\n abstract txType: TransactionType;\n\n abstract txSubType: string;\n\n protected constructor(public readonly data: D) {}\n\n abstract build(input: IntentionInput): Promise<Transaction>;\n\n serialize() {\n return JSON.stringify(sortKeys(this.data));\n }\n}\n","import { TransactionType } from '@msafe/sui3-utils';\nimport { Transaction } from '@mysten/sui/transactions';\n\nimport { TransactionSubType } from '../types';\nimport { SuilendBaseIntention } from './suilendBaseIntention';\nimport { IntentionInput } from '../helper';\n\nexport interface DepositIntentionData {\n coinType: string;\n value: string;\n}\n\nexport class DepositIntention extends SuilendBaseIntention<DepositIntentionData> {\n txType: TransactionType.Other;\n\n txSubType: TransactionSubType.DEPOSIT;\n\n constructor(public readonly data: DepositIntentionData) {\n super(data);\n }\n\n async build(input: IntentionInput): Promise<Transaction> {\n const { suiClient, account, suilendClient, obligationOwnerCaps } = input;\n console.log('DepositIntention.build', suiClient, account, suilendClient, obligationOwnerCaps);\n\n const transaction = new Transaction();\n await suilendClient.depositIntoObligation(\n account.address,\n this.data.coinType,\n this.data.value,\n transaction as any,\n obligationOwnerCaps[0]?.id,\n );\n\n return transaction;\n }\n\n static fromData(data: DepositIntentionData) {\n console.log('DepositIntention.fromData', data);\n return new DepositIntention(data);\n }\n}\n","import { TransactionType } from '@msafe/sui3-utils';\nimport { Transaction } from '@mysten/sui/transactions';\n\nimport { TransactionSubType } from '../types';\nimport { SuilendBaseIntention } from './suilendBaseIntention';\nimport { IntentionInput } from '../helper';\n\nexport interface RepayIntentionData {\n coinType: string;\n value: string;\n}\n\nexport class RepayIntention extends SuilendBaseIntention<RepayIntentionData> {\n txType: TransactionType.Other;\n\n txSubType: TransactionSubType.REPAY;\n\n constructor(public readonly data: RepayIntentionData) {\n super(data);\n }\n\n async build(input: IntentionInput): Promise<Transaction> {\n const { suiClient, account, suilendClient, obligationOwnerCaps, obligations } = input;\n console.log('RepayIntention.build', suiClient, account, suilendClient, obligationOwnerCaps, obligations);\n\n const transaction = new Transaction();\n await suilendClient.repayIntoObligation(\n account.address,\n obligations[0].id,\n this.data.coinType,\n this.data.value,\n transaction as any,\n );\n\n return transaction;\n }\n\n static fromData(data: RepayIntentionData) {\n console.log('RepayIntention.fromData', data);\n return new RepayIntention(data);\n }\n}\n","import { TransactionType } from '@msafe/sui3-utils';\nimport { Transaction } from '@mysten/sui/transactions';\n\nimport { TransactionSubType } from '../types';\nimport { SuilendBaseIntention } from './suilendBaseIntention';\nimport { IntentionInput } from '../helper';\n\nexport interface WithdrawIntentionData {\n coinType: string;\n value: string;\n}\n\nexport class WithdrawIntention extends SuilendBaseIntention<WithdrawIntentionData> {\n txType: TransactionType.Other;\n\n txSubType: TransactionSubType.WITHDRAW;\n\n constructor(public readonly data: WithdrawIntentionData) {\n super(data);\n }\n\n async build(input: IntentionInput): Promise<Transaction> {\n const { suiClient, account, suilendClient, obligationOwnerCaps, obligations } = input;\n console.log('WithdrawIntention.build', suiClient, account, suilendClient, obligationOwnerCaps, obligations);\n\n const transaction = new Transaction();\n await suilendClient.withdrawFromObligation(\n account.address,\n obligationOwnerCaps[0].id,\n obligations[0].id,\n this.data.coinType,\n this.data.value,\n transaction as any,\n );\n\n return transaction;\n }\n\n static fromData(data: WithdrawIntentionData) {\n console.log('WithdrawIntention.fromData', data);\n return new WithdrawIntention(data);\n }\n}\n","import { TransactionType } from '@msafe/sui3-utils';\nimport { SuiClient } from '@mysten/sui.js/client';\nimport { TransactionBlock } from '@mysten/sui.js/transactions';\nimport { SuiSignTransactionBlockInput, WalletAccount } from '@mysten/wallet-standard';\nimport { Network, TurbosSdk } from 'turbos-clmm-sdk';\n\n// eslint-disable-next-line import/no-cycle\nimport { IAppHelperInternalLegacy } from '@/apps/interface/sui-js';\n\nimport { Decoder } from './decoder';\nimport { AddLiquidityIntention, AddLiquidityIntentionData } from './intentions/add-liquidity';\nimport { BurnIntention, BurnIntentionData } from './intentions/burn';\nimport { CollectFeeIntention, CollectFeeIntentionData } from './intentions/collect-fee';\nimport { CollectRewardIntention, CollectRewardIntentionData } from './intentions/collect-reward';\nimport { CreatePoolIntention, CreatePoolIntentionData } from './intentions/create-pool';\nimport { DecreaseLiquidityIntention, DecreaseLiquidityIntentionData } from './intentions/decrease-liquidity';\nimport { IncreaseLiquidityIntention, IncreaseLiquidityIntentionData } from './intentions/increase-liquidity';\nimport { PrixClaimIntention, PrixClaimIntentionData } from './intentions/prix-claim';\nimport { PrixJoinIntention, PrixJoinIntentionData } from './intentions/prix-join';\nimport { RemoveLiquidityIntention, RemoveLiquidityIntentionData } from './intentions/remove-liquidity';\nimport { SwapIntention, SwapIntentionData } from './intentions/swap';\nimport {\n SwapExactBaseForQuoteIntention,\n SwapExactBaseForQuoteIntentionData,\n} from './intentions/swap-exact-base-for-quote';\nimport {\n SwapExactQuoteForBaseIntention,\n SwapExactQuoteForBaseIntentionData,\n} from './intentions/swap-exact-quote-for-base';\nimport { SuiNetworks, TransactionSubType } from './types';\n\nexport type TURBOSIntention =\n | CreatePoolIntention\n | AddLiquidityIntention\n | IncreaseLiquidityIntention\n | DecreaseLiquidityIntention\n | CollectFeeIntention\n | CollectRewardIntention\n | RemoveLiquidityIntention\n | BurnIntention\n | SwapIntention\n | PrixClaimIntention\n | PrixJoinIntention\n | SwapExactQuoteForBaseIntention\n | SwapExactBaseForQuoteIntention;\n\nexport type TURBOSIntentionData =\n | CreatePoolIntentionData\n | AddLiquidityIntentionData\n | IncreaseLiquidityIntentionData\n | DecreaseLiquidityIntentionData\n | CollectFeeIntentionData\n | CollectRewardIntentionData\n | RemoveLiquidityIntentionData\n | BurnIntentionData\n | SwapIntentionData\n | PrixJoinIntentionData\n | PrixClaimIntentionData\n | SwapExactQuoteForBaseIntentionData\n | SwapExactBaseForQuoteIntentionData;\n\nexport class TURBOSAppHelper implements IAppHelperInternalLegacy<TURBOSIntentionData> {\n application = 'turbos';\n\n supportSDK = '@mysten/sui.js' as const;\n\n async deserialize(\n input: SuiSignTransactionBlockInput & { network: SuiNetworks; suiClient: SuiClient; account: WalletAccount } & {\n action?: string;\n txbParams?: any;\n },\n ): Promise<{\n txType: TransactionType;\n txSubType: TransactionSubType;\n intentionData: TURBOSIntentionData;\n }> {\n const turbosSdk = new TurbosSdk(input.network.replace('sui:', '') as Network, input.suiClient);\n const contract = await turbosSdk.contract.getConfig();\n const { transactionBlock, account } = input;\n console.log(input, 'input');\n const decoder = new Decoder(transactionBlock, turbosSdk, contract);\n const result = await decoder.decode(account.address);\n return {\n txType: TransactionType.Other,\n txSubType: result.type,\n intentionData: result.intentionData,\n };\n }\n\n async build(input: {\n intentionData: TURBOSIntentionData;\n txType: TransactionType;\n txSubType: string;\n suiClient: SuiClient;\n account: WalletAccount;\n network: SuiNetworks;\n }): Promise<TransactionBlock> {\n const { suiClient, account, network } = input;\n let intention: TURBOSIntention;\n console.log(input.intentionData, 'intentionData');\n switch (input.txSubType) {\n case TransactionSubType.CreatePool:\n intention = CreatePoolIntention.fromData(input.intentionData as CreatePoolIntentionData);\n break;\n case TransactionSubType.AddLiquidity:\n intention = AddLiquidityIntention.fromData(input.intentionData as AddLiquidityIntentionData);\n break;\n case TransactionSubType.IncreaseLiquidity:\n intention = IncreaseLiquidityIntention.fromData(input.intentionData as IncreaseLiquidityIntentionData);\n break;\n case TransactionSubType.DecreaseLiquidity:\n intention = DecreaseLiquidityIntention.fromData(input.intentionData as DecreaseLiquidityIntentionData);\n break;\n case TransactionSubType.RemoveLiquidity:\n intention = RemoveLiquidityIntention.fromData(input.intentionData as RemoveLiquidityIntentionData);\n break;\n case TransactionSubType.CollectFee:\n intention = CollectFeeIntention.fromData(input.intentionData as CollectFeeIntentionData);\n break;\n case TransactionSubType.CollectReward:\n intention = CollectRewardIntention.fromData(input.intentionData as CollectRewardIntentionData);\n break;\n case TransactionSubType.Burn:\n intention = BurnIntention.fromData(input.intentionData as BurnIntentionData);\n break;\n case TransactionSubType.Swap:\n intention = SwapIntention.fromData(input.intentionData as SwapIntentionData);\n break;\n case TransactionSubType.PrixJoin:\n intention = PrixJoinIntention.fromData(input.intentionData as PrixJoinIntentionData);\n break;\n case TransactionSubType.PrixClaim:\n intention = PrixClaimIntention.fromData(input.intentionData as PrixClaimIntentionData);\n break;\n case TransactionSubType.SwapExactBaseForQuote:\n intention = SwapExactBaseForQuoteIntention.fromData(input.intentionData as SwapExactBaseForQuoteIntentionData);\n break;\n case TransactionSubType.SwapExactQuoteForBase:\n intention = SwapExactQuoteForBaseIntention.fromData(input.intentionData as SwapExactQuoteForBaseIntentionData);\n break;\n default:\n throw new Error('not implemented');\n }\n return intention.build({ suiClient, account, network });\n }\n}\n","import { TransactionType } from '@msafe/sui3-utils';\nimport { bcs } from '@mysten/sui.js/bcs';\nimport { MoveCallTransaction } from '@mysten/sui.js/dist/cjs/transactions';\nimport { TransactionBlock, TransactionBlockInput } from '@mysten/sui.js/transactions';\nimport { normalizeStructTag, normalizeSuiAddress } from '@mysten/sui.js/utils';\nimport { BN, Contract, TurbosSdk } from 'turbos-clmm-sdk';\n\nimport { deepbookConfig, prixConfig } from './config';\n// eslint-disable-next-line import/no-cycle\nimport { TURBOSIntentionData } from './helper';\nimport { TransactionSubType } from './types';\n\ntype DecodeResult = {\n txType: TransactionType;\n type: TransactionSubType;\n intentionData: TURBOSIntentionData;\n};\n\nconst getAtoB = (layer: 0 | 1, target: string, swap1Layer: string[], swap2Layer: string[]): boolean[] => {\n if (layer === 1) {\n const index = swap2Layer.findIndex((item) => item === target);\n switch (index) {\n case 0:\n return [true, true];\n case 1:\n return [true, false];\n case 2:\n return [false, true];\n case 3:\n return [false, false];\n default:\n throw new Error(`not target: ${target}`);\n }\n }\n const index = swap1Layer.findIndex((item) => item === target);\n switch (index) {\n case 0:\n return [true];\n case 1:\n return [false];\n default:\n throw new Error(`not target: ${target}`);\n }\n};\n\nexport class Decoder {\n constructor(\n public readonly txb: TransactionBlock,\n public readonly turbosSdk: TurbosSdk,\n public readonly config: Contract.Config,\n ) {}\n\n private get transactions() {\n return this.txb.blockData.transactions;\n }\n\n private get swap1Layer() {\n return [`${this.config.PackageId}::swap_router::swap_a_b`, `${this.config.PackageId}::swap_router::swap_b_a`];\n }\n\n private get swap2Layer() {\n return [\n `${this.config.PackageId}::swap_router::swap_a_b_b_c`,\n `${this.config.PackageId}::swap_router::swap_a_b_c_b`,\n `${this.config.PackageId}::swap_router::swap_b_a_b_c`,\n `${this.config.PackageId}::swap_router::swap_b_a_c_b`,\n ];\n }\n\n async decode(address: string) {\n if (this.isSwapTransaction()) {\n return await this.decodeSwap();\n }\n\n if (this.isAddLiquidityTransaction()) {\n return this.decodeAddLiquidity();\n }\n\n if (this.isIncreaseLiquidityTransaction()) {\n return this.decodeIncreaseLiquidity(address);\n }\n\n if (this.isRemoveLiquidityTransaction()) {\n return this.decodeRemoveLiquidity(address);\n }\n\n if (this.isDecreaseLiquidityTransaction()) {\n return this.decodeDecreaseLiquidity(address);\n }\n\n if (this.isCollectFeeTransaction()) {\n return this.decodeCollectFee();\n }\n\n if (this.isCollectRewardTransaction()) {\n return this.decodeCollectReward();\n }\n\n if (this.isBurnTransaction()) {\n return this.decodeBurn();\n }\n\n if (this.isPrixClaimTransaction()) {\n return this.decodePrixClaim();\n }\n\n if (this.isPrixJoinTransaction()) {\n return this.decodePrixJoin();\n }\n\n if (this.isSwapExactBaseForQuoteTransaction()) {\n return this.decodeSwapExactBaseForQuote();\n }\n\n if (this.isSwapExactQuoteForBaseTransaction()) {\n return this.decodeSwapExactQuoteForBase();\n }\n\n throw new Error(`Unknown transaction type`);\n }\n\n private getMoveCallTransaction(target: string) {\n return this.transactions.find((trans) => trans.kind === 'MoveCall' && trans.target === target);\n }\n\n private getMoveCallsTransaction(targets: string[]) {\n return targets.every((target) =>\n this.transactions.find((trans) => trans.kind === 'MoveCall' && trans.target === target),\n );\n }\n\n private getSwapMoveCallTransaction(targets: string[]) {\n return this.transactions.find((trans) => trans.kind === 'MoveCall' && targets.includes(trans.target));\n }\n\n private isSwapTransaction() {\n return !!this.getSwapMoveCallTransaction([...this.swap1Layer, ...this.swap2Layer]);\n }\n\n private isAddLiquidityTransaction() {\n return !!this.getMoveCallTransaction(`${this.config.PackageId}::position_manager::mint`);\n }\n\n private isIncreaseLiquidityTransaction() {\n return !!this.getMoveCallTransaction(`${this.config.PackageId}::position_manager::increase_liquidity`);\n }\n\n private isDecreaseLiquidityTransaction() {\n return !!this.getMoveCallTransaction(`${this.config.PackageId}::position_manager::decrease_liquidity`);\n }\n\n private isCollectFeeTransaction() {\n return !!this.getMoveCallTransaction(`${this.config.PackageId}::position_manager::collect`);\n }\n\n private isCollectRewardTransaction() {\n return !!this.getMoveCallTransaction(`${this.config.PackageId}::position_manager::collect_reward`);\n }\n\n private isBurnTransaction() {\n return !!this.getMoveCallTransaction(`${this.config.PackageId}::position_manager::burn`);\n }\n\n private isPrixJoinTransaction() {\n return !!this.getMoveCallTransaction(`${prixConfig.PackageId}::claim::join`);\n }\n\n private isPrixClaimTransaction() {\n return !!this.getMoveCallTransaction(`${prixConfig.PackageId}::claim::claim`);\n }\n\n private isRemoveLiquidityTransaction() {\n return !!this.getMoveCallsTransaction([\n `${this.config.PackageId}::position_manager::decrease_liquidity`,\n `${this.config.PackageId}::position_manager::burn`,\n ]);\n }\n\n private isSwapExactBaseForQuoteTransaction() {\n return !!this.getMoveCallTransaction(`${deepbookConfig.PackageId}::clob_v2::swap_exact_base_for_quote`);\n }\n\n private isSwapExactQuoteForBaseTransaction() {\n return !!this.getMoveCallTransaction(`${deepbookConfig.PackageId}::clob_v2::swap_exact_quote_for_base`);\n }\n\n private async decodeSwap(): Promise<DecodeResult> {\n const moveCall = this.transactions.find((trans) => trans.kind === 'MoveCall') as MoveCallTransaction;\n let layer: 0 | 1 = 0;\n if (this.swap2Layer.includes(moveCall.target)) {\n layer = 1;\n }\n\n const atob = getAtoB(layer, moveCall.target, this.swap1Layer, this.swap2Layer);\n\n const routes = atob.map((item, index) => {\n const pool = this.helper.decodeSharedObjectId(index);\n const sqrtPrice = this.helper.decodeInputU128(4 + index + layer);\n const nextTickIndex = this.turbosSdk.math.sqrtPriceX64ToTickIndex(new BN(sqrtPrice.toString()));\n\n return {\n pool,\n a2b: item,\n nextTickIndex,\n };\n });\n\n const coinTypeA = atob[0]\n ? moveCall.typeArguments[0]\n : layer === 1\n ? moveCall.typeArguments[0]\n : moveCall.typeArguments[1];\n const coinTypeB =\n layer === 1 ? moveCall.typeArguments[4] : atob[0] ? moveCall.typeArguments[1] : moveCall.typeArguments[0];\n\n const address = this.helper.decodeInputAddress(6 + 2 * layer);\n const deadline = this.helper.decodeInputU64(7 + 2 * layer);\n const amountSpecifiedIsInput = this.helper.decodeInputBool(5 + 2 * layer);\n const amountA = this.helper.decodeInputU64(2 + layer);\n const amountB = this.helper.decodeInputU64(3 + layer);\n\n const result = await this.turbosSdk.trade.computeSwapResultV2({\n pools: [{ pool: routes[0].pool, a2b: routes[0].a2b, amountSpecified: amountA }],\n address,\n amountSpecifiedIsInput,\n });\n\n return {\n txType: TransactionType.Other,\n type: TransactionSubType.Swap,\n intentionData: {\n routes,\n coinTypeA,\n coinTypeB,\n address,\n amountA: amountSpecifiedIsInput ? amountA : amountB,\n amountB: amountSpecifiedIsInput ? amountB : amountA,\n amountSpecifiedIsInput,\n slippage: '0.1',\n deadline,\n },\n };\n }\n\n private decodeAddLiquidity(): DecodeResult {\n console.log(this.helper, 'decodeAddLiquidity this.helper');\n const pool = this.helper.decodeSharedObjectId(0);\n const address = this.helper.decodeInputAddress(12);\n\n const amountA = this.helper.decodeInputU64(8);\n const amountB = this.helper.decodeInputU64(9);\n const tickLower = this.helper.decodeInputU32(4);\n const tickLowerIsNeg = this.helper.decodeInputBool(5);\n const tickUpper = this.helper.decodeInputU32(6);\n const tickUpperIsNeg = this.helper.decodeInputBool(7);\n\n const deadline = this.helper.decodeInputU64(13);\n\n return {\n txType: TransactionType.Other,\n type: TransactionSubType.AddLiquidity,\n intentionData: {\n pool,\n slippage: 10,\n address,\n amountA,\n amountB,\n tickLower: tickLowerIsNeg ? -tickLower : tickLower,\n tickUpper: tickUpperIsNeg ? -tickUpper : tickUpper,\n deadline,\n },\n };\n }\n\n private decodeIncreaseLiquidity(address: string): DecodeResult {\n console.log(this.helper, 'decodeIncreaseLiquidity this.helper');\n\n const pool = this.helper.decodeSharedObjectId(0);\n const nft = this.helper.decodeSharedObjectId(4);\n const amountA = this.helper.decodeInputU64(5);\n const amountB = this.helper.decodeInputU64(6);\n\n const deadline = this.helper.decodeInputU64(9);\n\n return {\n txType: TransactionType.Other,\n type: TransactionSubType.IncreaseLiquidity,\n intentionData: {\n pool,\n slippage: 10,\n address,\n amountA,\n amountB,\n nft,\n deadline,\n },\n };\n }\n\n private decodeDecreaseLiquidity(address: string): DecodeResult {\n console.log(this.helper, 'decodeDecreaseLiquidity this.helper');\n const pool = this.helper.decodeSharedObjectId(0);\n const nft = this.helper.decodeSharedObjectId(2);\n const decreaseLiquidity = this.helper.decodeInputU64(3);\n const amountA = this.helper.decodeInputU64(4);\n const amountB = this.helper.decodeInputU64(5);\n\n const deadline = this.helper.decodeInputU64(6);\n\n return {\n txType: TransactionType.Other,\n type: TransactionSubType.DecreaseLiquidity,\n intentionData: {\n pool,\n decreaseLiquidity,\n nft,\n amountA,\n amountB,\n slippage: 10, // DO NOT use slippage by user setting for now.\n address,\n deadline,\n },\n };\n }\n\n private decodeCollectFee(): DecodeResult {\n console.log(this.helper, 'decodeCollectFee this.helper');\n const pool = this.helper.decodeSharedObjectId(0);\n const nft = this.helper.decodeSharedObjectId(2);\n const address = this.helper.decodeInputAddress(5);\n const collectAmountA = this.helper.decodeInputU64(3);\n const collectAmountB = this.helper.decodeInputU64(4);\n\n const deadline = this.helper.decodeInputU64(6);\n\n return {\n txType: TransactionType.Other,\n type: TransactionSubType.CollectFee,\n intentionData: {\n pool,\n address,\n collectAmountA,\n collectAmountB,\n nft,\n deadline,\n },\n };\n }\n\n private decodeCollectReward(): DecodeResult {\n console.log(this.helper, 'decodeCollectReward this.helper');\n const pool = this.helper.decodeSharedObjectId(0);\n const nft = this.helper.decodeSharedObjectId(2);\n const address = this.helper.decodeInputAddress(6);\n const rewardAmounts = this.collectRewardHelper.map((helper) => helper.decodeInputU64(5));\n\n const deadline = this.helper.decodeInputU64(7);\n\n return {\n txType: TransactionType.Other,\n type: TransactionSubType.CollectReward,\n intentionData: {\n pool,\n address,\n rewardAmounts,\n nft,\n deadline,\n },\n };\n }\n\n private decodeBurn(): DecodeResult {\n console.log(this.helper, 'decodeBurn this.helper');\n const pool = this.helper.decodeSharedObjectId(0);\n const nft = this.helper.decodeSharedObjectId(2);\n\n return {\n txType: TransactionType.Other,\n type: TransactionSubType.Burn,\n intentionData: {\n pool,\n nft,\n },\n };\n }\n\n private decodeRemoveLiquidity(address: string): DecodeResult {\n console.log(this.helper, 'decodeRemoveLiquidity this.helper');\n const pool = this.decreaseLiquidityHelper.decodeSharedObjectId(0);\n const nft = this.decreaseLiquidityHelper.decodeSharedObjectId(2);\n const decreaseLiquidity = this.decreaseLiquidityHelper.decodeInputU64(3);\n const amountA = this.decreaseLiquidityHelper.decodeInputU64(4);\n const amountB = this.decreaseLiquidityHelper.decodeInputU64(5);\n\n const deadline = this.decreaseLiquidityHelper.decodeInputU64(6);\n const rewardAmounts = this.collectRewardHelper.map((helper) => helper.decodeInputU64(5));\n\n const collectAmountA = this.collectFeeHelper.decodeInputU64(3) || 0;\n const collectAmountB = this.collectFeeHelper.decodeInputU64(4) || 0;\n\n return {\n txType: TransactionType.Other,\n type: TransactionSubType.RemoveLiquidity,\n intentionData: {\n pool,\n decreaseLiquidity,\n nft,\n amountA,\n amountB,\n slippage: 10,\n address,\n collectAmountA,\n collectAmountB,\n rewardAmounts,\n deadline,\n },\n };\n }\n\n private decodePrixClaim(): DecodeResult {\n return {\n txType: TransactionType.Other,\n type: TransactionSubType.PrixClaim,\n intentionData: {},\n };\n }\n\n private decodePrixJoin(): DecodeResult {\n return {\n txType: TransactionType.Other,\n type: TransactionSubType.PrixJoin,\n intentionData: {},\n };\n }\n\n private decodeSwapExactBaseForQuote(): DecodeResult {\n const poolId = this.swapExactBaseForQuoteHelper.decodeSharedObjectId(0);\n const amountIn = this.swapExactBaseForQuoteHelper.decodeInputU64(3);\n const token1 = this.swapExactBaseForQuoteHelper.shortTypeArg(0);\n const token2 = this.swapExactBaseForQuoteHelper.shortTypeArg(1);\n return {\n txType: TransactionType.Other,\n type: TransactionSubType.SwapExactBaseForQuote,\n intentionData: {\n poolId,\n amountIn,\n token1,\n token2,\n },\n };\n }\n\n private decodeSwapExactQuoteForBase(): DecodeResult {\n const poolId = this.swapExactQuoteForBaseHelper.decodeSharedObjectId(0);\n const amountIn = this.swapExactQuoteForBaseHelper.decodeInputU64(3);\n const token1 = this.swapExactQuoteForBaseHelper.shortTypeArg(0);\n const token2 = this.swapExactQuoteForBaseHelper.shortTypeArg(1);\n\n return {\n txType: TransactionType.Other,\n type: TransactionSubType.SwapExactQuoteForBase,\n intentionData: {\n poolId,\n amountIn,\n token1,\n token2,\n },\n };\n }\n\n private get helper() {\n const moveCall = this.transactions.find(\n (trans) =>\n trans.kind === 'MoveCall' &&\n trans.target !== '0x2::coin::zero' &&\n trans.target !== '0x0000000000000000000000000000000000000000000000000000000000000002::coin::zero',\n ) as MoveCallTransaction;\n return new MoveCallHelper(moveCall, this.txb);\n }\n\n private get collectRewardHelper() {\n const moveCalls = this.transactions.filter(\n (trans) =>\n trans.kind === 'MoveCall' && trans.target === `${this.config.PackageId}::position_manager::collect_reward`,\n ) as MoveCallTransaction[];\n return moveCalls.map((moveCall) => new MoveCallHelper(moveCall, this.txb));\n }\n\n private get collectFeeHelper() {\n const moveCall = this.transactions.find(\n (trans) => trans.kind === 'MoveCall' && trans.target === `${this.config.PackageId}::position_manager::collect`,\n ) as MoveCallTransaction;\n return new MoveCallHelper(moveCall, this.txb);\n }\n\n private get decreaseLiquidityHelper() {\n const moveCall = this.transactions.find(\n (trans) =>\n trans.kind === 'MoveCall' && trans.target === `${this.config.PackageId}::position_manager::decrease_liquidity`,\n ) as MoveCallTransaction;\n return new MoveCallHelper(moveCall, this.txb);\n }\n\n private get swapExactBaseForQuoteHelper() {\n const moveCall = this.transactions.find(\n (trans) =>\n trans.kind === 'MoveCall' && trans.target === `${deepbookConfig.PackageId}::clob_v2::swap_exact_base_for_quote`,\n ) as MoveCallTransaction;\n return new MoveCallHelper(moveCall, this.txb);\n }\n\n private get swapExactQuoteForBaseHelper() {\n const moveCall = this.transactions.find(\n (trans) =>\n trans.kind === 'MoveCall' && trans.target === `${deepbookConfig.PackageId}::clob_v2::swap_exact_quote_for_base`,\n ) as MoveCallTransaction;\n return new MoveCallHelper(moveCall, this.txb);\n }\n}\n\nexport class MoveCallHelper {\n constructor(\n public readonly moveCall: MoveCallTransaction,\n public readonly txb: TransactionBlock,\n ) {}\n\n decodeSharedObjectId(argIndex: number) {\n const input = this.getInputParam(argIndex);\n return MoveCallHelper.getSharedObjectId(input);\n }\n\n decodeOwnedObjectId(argIndex: number) {\n const input = this.getInputParam(argIndex);\n return MoveCallHelper.getOwnedObjectId(input);\n }\n\n decodeInputU128(argIndex: number) {\n const strVal = this.decodePureArg<string>(argIndex, 'u128');\n return Number(strVal);\n }\n\n decodeInputU64(argIndex: number) {\n const strVal = this.decodePureArg<string>(argIndex, 'u64');\n return Number(strVal);\n }\n\n decodeInputU32(argIndex: number) {\n const strVal = this.decodePureArg<string>(argIndex, 'u32');\n return Number(strVal);\n }\n\n decodeInputU8(argIndex: number) {\n const strVal = this.decodePureArg<string>(argIndex, 'u8');\n return Number(strVal);\n }\n\n decodeInputAddress(argIndex: number) {\n const input = this.decodePureArg<string>(argIndex, 'address');\n return normalizeSuiAddress(input);\n }\n\n decodeInputString(argIndex: number) {\n return this.decodePureArg<string>(argIndex, 'string');\n }\n\n decodeInputBool(argIndex: number) {\n return this.decodePureArg<boolean>(argIndex, 'bool');\n }\n\n decodePureArg<T>(argIndex: number, bcsType: string) {\n const input = this.getInputParam(argIndex);\n return MoveCallHelper.getPureInputValue<T>(input, bcsType);\n }\n\n getInputParam(argIndex: number) {\n const arg = this.moveCall.arguments[argIndex];\n if (arg.kind !== 'Input') {\n throw new Error('not input type');\n }\n return this.txb.blockData.inputs[arg.index];\n }\n\n static getPureInputValue<T>(input: TransactionBlockInput, bcsType: string) {\n if (input.type !== 'pure') {\n throw new Error('not pure argument');\n }\n if (typeof input.value === 'object' && 'Pure' in input.value) {\n const bcsNums = input.value.Pure;\n return bcs.de(bcsType, new Uint8Array(bcsNums)) as T;\n }\n return input.value as T;\n }\n\n static getOwnedObjectId(input: TransactionBlockInput) {\n if (input.type !== 'object') {\n throw new Error(`not object argument: ${JSON.stringify(input)}`);\n }\n if (typeof input.value === 'object') {\n if (!('Object' in input.value) || !('ImmOrOwned' in input.value.Object)) {\n throw new Error('not ImmOrOwned');\n }\n return normalizeSuiAddress(input.value.Object.ImmOrOwned.objectId as string);\n }\n return normalizeSuiAddress(input.value as string);\n }\n\n static getSharedObjectId(input: TransactionBlockInput) {\n if (input.type !== 'object') {\n throw new Error(`not object argument: ${JSON.stringify(input)}`);\n }\n if (typeof input.value !== 'object') {\n return normalizeSuiAddress(input.value as string);\n }\n if (!('Object' in input.value) || !('Shared' in input.value.Object)) {\n throw new Error('not Shared');\n }\n return normalizeSuiAddress(input.value.Object.Shared.objectId as string);\n }\n\n static getPureInput<T>(input: TransactionBlockInput, bcsType: string) {\n if (input.type !== 'pure') {\n throw new Error('not pure argument');\n }\n if (typeof input.value !== 'object') {\n return input.value as T;\n }\n if (!('Pure' in input.value)) {\n throw new Error('Pure not in value');\n }\n const bcsVal = input.value.Pure;\n return bcs.de(bcsType, new Uint8Array(bcsVal)) as T;\n }\n\n typeArg(index: number) {\n return normalizeStructTag(this.moveCall.typeArguments[index]);\n }\n\n shortTypeArg(index: number) {\n return this.moveCall.typeArguments[index];\n }\n\n txArg(index: number) {\n return this.moveCall.arguments[index];\n }\n}\n","export const prixConfig = {\n PackageId: '0x02fe4933f4521250e55a15441096d1d4a38a7311195b0bca126fc0138c1f5a97',\n Claim: '0x0c822cec42f7ca703696b4232f1c47b348330c23580172a29aab465bc071d894',\n turbosCoinType: '0x5d1f47ea69bb0de31c313d7acf89b890dbb8991ea8e03c6c355171f84bb1ba4a::turbos::TURBOS',\n};\n\nexport const deepbookConfig = {\n PackageId: '0xdee9',\n};\n","import { TransactionType } from '@msafe/sui3-utils';\nimport { SuiClient } from '@mysten/sui.js/client';\nimport { TransactionBlock } from '@mysten/sui.js/transactions';\nimport { WalletAccount } from '@mysten/wallet-standard';\nimport { Pool, TurbosSdk, Network } from 'turbos-clmm-sdk';\n\nimport { BaseIntentionLegacy } from '@/apps/interface/sui-js';\n\nimport { SuiNetworks, TransactionSubType } from '../types';\n\nexport type AddLiquidityIntentionData = Pool.AddLiquidityOptions;\n\nexport class AddLiquidityIntention extends BaseIntentionLegacy<AddLiquidityIntentionData> {\n txType!: TransactionType.Other;\n\n txSubType!: TransactionSubType.AddLiquidity;\n\n constructor(public override readonly data: AddLiquidityIntentionData) {\n super(data);\n }\n\n async build(input: {\n suiClient: SuiClient;\n account: WalletAccount;\n network: SuiNetworks;\n }): Promise<TransactionBlock> {\n const turbosSdk = new TurbosSdk(input.network.replace('sui:', '') as Network, input.suiClient);\n const { pool, address, amountA, amountB, slippage, tickLower, tickUpper, deadline, txb } = this.data;\n\n return turbosSdk.pool.addLiquidity({\n pool,\n slippage,\n address,\n amountA,\n amountB,\n tickLower,\n tickUpper,\n deadline,\n txb,\n });\n }\n\n static fromData(data: AddLiquidityIntentionData) {\n return new AddLiquidityIntention(data);\n }\n}\n","import { TransactionType } from '@msafe/sui3-utils';\nimport { SuiClient } from '@mysten/sui.js/client';\nimport { TransactionBlock } from '@mysten/sui.js/transactions';\nimport { WalletAccount } from '@mysten/wallet-standard';\nimport { NFT, TurbosSdk, Network } from 'turbos-clmm-sdk';\n\nimport { BaseIntentionLegacy } from '@/apps/interface/sui-js';\n\nimport { SuiNetworks, TransactionSubType } from '../types';\n\nexport type BurnIntentionData = NFT.BurnOptions;\n\nexport class BurnIntention extends BaseIntentionLegacy<BurnIntentionData> {\n txType!: TransactionType.Other;\n\n txSubType!: TransactionSubType.AddLiquidity;\n\n constructor(public override readonly data: BurnIntentionData) {\n super(data);\n }\n\n async build(input: {\n suiClient: SuiClient;\n account: WalletAccount;\n network: SuiNetworks;\n }): Promise<TransactionBlock> {\n const turbosSdk = new TurbosSdk(input.network.replace('sui:', '') as Network, input.suiClient);\n const { pool, nft, txb } = this.data;\n\n return turbosSdk.nft.burn({\n pool,\n nft,\n txb,\n });\n }\n\n static fromData(data: BurnIntentionData) {\n return new BurnIntention(data);\n }\n}\n","import { TransactionType } from '@msafe/sui3-utils';\nimport { SuiClient } from '@mysten/sui.js/client';\nimport { TransactionBlock } from '@mysten/sui.js/transactions';\nimport { WalletAccount } from '@mysten/wallet-standard';\nimport { Network, Pool, TurbosSdk } from 'turbos-clmm-sdk';\n\nimport { BaseIntentionLegacy } from '@/apps/interface/sui-js';\n\nimport { SuiNetworks, TransactionSubType } from '../types';\n\nexport type CollectFeeIntentionData = Pool.CollectFeeOptions;\n\nexport class CollectFeeIntention extends BaseIntentionLegacy<CollectFeeIntentionData> {\n txType!: TransactionType.Other;\n\n txSubType!: TransactionSubType.AddLiquidity;\n\n constructor(public override readonly data: CollectFeeIntentionData) {\n super(data);\n }\n\n async build(input: {\n suiClient: SuiClient;\n account: WalletAccount;\n network: SuiNetworks;\n }): Promise<TransactionBlock> {\n const turbosSdk = new TurbosSdk(input.network.replace('sui:', '') as Network, input.suiClient);\n const { pool, address, nft, collectAmountA, collectAmountB, deadline, txb } = this.data;\n\n return turbosSdk.pool.collectFee({\n pool,\n address,\n collectAmountA,\n collectAmountB,\n nft,\n deadline,\n txb,\n });\n }\n\n static fromData(data: CollectFeeIntentionData) {\n return new CollectFeeIntention(data);\n }\n}\n","import { TransactionType } from '@msafe/sui3-utils';\nimport { SuiClient } from '@mysten/sui.js/client';\nimport { TransactionBlock } from '@mysten/sui.js/transactions';\nimport { WalletAccount } from '@mysten/wallet-standard';\nimport { Network, Pool, TurbosSdk } from 'turbos-clmm-sdk';\n\nimport { BaseIntentionLegacy } from '@/apps/interface/sui-js';\n\nimport { SuiNetworks, TransactionSubType } from '../types';\n\nexport type CollectRewardIntentionData = Pool.CollectRewardOptions;\n\nexport class CollectRewardIntention extends BaseIntentionLegacy<CollectRewardIntentionData> {\n txType!: TransactionType.Other;\n\n txSubType!: TransactionSubType.AddLiquidity;\n\n constructor(public override readonly data: CollectRewardIntentionData) {\n super(data);\n }\n\n async build(input: {\n suiClient: SuiClient;\n account: WalletAccount;\n network: SuiNetworks;\n }): Promise<TransactionBlock> {\n const turbosSdk = new TurbosSdk(input.network.replace('sui:', '') as Network, input.suiClient);\n const { pool, address, nft, rewardAmounts, deadline, txb } = this.data;\n\n return turbosSdk.pool.collectReward({\n pool,\n address,\n rewardAmounts,\n nft,\n deadline,\n txb,\n });\n }\n\n static fromData(data: CollectRewardIntentionData) {\n return new CollectRewardIntention(data);\n }\n}\n","import { TransactionType } from '@msafe/sui3-utils';\nimport { SuiClient } from '@mysten/sui.js/client';\nimport { TransactionBlock } from '@mysten/sui.js/transactions';\nimport { WalletAccount } from '@mysten/wallet-standard';\nimport { Network, Pool, TurbosSdk } from 'turbos-clmm-sdk';\n\nimport { BaseIntentionLegacy } from '@/apps/interface/sui-js';\n\nimport { SuiNetworks, TransactionSubType } from '../types';\n\nexport type CreatePoolIntentionData = Pool.CreatePoolOptions;\n\nexport class CreatePoolIntention extends BaseIntentionLegacy<CreatePoolIntentionData> {\n txType!: TransactionType.Other;\n\n txSubType!: TransactionSubType.AddLiquidity;\n\n constructor(public override readonly data: CreatePoolIntentionData) {\n super(data);\n }\n\n async build(input: {\n suiClient: SuiClient;\n account: WalletAccount;\n network: SuiNetworks;\n }): Promise<TransactionBlock> {\n const turbosSdk = new TurbosSdk(input.network.replace('sui:', '') as Network, input.suiClient);\n const {\n fee,\n address,\n tickLower,\n tickUpper,\n sqrtPrice,\n slippage,\n coinTypeA,\n coinTypeB,\n amountA,\n amountB,\n deadline,\n txb,\n } = this.data;\n\n return turbosSdk.pool.createPool({\n fee,\n amountA,\n amountB,\n address,\n tickLower,\n tickUpper,\n sqrtPrice,\n slippage,\n coinTypeA,\n coinTypeB,\n deadline,\n txb,\n });\n }\n\n static fromData(data: CreatePoolIntentionData) {\n return new CreatePoolIntention(data);\n }\n}\n","import { TransactionType } from '@msafe/sui3-utils';\nimport { SuiClient } from '@mysten/sui.js/client';\nimport { TransactionBlock } from '@mysten/sui.js/transactions';\nimport { WalletAccount } from '@mysten/wallet-standard';\nimport { Pool, TurbosSdk, Network } from 'turbos-clmm-sdk';\n\nimport { BaseIntentionLegacy } from '@/apps/interface/sui-js';\n\nimport { SuiNetworks, TransactionSubType } from '../types';\n\nexport type DecreaseLiquidityIntentionData = Pool.DecreaseLiquidityOptions;\n\nexport class DecreaseLiquidityIntention extends BaseIntentionLegacy<DecreaseLiquidityIntentionData> {\n txType!: TransactionType.Other;\n\n txSubType!: TransactionSubType.AddLiquidity;\n\n constructor(public override readonly data: DecreaseLiquidityIntentionData) {\n super(data);\n }\n\n async build(input: {\n suiClient: SuiClient;\n account: WalletAccount;\n network: SuiNetworks;\n }): Promise<TransactionBlock> {\n const turbosSdk = new TurbosSdk(input.network.replace('sui:', '') as Network, input.suiClient);\n const { pool, address, amountA, amountB, slippage, nft, decreaseLiquidity, deadline, txb } = this.data;\n\n return turbosSdk.pool.decreaseLiquidity({\n pool,\n slippage,\n address,\n amountA,\n amountB,\n nft,\n decreaseLiquidity,\n deadline,\n txb,\n });\n }\n\n static fromData(data: DecreaseLiquidityIntentionData) {\n return new DecreaseLiquidityIntention(data);\n }\n}\n","import { TransactionType } from '@msafe/sui3-utils';\nimport { SuiClient } from '@mysten/sui.js/client';\nimport { TransactionBlock } from '@mysten/sui.js/transactions';\nimport { WalletAccount } from '@mysten/wallet-standard';\nimport { Pool, TurbosSdk, Network } from 'turbos-clmm-sdk';\n\nimport { BaseIntentionLegacy } from '@/apps/interface/sui-js';\n\nimport { SuiNetworks, TransactionSubType } from '../types';\n\nexport type IncreaseLiquidityIntentionData = Pool.IncreaseLiquidityOptions;\n\nexport class IncreaseLiquidityIntention extends BaseIntentionLegacy<IncreaseLiquidityIntentionData> {\n txType!: TransactionType.Other;\n\n txSubType!: TransactionSubType.AddLiquidity;\n\n constructor(public override readonly data: IncreaseLiquidityIntentionData) {\n super(data);\n }\n\n async build(input: {\n suiClient: SuiClient;\n account: WalletAccount;\n network: SuiNetworks;\n }): Promise<TransactionBlock> {\n const turbosSdk = new TurbosSdk(input.network.replace('sui:', '') as Network, input.suiClient);\n const { pool, address, amountA, amountB, slippage, nft, deadline, txb } = this.data;\n\n return turbosSdk.pool.increaseLiquidity({\n pool,\n slippage,\n address,\n amountA,\n amountB,\n nft,\n deadline,\n txb,\n });\n }\n\n static fromData(data: IncreaseLiquidityIntentionData) {\n return new IncreaseLiquidityIntention(data);\n }\n}\n","import { TransactionType } from '@msafe/sui3-utils';\nimport { SuiClient } from '@mysten/sui.js/client';\nimport { TransactionBlock } from '@mysten/sui.js/transactions';\nimport { SUI_CLOCK_OBJECT_ID } from '@mysten/sui.js/utils';\nimport { WalletAccount } from '@mysten/wallet-standard';\n\nimport { BaseIntentionLegacy } from '@/apps/interface/sui-js';\n\nimport { prixConfig } from '../config';\nimport { SuiNetworks, TransactionSubType } from '../types';\n\nexport interface PrixClaimIntentionData {}\n\nexport class PrixClaimIntention extends BaseIntentionLegacy<PrixClaimIntentionData> {\n txType!: TransactionType.Other;\n\n txSubType!: TransactionSubType.PrixClaim;\n\n constructor(public override readonly data: PrixClaimIntentionData) {\n super(data);\n }\n\n async build(input: {\n suiClient: SuiClient;\n account: WalletAccount;\n network: SuiNetworks;\n }): Promise<TransactionBlock> {\n const txb = new TransactionBlock();\n txb.moveCall({\n target: `${prixConfig.PackageId}::claim::claim`,\n typeArguments: [prixConfig.turbosCoinType],\n arguments: [txb.object(prixConfig.Claim), txb.object(SUI_CLOCK_OBJECT_ID)],\n });\n return txb;\n }\n\n static fromData(data: PrixClaimIntentionData) {\n return new PrixClaimIntention(data);\n }\n}\n","import { TransactionType } from '@msafe/sui3-utils';\nimport { SuiClient } from '@mysten/sui.js/client';\nimport { TransactionBlock } from '@mysten/sui.js/transactions';\nimport { WalletAccount } from '@mysten/wallet-standard';\n\nimport { BaseIntentionLegacy } from '@/apps/interface/sui-js';\n\nimport { prixConfig } from '../config';\nimport { SuiNetworks, TransactionSubType } from '../types';\n\nexport interface PrixJoinIntentionData {}\n\nexport class PrixJoinIntention extends BaseIntentionLegacy<PrixJoinIntentionData> {\n txType!: TransactionType.Other;\n\n txSubType!: TransactionSubType.PrixJoin;\n\n constructor(public override readonly data: PrixJoinIntentionData) {\n super(data);\n }\n\n async build(input: {\n suiClient: SuiClient;\n account: WalletAccount;\n network: SuiNetworks;\n }): Promise<TransactionBlock> {\n const txb = new TransactionBlock();\n txb.moveCall({\n target: `${prixConfig.PackageId}::claim::join`,\n typeArguments: [prixConfig.turbosCoinType],\n arguments: [txb.object(prixConfig.Claim)],\n });\n return txb;\n }\n\n static fromData(data: PrixJoinIntentionData) {\n return new PrixJoinIntention(data);\n }\n}\n","import { TransactionType } from '@msafe/sui3-utils';\nimport { SuiClient } from '@mysten/sui.js/client';\nimport { TransactionBlock } from '@mysten/sui.js/transactions';\nimport { WalletAccount } from '@mysten/wallet-standard';\nimport { Pool, TurbosSdk, Network } from 'turbos-clmm-sdk';\n\nimport { BaseIntentionLegacy } from '@/apps/interface/sui-js';\n\nimport { SuiNetworks, TransactionSubType } from '../types';\n\nexport type RemoveLiquidityIntentionData = Pool.RemoveLiquidityOptions;\n\nexport class RemoveLiquidityIntention extends BaseIntentionLegacy<RemoveLiquidityIntentionData> {\n txType!: TransactionType.Other;\n\n txSubType!: TransactionSubType.AddLiquidity;\n\n constructor(public override readonly data: RemoveLiquidityIntentionData) {\n super(data);\n }\n\n async build(input: {\n suiClient: SuiClient;\n account: WalletAccount;\n network: SuiNetworks;\n }): Promise<TransactionBlock> {\n const turbosSdk = new TurbosSdk(input.network.replace('sui:', '') as Network, input.suiClient);\n let txb = new TransactionBlock();\n txb = await turbosSdk.pool.collectFee({ txb, ...this.data });\n txb = await turbosSdk.pool.collectReward({ txb, ...this.data });\n txb = await turbosSdk.pool.decreaseLiquidity({ txb, ...this.data });\n txb = await turbosSdk.nft.burn({ txb, nft: this.data.nft, pool: this.data.pool });\n return txb;\n }\n\n static fromData(data: RemoveLiquidityIntentionData) {\n return new RemoveLiquidityIntention(data);\n }\n}\n","import { TransactionType } from '@msafe/sui3-utils';\nimport { SuiClient } from '@mysten/sui.js/client';\nimport { TransactionBlock } from '@mysten/sui.js/transactions';\nimport { WalletAccount } from '@mysten/wallet-standard';\nimport { Trade, TurbosSdk, Network } from 'turbos-clmm-sdk';\n\nimport { BaseIntentionLegacy } from '@/apps/interface/sui-js';\n\nimport { SuiNetworks, TransactionSubType } from '../types';\n\nexport type SwapIntentionData = Trade.SwapOptions;\n\nexport class SwapIntention extends BaseIntentionLegacy<SwapIntentionData> {\n txType!: TransactionType.Other;\n\n txSubType!: TransactionSubType.AddLiquidity;\n\n constructor(public override readonly data: SwapIntentionData) {\n super(data);\n }\n\n async build(input: {\n suiClient: SuiClient;\n account: WalletAccount;\n network: SuiNetworks;\n }): Promise<TransactionBlock> {\n console.log(this.data, 'this.data');\n const turbosSdk = new TurbosSdk(input.network.replace('sui:', '') as Network, input.suiClient);\n const { routes, coinTypeA, coinTypeB, address, amountA, amountB, slippage, amountSpecifiedIsInput, deadline, txb } =\n this.data;\n return turbosSdk.trade.swap({\n routes,\n coinTypeA,\n coinTypeB,\n address,\n amountA,\n amountB,\n amountSpecifiedIsInput,\n slippage,\n deadline,\n txb,\n });\n }\n\n static fromData(data: SwapIntentionData) {\n return new SwapIntention(data);\n }\n}\n","import { TransactionType } from '@msafe/sui3-utils';\nimport { SuiClient } from '@mysten/sui.js/client';\nimport { TransactionBlock } from '@mysten/sui.js/transactions';\nimport { WalletAccount } from '@mysten/wallet-standard';\nimport { TurbosSdk, Network } from 'turbos-clmm-sdk';\n\nimport { BaseIntentionLegacy } from '@/apps/interface/sui-js';\n\nimport { swap_exact_base_for_quote } from '../api/deepbook';\nimport { SuiNetworks, TransactionSubType } from '../types';\n\nexport interface SwapExactBaseForQuoteIntentionData {\n token1: string;\n token2: string;\n poolId: string;\n amountIn: number;\n}\n\nexport class SwapExactBaseForQuoteIntention extends BaseIntentionLegacy<SwapExactBaseForQuoteIntentionData> {\n txType!: TransactionType.Other;\n\n txSubType!: TransactionSubType.SwapExactBaseForQuote;\n\n constructor(public override readonly data: SwapExactBaseForQuoteIntentionData) {\n super(data);\n }\n\n async build(input: {\n suiClient: SuiClient;\n account: WalletAccount;\n network: SuiNetworks;\n }): Promise<TransactionBlock> {\n const turbosSdk = new TurbosSdk(input.network.replace('sui:', '') as Network, input.suiClient);\n const txb = await swap_exact_base_for_quote({ ...this.data, turbosSdk, currentAddress: input.account.address });\n return txb;\n }\n\n static fromData(data: SwapExactBaseForQuoteIntentionData) {\n return new SwapExactBaseForQuoteIntention(data);\n }\n}\n","import { normalizeSuiObjectId } from '@mysten/sui.js/utils';\nimport { TransactionBlock, TransactionObjectArgument } from '@mysten/sui.js/transactions';\nimport { deepbookConfig } from '../config';\nimport { TurbosSdk } from 'turbos-clmm-sdk';\nimport { SuiKit } from '../utils/sui-kit';\n\nconst client_order_id = 89;\nconst gasBudget = 1_000_000;\n\ninterface SwapExactOptions {\n token1: string;\n token2: string;\n poolId: string;\n amountIn: number;\n turbosSdk: TurbosSdk;\n currentAddress: string;\n}\n\nexport const swap_exact_quote_for_base = async (options: SwapExactOptions) => {\n const { token1, token2, poolId, amountIn, currentAddress, turbosSdk } = options;\n let txb = new TransactionBlock();\n\n const suiKit = new SuiKit(turbosSdk);\n // get token objectId\n const coinsData = await suiKit.getCoinsData(currentAddress, token2, amountIn);\n const [sendCoin, mergeCoin] = suiKit.splitAndMergeCoin(coinsData, amountIn, txb);\n if (!sendCoin) {\n throw new Error(`Not enough balance: ${token2}`);\n }\n\n // get accountCap id\n const currentAccountCap = await suiKit.IsAccountCap(currentAddress);\n const accountCap = !currentAccountCap ? suiKit.createAccount(txb) : txb.object(currentAccountCap);\n\n const [base_coin_ret, quote_coin_ret, _amount] = txb.moveCall({\n typeArguments: [token1, token2],\n target: `${deepbookConfig.PackageId}::clob_v2::swap_exact_quote_for_base`,\n arguments: [\n txb.object(String(poolId)),\n txb.pure(client_order_id),\n accountCap,\n txb.pure(amountIn),\n txb.object(normalizeSuiObjectId('0x6')),\n sendCoin,\n ],\n });\n\n if (mergeCoin) {\n txb.transferObjects([mergeCoin], txb.pure(currentAddress));\n }\n\n txb.transferObjects([base_coin_ret!], txb.pure(currentAddress));\n txb.transferObjects([quote_coin_ret!], txb.pure(currentAddress));\n\n if (!currentAccountCap) {\n txb.transferObjects([accountCap], txb.pure(currentAddress));\n }\n\n txb.setSenderIfNotSet(currentAddress);\n txb.setGasBudget(gasBudget);\n\n return txb;\n};\n\nexport const swap_exact_base_for_quote = async (options: SwapExactOptions) => {\n const { token1, token2, poolId, amountIn, currentAddress, turbosSdk } = options;\n let txb = new TransactionBlock();\n\n const suiKit = new SuiKit(turbosSdk);\n // get token objectId\n const coinsData = await suiKit.getCoinsData(currentAddress, token1, amountIn);\n const [sendCoin, mergeCoin] = suiKit.splitAndMergeCoin(coinsData, amountIn, txb);\n\n if (!sendCoin) {\n throw new Error(`Not enough balance: ${token1}`);\n }\n\n // get accountCap id\n const currentAccountCap = await suiKit.IsAccountCap(currentAddress);\n const accountCap = !currentAccountCap ? suiKit.createAccount(txb) : txb.object(currentAccountCap);\n\n const zero = suiKit.zero(token2, txb);\n\n const [base_coin_ret, quote_coin_ret, _amount] = txb.moveCall({\n typeArguments: [token1, token2],\n target: `${deepbookConfig.PackageId}::clob_v2::swap_exact_base_for_quote`,\n arguments: [\n txb.object(String(poolId)),\n txb.pure(client_order_id),\n accountCap,\n txb.pure(amountIn),\n sendCoin,\n zero,\n txb.object(normalizeSuiObjectId('0x6')),\n ],\n });\n if (mergeCoin) {\n txb.transferObjects([mergeCoin], txb.pure(currentAddress));\n }\n\n txb.transferObjects([base_coin_ret!], txb.pure(currentAddress));\n txb.transferObjects([quote_coin_ret!], txb.pure(currentAddress));\n\n if (!currentAccountCap) {\n txb.transferObjects([accountCap], txb.pure(currentAddress));\n }\n\n txb.setSenderIfNotSet(currentAddress);\n txb.setGasBudget(gasBudget);\n\n return txb;\n};\n","import { PaginatedCoins } from '@mysten/sui.js/client';\nimport { TransactionBlock, TransactionObjectArgument } from '@mysten/sui.js/transactions';\nimport { TurbosSdk, unstable_getObjectId } from 'turbos-clmm-sdk';\nimport { deepbookConfig } from '../config';\n\ntype CoinData = PaginatedCoins['data'];\n\nexport class SuiKit {\n constructor(public readonly turbosSdk: TurbosSdk) {}\n\n async getCoinsData(currentAddress: string, type: string, amount: number): Promise<CoinData> {\n const coinObjects: CoinData = [];\n let coinFields: PaginatedCoins | undefined;\n do {\n coinFields = await this.turbosSdk.provider.getCoins({\n owner: currentAddress,\n coinType: type,\n cursor: coinFields?.nextCursor,\n });\n coinObjects.push(...coinFields.data);\n } while (coinFields.hasNextPage);\n\n const resultCoinObjects: CoinData = [];\n let currentBalance = 0;\n coinObjects\n .sort((coinA, coinB) => Number(coinB.balance) - Number(coinA.balance))\n .some((object) => {\n if (currentBalance >= amount) {\n return true;\n } else {\n currentBalance += Number(object.balance);\n resultCoinObjects.push(object);\n return false;\n }\n });\n return resultCoinObjects;\n }\n\n splitAndMergeCoin(\n coins: CoinData | undefined,\n amount: number,\n txb: TransactionBlock,\n ): [TransactionObjectArgument | undefined, TransactionObjectArgument | undefined] {\n if (!coins || coins.length < 1) {\n return [undefined, undefined];\n }\n\n if (this.isSuiCoinAddress(coins[0]!.coinType)) {\n const [sendCoin] = txb.splitCoins(txb.gas, [txb.pure(amount)]);\n return [sendCoin, undefined];\n }\n\n const mergeCoin = txb.object(coins[0]!.coinObjectId);\n if (coins.length > 1) {\n txb.mergeCoins(\n mergeCoin,\n coins.slice(1).map((coin) => txb.object(coin.coinObjectId)),\n );\n }\n\n const [sendCoin] = txb.splitCoins(mergeCoin, [txb.pure(amount)]);\n return [sendCoin, mergeCoin];\n }\n\n isSuiCoinAddress(type: string) {\n return type.toLocaleLowerCase() === '0x2::sui::sui';\n }\n\n async IsAccountCap(currentAddress: string): Promise<string | undefined> {\n const dynamicFields = await this.turbosSdk.provider.getOwnedObjects({\n owner: currentAddress,\n options: { showContent: true, showType: true, showOwner: true },\n filter: {\n StructType: `${deepbookConfig.PackageId}::custodian_v2::AccountCap`,\n },\n });\n return dynamicFields.data[0]?.data ? unstable_getObjectId(dynamicFields.data[0].data) : undefined;\n }\n\n createAccount(txb: TransactionBlock): TransactionObjectArgument {\n let [cap] = txb.moveCall({\n typeArguments: [],\n target: `${deepbookConfig.PackageId}::clob_v2::create_account`,\n arguments: [],\n });\n return cap;\n }\n\n zero(token: string, txb: TransactionBlock): TransactionObjectArgument {\n return txb.moveCall({\n typeArguments: [token],\n target: `0x2::coin::zero`,\n arguments: [],\n });\n }\n}\n","import { TransactionType } from '@msafe/sui3-utils';\nimport { SuiClient } from '@mysten/sui.js/client';\nimport { TransactionBlock } from '@mysten/sui.js/transactions';\nimport { WalletAccount } from '@mysten/wallet-standard';\nimport { TurbosSdk, Network } from 'turbos-clmm-sdk';\n\nimport { BaseIntentionLegacy } from '@/apps/interface/sui-js';\n\nimport { swap_exact_quote_for_base } from '../api/deepbook';\nimport { SuiNetworks, TransactionSubType } from '../types';\n\nexport interface SwapExactQuoteForBaseIntentionData {\n token1: string;\n token2: string;\n poolId: string;\n amountIn: number;\n}\n\nexport class SwapExactQuoteForBaseIntention extends BaseIntentionLegacy<SwapExactQuoteForBaseIntentionData> {\n txType!: TransactionType.Other;\n\n txSubType!: TransactionSubType.SwapExactQuoteForBase;\n\n constructor(public override readonly data: SwapExactQuoteForBaseIntentionData) {\n super(data);\n }\n\n async build(input: {\n suiClient: SuiClient;\n account: WalletAccount;\n network: SuiNetworks;\n }): Promise<TransactionBlock> {\n const turbosSdk = new TurbosSdk(input.network.replace('sui:', '') as Network, input.suiClient);\n const txb = await swap_exact_quote_for_base({ ...this.data, turbosSdk, currentAddress: input.account.address });\n return txb;\n }\n\n static fromData(data: SwapExactQuoteForBaseIntentionData) {\n return new SwapExactQuoteForBaseIntention(data);\n }\n}\n","import { TransactionType } from '@msafe/sui3-utils';\nimport { SuiClient } from '@mysten/sui.js/client';\nimport { TransactionBlock } from '@mysten/sui.js/transactions';\nimport { SuiSignTransactionBlockInput, WalletAccount } from '@mysten/wallet-standard';\n\nimport { IAppHelperInternalLegacy } from '@/apps/interface/sui-js';\nimport { SuiNetworks } from '@/types';\n\nimport { Decoder } from './decoder';\nimport { ClaimTicketIntention, ClaimTicketIntentionData } from './intentions/claimTicket';\nimport { StakeIntention, StakeIntentionData } from './intentions/stake';\nimport { UnStakeIntention, UnStakeIntentionData } from './intentions/unStake';\nimport { TransactionSubType } from './types';\n\nexport type VoloIntention = StakeIntention | UnStakeIntention | ClaimTicketIntention;\n\nexport type VoloIntentionData = StakeIntentionData | UnStakeIntentionData | ClaimTicketIntentionData;\n\nexport class VoloAppHelper implements IAppHelperInternalLegacy<VoloIntentionData> {\n application = 'volo';\n\n supportSDK = '@mysten/sui.js' as const;\n\n async deserialize(\n input: SuiSignTransactionBlockInput & { network: SuiNetworks; suiClient: SuiClient; account: WalletAccount },\n ): Promise<{ txType: TransactionType; txSubType: TransactionSubType; intentionData: VoloIntentionData }> {\n const { transactionBlock } = input;\n const decoder = new Decoder(transactionBlock);\n const result = decoder.decode();\n return {\n txType: TransactionType.Other,\n txSubType: result.type,\n intentionData: result.intentionData,\n };\n }\n\n async build(input: {\n intentionData: VoloIntentionData;\n txType: TransactionType;\n txSubType: string;\n suiClient: SuiClient;\n account: WalletAccount;\n }): Promise<TransactionBlock> {\n const { suiClient, account } = input;\n let intention: VoloIntention;\n switch (input.txSubType) {\n case TransactionSubType.Stake:\n intention = StakeIntention.fromData(input.intentionData as StakeIntentionData);\n break;\n case TransactionSubType.UnStake:\n intention = UnStakeIntention.fromData(input.intentionData as UnStakeIntentionData);\n break;\n case TransactionSubType.ClaimTicket:\n intention = ClaimTicketIntention.fromData(input.intentionData as ClaimTicketIntentionData);\n break;\n default:\n throw new Error('not implemented');\n }\n return intention.build({ suiClient, account });\n }\n}\n","import { TransactionType } from '@msafe/sui3-utils';\nimport { bcs } from '@mysten/sui.js/bcs';\nimport { MoveCallTransaction } from '@mysten/sui.js/dist/cjs/transactions';\nimport { TransactionBlock, TransactionBlockInput } from '@mysten/sui.js/transactions';\nimport { normalizeStructTag, normalizeSuiAddress } from '@mysten/sui.js/utils';\n\nimport config from './config';\nimport { TransactionSubType } from './types';\n\nexport function isSameCoinType(type1: string, type2: string) {\n return normalizeStructTag(type1) === normalizeStructTag(type2);\n}\n\nexport function isSameTarget(target1: string, target2: string): boolean {\n return normalizeStructTag(target1) === normalizeStructTag(target2);\n}\n\ntype DecodeResult = {\n txType: TransactionType;\n type: TransactionSubType;\n intentionData: any;\n};\n\nexport class Decoder {\n constructor(public readonly txb: TransactionBlock) {}\n\n decode() {\n console.log('txb', this.txb);\n if (this.isStakeTransaction()) {\n return this.decodeStake();\n }\n\n if (this.isUnStakeTransaction()) {\n return this.decodeUnStake();\n }\n\n if (this.isClaimTicketTransaction()) {\n return this.decodeClaimTicket();\n }\n\n throw new Error(`Unknown transaction type`);\n }\n\n private get transactions() {\n return this.txb.blockData.transactions;\n }\n\n private getMoveCallTransaction(target: string) {\n return this.transactions.find((trans) => trans.kind === 'MoveCall' && trans.target === target);\n }\n\n private isStakeTransaction() {\n return !!this.getMoveCallTransaction(`${config.packageId}::native_pool::stake`);\n }\n\n private isUnStakeTransaction() {\n return !!this.getMoveCallTransaction(`${config.packageId}::native_pool::unstake`);\n }\n\n private isClaimTicketTransaction() {\n return !!this.getMoveCallTransaction(`${config.packageId}::native_pool::burn_ticket`);\n }\n\n private decodeStake(): DecodeResult {\n const amount = (this.transactions[0] as any).amounts[0].value.toNumber() as number;\n return {\n txType: TransactionType.Other,\n type: TransactionSubType.Stake,\n intentionData: {\n amount,\n },\n };\n }\n\n private decodeUnStake(): DecodeResult {\n const splitCoinTrans = this.transactions.find((trans) => trans.kind === 'SplitCoins') as any;\n const amount = splitCoinTrans.amounts[0].value.toNumber() as number;\n return {\n txType: TransactionType.Other,\n type: TransactionSubType.UnStake,\n intentionData: {\n amount,\n },\n };\n }\n\n private decodeClaimTicket(): DecodeResult {\n const ticketId = this.helper.decodeOwnedObjectId(2);\n console.log(ticketId);\n return {\n txType: TransactionType.Other,\n type: TransactionSubType.ClaimTicket,\n intentionData: {\n ticketId,\n },\n };\n }\n\n private get helper() {\n const moveCall = this.transactions.find(\n (trans) => trans.kind === 'MoveCall' && trans.target.startsWith(config.packageId),\n ) as MoveCallTransaction;\n return new MoveCallHelper(moveCall, this.txb);\n }\n}\n\nexport class MoveCallHelper {\n constructor(\n public readonly moveCall: MoveCallTransaction,\n public readonly txb: TransactionBlock,\n ) {}\n\n decodeSharedObjectId(argIndex: number) {\n const input = this.getInputParam(argIndex);\n return MoveCallHelper.getSharedObjectId(input);\n }\n\n decodeOwnedObjectId(argIndex: number) {\n const input = this.getInputParam(argIndex);\n return MoveCallHelper.getOwnedObjectId(input);\n }\n\n decodeInputU64(argIndex: number) {\n const strVal = this.decodePureArg<string>(argIndex, 'u64');\n return Number(strVal);\n }\n\n decodeInputU8(argIndex: number) {\n const strVal = this.decodePureArg<string>(argIndex, 'u8');\n return Number(strVal);\n }\n\n decodeInputAddress(argIndex: number) {\n const input = this.decodePureArg<string>(argIndex, 'address');\n return normalizeSuiAddress(input);\n }\n\n decodeInputString(argIndex: number) {\n return this.decodePureArg<string>(argIndex, 'string');\n }\n\n decodeInputBool(argIndex: number) {\n return this.decodePureArg<boolean>(argIndex, 'bool');\n }\n\n decodePureArg<T>(argIndex: number, bcsType: string) {\n const input = this.getInputParam(argIndex);\n return MoveCallHelper.getPureInputValue<T>(input, bcsType);\n }\n\n getInputParam(argIndex: number) {\n const arg = this.moveCall.arguments[argIndex];\n if (arg.kind !== 'Input') {\n throw new Error('not input type');\n }\n return this.txb.blockData.inputs[arg.index];\n }\n\n static getPureInputValue<T>(input: TransactionBlockInput, bcsType: string) {\n if (input.type !== 'pure') {\n throw new Error('not pure argument');\n }\n if (typeof input.value === 'object' && 'Pure' in input.value) {\n const bcsNums = input.value.Pure;\n return bcs.de(bcsType, new Uint8Array(bcsNums)) as T;\n }\n return input.value as T;\n }\n\n static getOwnedObjectId(input: TransactionBlockInput) {\n if (input.type !== 'object') {\n throw new Error(`not object argument: ${JSON.stringify(input)}`);\n }\n if (typeof input.value === 'object') {\n if (!('Object' in input.value) || !('ImmOrOwned' in input.value.Object)) {\n throw new Error('not ImmOrOwned');\n }\n return normalizeSuiAddress(input.value.Object.ImmOrOwned.objectId as string);\n }\n return normalizeSuiAddress(input.value as string);\n }\n\n static getSharedObjectId(input: TransactionBlockInput) {\n if (input.type !== 'object') {\n throw new Error(`not object argument: ${JSON.stringify(input)}`);\n }\n if (typeof input.value !== 'object') {\n return normalizeSuiAddress(input.value as string);\n }\n if (!('Object' in input.value) || !('Shared' in input.value.Object)) {\n throw new Error('not Shared');\n }\n return normalizeSuiAddress(input.value.Object.Shared.objectId as string);\n }\n\n static getPureInput<T>(input: TransactionBlockInput, bcsType: string) {\n if (input.type !== 'pure') {\n throw new Error('not pure argument');\n }\n if (typeof input.value !== 'object') {\n return input.value as T;\n }\n if (!('Pure' in input.value)) {\n throw new Error('Pure not in value');\n }\n const bcsVal = input.value.Pure;\n return bcs.de(bcsType, new Uint8Array(bcsVal)) as T;\n }\n\n typeArg(index: number) {\n return normalizeStructTag(this.moveCall.typeArguments[index]);\n }\n\n txArg(index: number) {\n return this.moveCall.arguments[index];\n }\n}\n","const config = {\n packageId: '0x549e8b69270defbfafd4f94e17ec44cdbdd99820b33bda2278dea3b9a32d3f55',\n poolObjectId: '0x7fa2faa111b8c65bea48a23049bfd81ca8f971a262d981dcd9a17c3825cb5baf',\n metadataObjectId: '0x680cd26af32b2bde8d3361e804c53ec1d1cfe24c7f039eb7f549e8dfde389a60',\n systemStateObjectId: '0x0000000000000000000000000000000000000000000000000000000000000005',\n certType: '0x549e8b69270defbfafd4f94e17ec44cdbdd99820b33bda2278dea3b9a32d3f55::cert::CERT',\n gasBudget: 50_000_000,\n};\n\nexport default config;\n","import { TransactionType } from '@msafe/sui3-utils';\nimport { SuiClient } from '@mysten/sui.js/client';\nimport { TransactionBlock } from '@mysten/sui.js/transactions';\nimport { WalletAccount } from '@mysten/wallet-standard';\n\nimport { BaseIntentionLegacy } from '@/apps/interface/sui-js';\n\nimport config from '../config';\nimport { TransactionSubType } from '../types';\n\nexport interface ClaimTicketIntentionData {\n ticketId: string;\n}\n\nexport class ClaimTicketIntention extends BaseIntentionLegacy<ClaimTicketIntentionData> {\n txType: TransactionType.Other;\n\n txSubType: TransactionSubType.Stake;\n\n constructor(public readonly data: ClaimTicketIntentionData) {\n super(data);\n }\n\n async build(input: { suiClient: SuiClient; account: WalletAccount }): Promise<TransactionBlock> {\n console.log(input);\n const tx = new TransactionBlock();\n const { ticketId } = this.data;\n tx.moveCall({\n target: `${config.packageId}::native_pool::burn_ticket`,\n arguments: [tx.object(config.poolObjectId), tx.object(config.systemStateObjectId), tx.object(ticketId)],\n });\n return tx;\n }\n\n static fromData(data: ClaimTicketIntentionData) {\n return new ClaimTicketIntention(data);\n }\n}\n","import { TransactionType } from '@msafe/sui3-utils';\nimport { SuiClient } from '@mysten/sui.js/client';\nimport { TransactionBlock } from '@mysten/sui.js/transactions';\nimport { WalletAccount } from '@mysten/wallet-standard';\n\nimport { BaseIntentionLegacy } from '@/apps/interface/sui-js';\n\nimport config from '../config';\nimport { TransactionSubType } from '../types';\n\nexport interface StakeIntentionData {\n amount: number;\n}\n\nexport class StakeIntention extends BaseIntentionLegacy<StakeIntentionData> {\n txType: TransactionType.Other;\n\n txSubType: TransactionSubType.Stake;\n\n constructor(public readonly data: StakeIntentionData) {\n super(data);\n }\n\n async build(input: { suiClient: SuiClient; account: WalletAccount }): Promise<TransactionBlock> {\n console.log(input);\n const tx = new TransactionBlock();\n const { amount } = this.data;\n const [coin] = tx.splitCoins(tx.gas, [tx.pure(amount)]);\n tx.moveCall({\n target: `${config.packageId}::native_pool::stake`,\n arguments: [\n tx.object(config.poolObjectId),\n tx.object(config.metadataObjectId),\n tx.object(config.systemStateObjectId),\n coin,\n ],\n });\n return tx;\n }\n\n static fromData(data: StakeIntentionData) {\n return new StakeIntention(data);\n }\n}\n","import { TransactionType } from '@msafe/sui3-utils';\nimport { SuiClient } from '@mysten/sui.js/client';\nimport { TransactionBlock } from '@mysten/sui.js/transactions';\nimport { WalletAccount } from '@mysten/wallet-standard';\n\nimport { BaseIntentionLegacy } from '@/apps/interface/sui-js';\n\nimport config from '../config';\nimport { TransactionSubType } from '../types';\n\nexport interface UnStakeIntentionData {\n amount: number;\n}\n\nexport class UnStakeIntention extends BaseIntentionLegacy<UnStakeIntentionData> {\n txType: TransactionType.Other;\n\n txSubType: TransactionSubType.Stake;\n\n constructor(public readonly data: UnStakeIntentionData) {\n super(data);\n }\n\n async build(input: { suiClient: SuiClient; account: WalletAccount }): Promise<TransactionBlock> {\n console.log(input);\n const tx = new TransactionBlock();\n const { amount } = this.data;\n const coins = (\n await input.suiClient.getAllCoins({\n owner: input.account.address,\n limit: 100,\n })\n ).data;\n const [primaryCoin, ...mergeCoins] = coins.filter(\n (coin) => coin.coinType.split('::')[0] === config.certType.split('::')[0],\n );\n\n const primaryCoinInput = tx.object(primaryCoin.coinObjectId);\n if (mergeCoins.length) {\n tx.mergeCoins(\n primaryCoinInput,\n mergeCoins.map((coin) => tx.object(coin.coinObjectId)),\n );\n }\n const coin = tx.splitCoins(tx.object(primaryCoin.coinObjectId), [tx.pure(amount)]);\n\n tx.moveCall({\n target: `${config.packageId}::native_pool::unstake`,\n arguments: [\n tx.object(config.poolObjectId),\n tx.object(config.metadataObjectId),\n tx.object(config.systemStateObjectId),\n coin,\n ],\n });\n return tx;\n }\n\n static fromData(data: UnStakeIntentionData) {\n return new UnStakeIntention(data);\n }\n}\n","import { BucketHelper } from '@/apps/bucket/helper';\nimport { CetusHelper } from '@/apps/cetus/helper';\nimport { MPayAppHelper } from '@/apps/mpay/helper';\nimport { CoreHelper } from '@/apps/msafe-core/helper';\nimport { NAVIAppHelper } from '@/apps/navi/helper';\nimport { PlainTransactionHelper } from '@/apps/plain-transaction/helper';\nimport { MSafeApps } from '@/apps/registry';\nimport { ScallopAppHelper } from '@/apps/scallop/helper';\nimport { SuilendAppHelper } from '@/apps/suilend/helper';\nimport { TURBOSAppHelper } from '@/apps/turbos/helper';\nimport { VoloAppHelper } from '@/apps/volo/helper';\n\nexport const appHelpers = MSafeApps.fromHelpers([\n new CoreHelper(),\n new NAVIAppHelper(),\n new MPayAppHelper(),\n new PlainTransactionHelper(),\n new CetusHelper(),\n new TURBOSAppHelper(),\n // new KRIYAAppHelper(),\n new ScallopAppHelper(),\n new VoloAppHelper(),\n new BucketHelper(),\n new SuilendAppHelper(),\n]);\n"],"mappings":"6FAAA,OAAS,mBAAAA,OAAuB,oBCAhC,OAAS,mBAAAC,OAAuB,oBCKhC,OAAOC,OAAc,sBAyCd,IAAeC,EAAf,KAAmE,CAK9D,YAA4BC,EAAS,CAAT,UAAAA,CAAU,CAIhD,WAAY,CACV,OAAO,KAAK,UAAUF,GAAS,KAAK,IAAI,CAAC,CAC3C,CACF,ECzDA,OAAS,eAAAG,OAAmB,2BCC5B,OAAS,gBAAAC,OAAoB,sBAEtB,IAAMC,GAAkB,C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data","Transaction","BucketClient","getBucketClient","network","account","config","getPsmTx","txbParams","account","network","coin","amount","isIn","tx","Transaction","getBucketClient","PsmIntention","_PsmIntention","BaseIntention","data","TransactionType","input","account","network","txbParams","getPsmTx","BucketHelper","input","txbParams","action","TransactionType","suiClient","account","network","intention","PsmIntention","TransactionType","TransactionType","AggregatorClient","Env","CetusPeripherySDK","CetusClmmSDK","SuiClient","clmmConfig","peripheryConfig","clmmConfigTestnet","peripheryConfigTestnet","getClmmSdk","network","account","config","clmmSdk","getPeripherySdk","aggregatorURL","getAggregatorSdk","suiClient","getAddLiquidityTxb","txbParams","account","network","getClmmSdk","getIncreaseLiquidityTxb","getRemoveLiquidityTxb","getDecreaseLiquidityTxb","getClaimFeeAndMiningTxb","AddLiquidityIntention","_AddLiquidityIntention","BaseIntention","data","TransactionType","input","account","network","txbParams","getAddLiquidityTxb","TransactionType","ClaimFeeAndMiningIntention","_ClaimFeeAndMiningIntention","BaseIntention","data","TransactionType","input","account","network","txbParams","getClaimFeeAndMiningTxb","TransactionType","DecreaseLiquidityIntention","_DecreaseLiquidityIntention","BaseIntention","data","TransactionType","input","account","network","txbParams","getDecreaseLiquidityTxb","TransactionType","getFarmingAddLiquidityTxb","txbParams","account","network","getPeripherySdk","getFarmingIncreaseLiquidityTxb","getFarmingDecreaseLiquidityTxb","getFarmingRemoveLiquidityTxb","getFarmingClaimFeeAndRewardTxb","getFarmingHarvest","getFarmingBatchHarvest","peripherySdk","params","getFarmingStake","getFarmingUnstake","FarmingAddLiquidityIntention","_FarmingAddLiquidityIntention","BaseIntention","data","TransactionType","input","account","network","txbParams","getFarmingAddLiquidityTxb","TransactionType","FarmingBatchHarvestIntention","_FarmingBatchHarvestIntention","BaseIntention","data","TransactionType","input","account","network","txbParams","getFarmingBatchHarvest","TransactionType","FarmingClaimFeeAndRewardIntention","_FarmingClaimFeeAndRewardIntention","BaseIntention","data","TransactionType","input","account","network","txbParams","getFarmingClaimFeeAndRewardTxb","TransactionType","FarmingDecreaseLiquidityIntention","_FarmingDecreaseLiquidityIntention","BaseIntention","data","TransactionType","input","account","network","txbParams","getFarmingDecreaseLiquidityTxb","TransactionType","FarmingHarvestIntention","_FarmingHarvestIntention","BaseIntention","data","TransactionType","input","account","network","txbParams","getFarmingHarvest","TransactionType","FarmingIncreaseLiquidityIntention","_FarmingIncreaseLiquidityIntention","BaseIntention","data","TransactionType","input","account","network","txbParams","getFarmingIncreaseLiquidityTxb","TransactionType","FarmingRemoveLiquidityIntention","_FarmingRemoveLiquidityIntention","BaseIntention","data","TransactionType","input","account","network","txbParams","getFarmingRemoveLiquidityTxb","TransactionType","FarmingStakeIntention","_FarmingStakeIntention","BaseIntention","data","TransactionType","input","account","network","txbParams","getFarmingStake","TransactionType","FarmingUnstakeIntention","_FarmingUnstakeIntention","BaseIntention","data","TransactionType","input","account","network","txbParams","getFarmingUnstake","TransactionType","IncreaseLiquidityIntention","_IncreaseLiquidityIntention","BaseIntention","data","TransactionType","input","account","network","txbParams","getIncreaseLiquidityTxb","TransactionType","RemoveLiquidityIntention","_RemoveLiquidityIntention","BaseIntention","data","TransactionType","input","account","network","txbParams","getRemoveLiquidityTxb","TransactionType","restituteMsafeFastRouterSwapParams","Transaction","getSwapRouterTxb","txbParams","account","network","aggregatorSdk","getAggregatorSdk","txb","Transaction","restituteMsafeFastRouterSwapParams","SwapIntention","_SwapIntention","BaseIntention","data","TransactionType","input","account","network","txbParams","getSwapRouterTxb","TransactionType","Transaction","VestingConfing","getVestingRedeemTxb","txbParams","account","network","pool","nftId","periods","CLOCK_ADDRESS","txb","period","VestingRedeemIntention","_VestingRedeemIntention","BaseIntention","data","TransactionType","input","account","network","txbParams","getVestingRedeemTxb","TransactionType","Transaction","getXcetusConvertTxb","txbParams","account","network","peripherySdk","getPeripherySdk","tx","Transaction","getXcetusRedeemLockTxb","getXcetusClaimingStakeRewardsTxb","getXcetusCancelRedeemTxb","getXcetusRedeemTxb","XcetusCancelIntention","_XcetusCancelIntention","BaseIntention","data","TransactionType","input","account","network","txbParams","getXcetusCancelRedeemTxb","TransactionType","XcetusClaimingStakeRewardsIntention","_XcetusClaimingStakeRewardsIntention","BaseIntention","data","TransactionType","input","account","network","txbParams","getXcetusClaimingStakeRewardsTxb","TransactionType","XcetusConvertIntention","_XcetusConvertIntention","BaseIntention","data","TransactionType","input","account","network","txbParams","getXcetusConvertTxb","TransactionType","XcetusRedeemIntention","_XcetusRedeemIntention","BaseIntention","data","TransactionType","input","account","network","txbParams","getXcetusRedeemTxb","TransactionType","XcetusRedeemLockIntention","_XcetusRedeemLockIntention","BaseIntention","data","TransactionType","input","account","network","txbParams","getXcetusRedeemLockTxb","CetusHelper","input","txbParams","action","TransactionType","suiClient","account","network","intention","AddLiquidityIntention","IncreaseLiquidityIntention","DecreaseLiquidityIntention","RemoveLiquidityIntention","ClaimFeeAndMiningIntention","FarmingAddLiquidityIntention","FarmingIncreaseLiquidityIntention","FarmingDecreaseLiquidityIntention","FarmingRemoveLiquidityIntention","FarmingClaimFeeAndRewardIntention","FarmingHarvestIntention","FarmingBatchHarvestIntention","FarmingStakeIntention","FarmingUnstakeIntention","XcetusConvertIntention","XcetusRedeemLockIntention","XcetusClaimingStakeRewardsIntention","XcetusCancelIntention","XcetusRedeemIntention","VestingRedeemIntention","SwapIntention","TransactionType","sortKeys","BaseIntentionLegacy","data","getFullnodeUrl","dev_exports","__export","contractId","dev_default","feeObjId","roleObjId","status","transaction","upgradeCapObjId","vaultObjId","prod_exports","__export","contractId","prod_default","feeObjId","roleObjId","status","transaction","upgradeCapObjId","vaultObjId","DEV_RPC_ENDPOINT","getFullnodeUrl","STG_RPC_ENDPOINT","PREV_RPC_ENDPOINT","PROD_RPC_ENDPOINT","DEV_BE_API","STG_BE_API","PREV_BE_API","PROD_BE_API","CONTRACT_DEV","dev_exports","CONTRACT_PROD","prod_exports","ENV_CONFIG","getConfig","env","options","ec","SuiClient","MPayError","mpayErrorCode","msg","options","cause","context","NoBackendError","MPayError","WalletNotConnectedError","MPayError","axios","AxiosError","BackendError","MPayError","msg","context","Backend","_Backend","apiURL","response","AxiosError","BackendError","recipient","options","res","axios","sender","query","paginatedData","event","formalizedEvent","address","Globals","_Globals","envConfig","SuiClient","Backend","env","options","ec","getConfig","NoBackendError","b","wallet","WalletNotConnectedError","SUI_TYPE_ARG","normalizeStructTag","normalizeSuiAddress","TransactionBlock","TransactionBlock","SUI_TYPE_ARG","normalizeStructTag","FEE_NUMERATOR","FEE_DENOMINATOR","CLAIM_FEE_NUMERATOR","FLAT_FEE_SUI","MoveObject","object","txb","ObjectVector","objects","o","ResultRef","_ResultRef","result","target","property","nestedResultFor","resultIndex","Buffer","normalizeSuiAddress","InvalidRpcResultError","MPayError","msg","ctx","InspectViewer","results","index","returned","callIndex","returnIndex","callResult","value","type","InvalidRpcResultError","normalizeSuiAddress","Buffer","bcs","InvalidInputError","MPayError","msg","fieldKey","fieldValue","metadataBcsType","MAX_NAME_SIZE","encodeMetadata","metadata","validateMetadata","bcs","decodeMetadata","metaStr","isAsciiString","InvalidInputError","str","normalizeStructTag","isSameCoinType","type1","type2","isSameTarget","target1","target2","GAS_OBJECT_SPEC","nanoid","generateGroupId","CreateStreamHelper","_CreateStreamHelper","globals","feeContract","streamContract","info","encodeMetadata","generateGroupId","normalizeStructTag","recipient","txb","TransactionBlock","paymentWithFee","coinReqs","coinResp","paymentMergedObject","flatFeeMergedObject","i","paymentAmount","feeAmount","paymentCoin","flatFeeCoin","ResultRef","createInfo","infoInternal","FEE_NUMERATOR","FEE_DENOMINATOR","CLAIM_FEE_NUMERATOR","FLAT_FEE_SUI","coins","mergedCoin","coinId","GAS_OBJECT_SPEC","payment","streamCoinType","isSameCoinType","SUI_TYPE_ARG","streamPayment","sum","totalAmount","fee","numEpoch","streamAmount","res","InspectViewer","Transactions","CLOCK_ID","BaseContract","moduleName","config","globals","txb","input","target","Transactions","arg","ObjectVector","MoveObject","ResultRef","callArgs","typeArgs","object","CLOCK_ID","FeeContract","_FeeContract","BaseContract","config","globals","txb","createFeeNumerator","roleObject","feeObject","flatFee","claimFee","amount","StreamContract","_StreamContract","BaseContract","config","globals","txb","input","feeObject","vaultObject","paymentCoinObject","flatFeeObject","clockObject","streamObject","MPayBuilder","globals","config","FeeContract","StreamContract","info","infoInternal","CreateStreamHelper","streamId","enabled","coinType","txb","TransactionBlock","SanityError","MPayError","msg","options","getAllFromIterator","it","res","val","PagedIterator","requester","EntryIterator","NotEnoughBalanceError","MPayError","coinType","requestAmount","gotAmount","DEF_REQ_PAGE_SIZE","getCoinsWithAmount","suiClient","owner","requestAmount","coinType","pageSize","it","OwnedCoinIterator","totalAmount","res","val","NotEnoughBalanceError","OwnedCoinIterator","EntryIterator","suiClient","owner","coinType","reqPageSize","OwnedCoinRequester","SanityError","res","TransactionBlock","normalizeStructTag","parseStructTag","DateTime","NotCreatorError","MPayError","NotRecipientError","MPayError","RpcError","MPayError","msg","context","StreamNotFoundError","MPayError","streamId","DateTime","Duration","MAX_U64","TIME_ROUND_UNIT","roundDateTime","date","dateMs","roundMs","roundDuration","duration","durationMs","Stream","_Stream","globals","streamId","rawData","StreamContract","data","SanityError","pagination","NotCreatorError","txb","TransactionBlock","NotRecipientError","enabled","normalizeStructTag","roundDuration","metadata","decodeMetadata","roundDateTime","rawConfig","duration","rawStatus","MAX_U64","timeNowMs","DateTime","timeStartMs","epoch","res","StreamNotFoundError","RpcError","content","typeParams","parseStructTag","coinType","dataFields","config","status","normalizeStructTag","SUI_TYPE_ARG","Duration","TransactionFailedError","MPayError","status","msg","MIN_INTERVAL_MS","MPayHelper","globals","CoinMetaHelper","MPayBuilder","res","TransactionFailedError","change","info","input","InvalidInputError","cliffFraction","cliffAmount","amountPerStep","timeEnd","intervalMilli","Duration","address","coinType","balance","coinMeta","normalizeStructTag","allBalance","coinMetas","bal","i","txb","val","originTotalAmount","suiClient","normalized","SUI_TYPE_ARG","meta","normalizeStructTag","normalizeSuiAddress","DateTime","InvalidStreamGroupError","MPayError","msg","context","REQUEST_PAGE_SIZE","getObjectsById","suiClient","ids","options","oidIter","ListOidIterator","iter","ObjectBatchIterator","getAllFromIterator","EntryIterator","idIter","ObjectBatchRequester","stringIter","requestPage","objId","res","filtered","filter","StreamGroup","_StreamGroup","globals","streams","InvalidStreamGroupError","gids","st","InvalidInputError","ids","streamObjs","getObjectsById","obj","SanityError","responses","commonInfos","stream","expInfo","isEqual","info","isEqualStreamGroupCommonInfo","i","sum","pagination","Stream","info1","info2","PagedStreamListIterator","_PagedStreamListIterator","it","pageSize","input","StreamListIterator","res","_StreamListIterator","requester","StreamListRequester","SanityError","_StreamListRequester","globals","recipient","groupRefs","query","oidIter","ListOidIterator","ref","ObjectBatchIterator","backendQuery","convertToIncomingBackendQuery","filtered","normalizeSuiAddress","groupedRefs","groupAndSortRefs","convertToOutgoingBackendQuery","sender","refs","stRefs","stream","getStreamFromIterator","isStreamOfQuery","sg","getStreamGroupFromIterator","isStreamGroupOfQuery","m","groupList","gl1","gl2","DateTime","isStatus","isStreamOfStatus","isClaimable","filter","streamId","data","getStreamObjectResponseFromIter","Stream","streamIds","objResponses","StreamGroup","convertStreamStatus","normalizeCoinTypeFilter","normalizeAddressFilter","status","st","sts","convertStreamStatusSingle","InvalidInputError","coinType","ct","normalizeStructTag","address","addr","MSafeAccountAdapter","msafe","reqs","MSafeSingleWallet","account","SingleWalletAdapter","singleWallet","suiClient","req","isSameCoinType","SUI_TYPE_ARG","GAS_OBJECT_SPEC","InvalidInputError","coins","getCoinsWithAmount","SanityError","coin","MPayClient","env","options","Globals","MPayHelper","wallet","adapter","info","streamId","Stream","query","pageSize","PagedStreamListIterator","address","coinType","normalizeStructTag","recipient","normalizeSuiAddress","creator","MPayBuilder","StreamIntention","BaseIntentionLegacy","network","account","mpayClient","MPayClient","MSafeSingleWallet","CancelStreamIntention","StreamIntention","data","TransactionType","input","network","account","TransactionType","ClaimByProxyStreamIntention","StreamIntention","data","TransactionType","input","network","account","TransactionType","ClaimStreamIntention","StreamIntention","data","TransactionType","input","network","account","TransactionType","CreateStreamIntention","StreamIntention","data","TransactionType","input","network","account","bcs","normalizeStructTag","normalizeSuiAddress","MoveCallHelper","_MoveCallHelper","moveCall","txb","argIndex","input","strVal","bcsType","arg","bcsNums","bcsVal","index","CreateStreamDecodeHelper","globals","txb","streamInfo","fees","infos","moveCall","txs","tx","isSameTarget","SanityError","MoveCallHelper","metadata","name","groupId","decodeMetadata","recipient","timeStart","cliff","epochInterval","totalEpoch","amountPerEpoch","cancelable","coinType","info","InvalidInputError","recipients","StreamContract","FeeContract","CreateStreamHelper","arg","DecodeHelper","globals","txb","StreamContract","tx","isSameTarget","CreateStreamDecodeHelper","streamId","enabled","moveCall","MoveCallHelper","TransactionType","SetAutoClaimStreamIntention","StreamIntention","data","TransactionType","input","network","account","MPayAppHelper","input","network","transactionBlock","globals","Globals","result","DecodeHelper","intention","CreateStreamIntention","SetAutoClaimStreamIntention","ClaimStreamIntention","ClaimByProxyStreamIntention","CancelStreamIntention","intentionData","TransactionDefaultApplication","TransactionSubTypes","buildCoinTransferTxb","CoinTransferIntention","_CoinTransferIntention","BaseIntentionLegacy","data","input","suiClient","account","buildCoinTransferTxb","buildObjectTransferTxb","ObjectTransferIntention","_ObjectTransferIntention","BaseIntentionLegacy","data","input","suiClient","account","buildObjectTransferTxb","isSameAddress","TransactionBlock","PlainPayloadIntention","_PlainPayloadIntention","BaseIntentionLegacy","data","input","account","tb","TransactionBlock","isSameAddress","CoreHelper","TransactionDefaultApplication","input","suiClient","account","intention","TransactionSubTypes","CoinTransferIntention","ObjectTransferIntention","PlainPayloadIntention","TransactionType","updated","config","updatePackageId","data","res","packageId","borrowFee","borrowFeeAddress","pool","e","config_default","TransactionType","bcs","normalizeStructTag","normalizeSuiAddress","Decoder","txb","target","trans","config_default","assetId","findPool","pool","claims","helper","MoveCallHelper","optionId","poolId","typeArguments","TransactionType","amount","moveCall","_MoveCallHelper","argIndex","input","strVal","normalizeSuiAddress","bcsType","arg","bcsNums","bcs","bcsVal","index","normalizeStructTag","TransactionBlock","depositToken","txb","pool","coinObject","amount","config_default","withdrawToken","borrowToken","tx","userAddress","borrowBalance","borrowCoin","borrowFeeCoin","repayToken","claimReward","assetId","poolId","option","typeArguments","ClaimRewardIntention","_ClaimRewardIntention","BaseIntentionLegacy","data","claims","tx","TransactionBlock","claim","assetId","poolId","option","typeArguments","claimReward","TransactionBlock","EntryBorrowIntention","_EntryBorrowIntention","BaseIntentionLegacy","data","input","coinType","amount","tx","TransactionBlock","pool","config_default","borrowToken","TransactionBlock","getTokenObjs","client","sender","coinType","result","EntryDepositIntention","_EntryDepositIntention","BaseIntentionLegacy","data","input","suiClient","account","coinType","amount","tx","TransactionBlock","toDeposit","depositToken","config_default","pool","tokenInfo","getTokenObjs","coinObj","i","TransactionBlock","EntryRepayIntention","_EntryRepayIntention","BaseIntentionLegacy","data","input","suiClient","account","coinType","amount","tx","TransactionBlock","toDeposit","repayToken","config_default","pool","tokenInfo","getTokenObjs","coinObj","i","TransactionBlock","EntryWithdrawIntention","_EntryWithdrawIntention","BaseIntentionLegacy","data","coinType","amount","tx","TransactionBlock","pool","config_default","withdrawToken","NAVIAppHelper","input","updatePackageId","transactionBlock","result","Decoder","TransactionType","suiClient","account","intention","EntryDepositIntention","EntryBorrowIntention","EntryRepayIntention","EntryWithdrawIntention","ClaimRewardIntention","TransactionSubTypes","TransactionType","fromHEX","toHEX","Transaction","sortKeys","PlainTransactionApplication","PlainTransactionType","PlainTransactionIntention","_PlainTransactionIntention","data","input","PlainTransactionHelper","transaction","content","account","tx","inspectResult","SuiClient","Transaction","SuiClientLegacy","TransactionBlock","MSafeApps","_MSafeApps","apps","mApps","i","app","SuiJsSdkAdapter","SuiSdkAdapter","appName","helper","input","client","clientLegacy","build","tx","bytes","TransactionType","TransactionType","Decoder","txb","scallop","target","trans","API_BASE_URL","ADDRESSES_ID","PROTOCOL_OBJECT_ID","SCA_COIN_TYPE","OLD_BORROW_INCENTIVE_PROTOCOL_ID","SUPPORT_POOLS","SUPPORT_COLLATERALS","SUPPORT_SPOOLS","SUPPORT_SCOIN","SUPPORT_SPOOLS_REWARDS","SUPPORT_BORROW_INCENTIVE_POOLS","coinDecimals","spoolRewardCoins","borrowIncentiveRewardCoins","coinIds","wormholeCoinIds","voloCoinIds","sCoinIds","bcs","normalizeStructTag","normalizeSuiAddress","MoveCallHelper","_MoveCallHelper","moveCall","txb","argIndex","input","strVal","bcsType","arg","bcsNums","bcsVal","index","bcs","SplitCoinHelper","splitCoin","txb","input","MoveCallHelper","bcsType","bcsNums","bcs","DecoderLending","Decoder","supplyMoveCall","stakeMoveCall","unstakeMoveCall","withdrawMoveCall","redeem","burnScoin","borrowMoveCall","repayMoveCall","lendingIncentive","borrowIncentiveV2","oldBorrowIncentive","OLD_BORROW_INCENTIVE_PROTOCOL_ID","stakeWithVeSca","stakeWithoutVesca","trans","MoveCallHelper","moveCall","TransactionType","veScaKey","obligationKey","obligationId","rewardCoinName","coinName","amount","amountFromSplitCoin","SplitCoinHelper","a","b","stakeSpoolAccount","coinType","stakeAccountWithAmount","tx","stakeAccountId","slippage","validSwapAmount","lendingReward","borrowRewardV2","borrowReward","stakeMarketCoinName","TransactionType","DecoderReferral","Decoder","trans","MoveCallHelper","moveCall","TransactionType","veScaKey","coins","helper","TransactionType","DecoderVesca","Decoder","extendPeriod","stakeMoreSca","moveCall","trans","MoveCallHelper","OLD_BORROW_INCENTIVE_PROTOCOL_ID","veScaKey","TransactionType","lockSca","unlockTime","amountFromSplitCoin","SplitCoinHelper","a","b","isHaveRedeem","oldUnstakeObligation","unstakeObligation","stakeObligation","isObligationLocked","isOldBorrowIncentive","obligationId","obligationKey","operations","i","sortKeys","ScallopCoreBaseIntention","data","BorrowIntention","_BorrowIntention","ScallopCoreBaseIntention","data","input","BorrowWithBoostIntention","_BorrowWithBoostIntention","ScallopCoreBaseIntention","data","input","BorrowWithReferralIntention","_BorrowWithReferralIntention","ScallopCoreBaseIntention","data","input","ClaimIncentiveRewardIntention","_ClaimIncentiveRewardIntention","ScallopCoreBaseIntention","data","input","DepositCollateralIntention","_DepositCollateralIntention","ScallopCoreBaseIntention","data","input","MigrateAndClaimIntention","_MigrateAndClaimIntention","ScallopCoreBaseIntention","data","input","MigrateScoinIntention","_MigrateScoinIntention","ScallopCoreBaseIntention","data","input","MigrateWusdcToUsdcIntention","_MigrateWusdcToUsdcIntention","ScallopCoreBaseIntention","data","input","OpenObligationIntention","_OpenObligationIntention","ScallopCoreBaseIntention","data","input","RepayIntention","_RepayIntention","ScallopCoreBaseIntention","data","input","RepayWithBoostIntention","_RepayWithBoostIntention","ScallopCoreBaseIntention","data","input","StakeSpoolIntention","_StakeSpoolIntention","ScallopCoreBaseIntention","data","input","SupplyLendingIntention","_SupplyLendingIntention","ScallopCoreBaseIntention","data","input","UnstakeSpoolIntention","_UnstakeSpoolIntention","ScallopCoreBaseIntention","data","input","WithdrawAndUnstakeLendingIntention","_WithdrawAndUnstakeLendingIntention","ScallopCoreBaseIntention","data","input","WithdrawCollateralIntention","_WithdrawCollateralIntention","ScallopCoreBaseIntention","data","input","WithdrawLendingIntention","_WithdrawLendingIntention","ScallopCoreBaseIntention","data","input","BindReferralIntention","_BindReferralIntention","ScallopCoreBaseIntention","data","input","ClaimRevenueReferralIntention","_ClaimRevenueReferralIntention","ScallopCoreBaseIntention","data","input","CreateReferralLinkIntention","_CreateReferralLinkIntention","ScallopCoreBaseIntention","data","input","ExtendPeriodAndStakeMoreIntention","_ExtendPeriodAndStakeMoreIntention","ScallopCoreBaseIntention","data","input","ExtendStakePeriodIntention","_ExtendStakePeriodIntention","ScallopCoreBaseIntention","data","input","RedeemScaIntention","_RedeemScaIntention","ScallopCoreBaseIntention","data","input","RenewExpStakePeriodIntention","_RenewExpStakePeriodIntention","ScallopCoreBaseIntention","data","input","StakeScaIntention","_StakeScaIntention","ScallopCoreBaseIntention","data","input","SupplyAndStakeLendingIntention","_SupplyAndStakeLendingIntention","ScallopCoreBaseIntention","data","input","WithdrawStakedScaIntention","_WithdrawStakedScaIntention","ScallopCoreBaseIntention","data","input","ScallopAddress","params","id","path","nestedAddressObj","key","options","response","API_BASE_URL","responseData","TransactionBlock","BigNumber","TransactionBlock","ScallopBuilder","params","instance","address","query","utils","txBlock","assetCoinName","amount","sender","coinType","coins","takeCoin","leftCoin","marketCoinName","marketCoinType","totalAmount","prev","coin","coinIds","value","sCoinName","sCoinType","TransactionBlock","BigNumber","getObligations","query","ownerAddress","owner","protocolObjectId","PROTOCOL_OBJECT_ID","keyObjectsResponse","hasNextPage","nextCursor","paginatedKeyObjectsResponse","keyObjectIds","ref","id","keyObjects","obligations","i","keyId","content","fields","obligationId","locked","getObligationLocked","obligationObjectResponse","obligationLocked","getCoinAmounts","assetCoinNames","updatedAssetCoinNames","SUPPORT_POOLS","coinObjectsResponse","paginatedCoinObjectsResponse","assetCoinName","coinAmounts","response","object","coinObject","type","poolCoinName","BigNumber","getCoinAmount","coinType","coinAmount","getMarketCoinAmounts","marketCoinNames","updatedMarketCoinNames","marketCoinObjectsResponse","paginatedMarketCoinObjectsResponse","marketCoinName","marketCoinAmounts","marketCoinObject","getMarketCoinAmount","marketCoinType","marketCoinAmount","queryObligation","queryTarget","txBlock","TransactionBlock","normalizeStructTag","getStakeAccounts","query","ownerAddress","owner","spoolObjectId","stakeAccountType","stakeObjectsResponse","hasNextPage","nextCursor","paginatedStakeObjectsResponse","stakeAccounts","stakeMarketCoinTypes","types","stakeMarketCoinName","stakeCoinName","marketCoinType","updateTypes","newType","stakeObjectIds","ref","id","stakeObject","type","fields","stakePoolId","stakeType","staked","index","points","totalPoints","getStakePool","marketCoinName","poolId","stakePool","stakePoolObjectResponse","stakePoolObject","maxPoint","distributedPoint","pointPerPeriod","period","maxStake","totalStaked","createdAt","lastUpdate","getStakeRewardPool","stakeRewardPool","stakeRewardPoolObjectResponse","stakeRewardPoolObject","rewardPoolFields","ratioNumerator","ratioDenominator","rewards","claimedRewards","TransactionBlock","normalizeStructTag","BigNumber","requireSender","txBlock","sender","checkLockSca","scaAmountOrCoin","lockPeriodInDays","newUnlockAtInSecondTimestamp","prevUnlockAtInSecondTimestamp","isInitialLock","isLockExpired","checkVesca","checkExtendLockPeriod","checkExtendLockAmount","scaAmount","checkRenewExpiredVeSca","normalizeStructTag","parseStructTag","BigNumber","parseOriginBorrowIncentiveAccountPoolPointData","originBorrowIncentiveAccountPoolPointData","normalizeStructTag","parseOriginBorrowIncentiveAccountData","originBorrowIncentiveAccountData","acc","point","parsed","name","parseStructTag","isMarketCoin","coinName","assetCoinName","SUPPORT_POOLS","SUPPORT_COLLATERALS","SUPPORT_SPOOLS_REWARDS","parseAssetSymbol","findClosestUnlockRound","unlockAtInSecondTimestamp","unlockDate","closestTwelveAM","now","queryBorrowIncentiveAccounts","query","obligationId","sender","borrowIncentiveCoinNames","coinName","SUPPORT_BORROW_INCENTIVE_POOLS","queryPkgId","incentiveAccountsId","queryTarget","txBlock","TransactionBlock","borrowIncentiveAccountsQueryData","borrowIncentiveAccounts","accountData","parsedBorrowIncentiveAccount","parseOriginBorrowIncentiveAccountData","poolType","parsedCoinName","getBindedVeScaKey","address","client","obligationId","borrowIncentiveObjectId","incentiveAccountsId","corePkg","incentiveAccountsObject","incentiveAccountsTableId","bindedIncentiveAcc","getPythPrice","query","assetCoinName","pythFeedObjectId","priceFeedObjectResponse","priceFeedPoolObject","fields","expoMagnitude","expoNegative","priceMagnitude","priceNegative","BigNumber","getVescaKeys","query","ownerAddress","owner","veScaKeyType","keyObjectsResponse","hasNextPage","nextCursor","paginatedKeyObjectsResponse","objResponse","data","getVeScas","keyObjectId","veScas","i","veSca","getVeSca","veScaKeyId","tableId","veScaKeyIdValue","vesca","veScaDynamicFieldObject","dynamicFields","ScallopQuery","params","instance","address","utils","ownerAddress","getObligations","assetCoinNames","getCoinAmounts","assetCoinName","getCoinAmount","marketCoinNames","getMarketCoinAmounts","marketCoinName","getMarketCoinAmount","getPythPrice","getStakeAccounts","stakeMarketCoinName","stakeMarketCoinNames","SUPPORT_SPOOLS","stakePools","i","stakePool","getStakePool","stakeRewardPools","stakeRewardPool","getStakeRewardPool","obligationId","walletAddress","coinNames","queryBorrowIncentiveAccounts","obligation","queryObligation","collateralCoinTypes","collateral","debtCoinTypes","debt","coinType","SUI_TYPE_ARG","normalizeStructTag","ScallopUtils","params","address","coinName","isMarketCoin","assetCoinName","parseAssetSymbol","validCoinName","coinPackageId","coinIds","wormholeCoinIds","voloCoinIds","protocolObjectId","PROTOCOL_OBJECT_ID","coinType","type","normalizeStructTag","coinTypeRegex","coinTypeMatch","isMarketCoinType","wormHoleCoinTypeMap","voloCoinTypeMap","marketCoinName","stakeMarketCoinName","spoolRewardCoins","borrowIncentiveCoinName","borrowIncentiveRewardCoins","coinDecimals","sCoinName","sCoinIds","amount","SUI_TYPE_ARG","ownerAddress","selectedCoins","totalAmount","hasNext","nextCursor","coins","a","b","i","coin","apr","compoundFrequency","apy","txBlock","coinObjectId","coinObjects","objectId","mergedCoin","sendCoin","extendLockPeriodInDay","unlockAtInSecondTimestamp","now","remainingLockPeriod","newUnlockAtInSecondTimestamp","lockPeriod","findClosestUnlockRound","SUPPORT_SCOIN","SUI_CLOCK_OBJECT_ID","SUI_TYPE_ARG","requireVeSca","params","builder","txBlock","veScaKey","veSca","getVeSca","sender","requireSender","veScas","getVeScas","requireObligationInfo","params","builder","txBlock","obligationId","obligationKey","obligationLocked","getObligationLocked","sender","requireSender","obligations","getObligations","selectedObligation","obligation","generateBorrowIncentiveNormalMethod","borrowIncentiveIds","OldBorrowIncentiveContract","veScaIds","SUI_CLOCK_OBJECT_ID","veScaKey","SUI_TYPE_ARG","rewardCoinName","rewardType","generateBorrowIncentiveQuickMethod","normalMethod","obligationArg","obligationtKeyArg","unstakeObligationBeforeStake","txn","OLD_BORROW_INCENTIVE_PROTOCOL_ID","bindedVeScaKey","getBindedVeScaKey","SUI_CLOCK_OBJECT_ID","SUI_CLOCK_OBJECT_ID","axios","PYTH_ENDPOINTS","bcs","SUI_CLOCK_OBJECT_ID","MAX_ARGUMENT_SIZE","PythClient","provider","pythStateId","wormholeStateId","result","objectId","state","vaas","tx","wormholePackageId","verifiedVaas","vaa","verifiedVaa","updates","feedIds","packageId","priceUpdatesHotPotato","priceInfoObjects","baseUpdateFee","coins","coinId","i","priceInfoObjectId","feedId","normalizedFeedId","tableId","fieldType","type","accumulatorMessage","vaaSizeOffset","vaaSize","vaaOffset","getLatestVaas","endpoint","priceIds","axios","vaa","updateOracles","builder","txBlock","assetCoinNames","coinNames","SUPPORT_POOLS","SUPPORT_COLLATERALS","rules","pythClient","PythClient","assetCoinName","endpoints","PYTH_ENDPOINTS","priceUpdateData","e","updateAssetCoinNames","updateOracle","coinType","updatePrice","xOraclePackageId","xOracleId","pythPackageId","pythRegistryId","pythStateId","pythFeedObjectId","switchboardPackageId","switchboardRegistryId","switchboardAggregatorId","supraPackageId","supraRegistryId","supraHolderId","request","priceUpdateRequest","updatePythPrice","updateSwitchboardPrice","updateSupraPrice","confirmPriceUpdateRequest","packageId","validXOracleId","target","typeArgs","SUI_CLOCK_OBJECT_ID","holderId","registryId","validHolderId","validRegistryId","aggregatorId","validAggregatorId","stateId","feedObjectId","validRequest","validStateId","validFeedObjectId","generateSCoinNormalMethod","builder","txBlock","sCoinPkgIds","treasuryIds","SUPPORT_SCOIN","sCoinName","treasuryId","marketCoinName","marketCoin","sCoin","requireObligationInfo","params","txBlock","builder","obligationId","obligationKey","sender","requireSender","obligations","getObligations","generateCoreNormalMethod","coreIds","referralWitnessType","obligation","obligationHotPotato","coin","collateralCoinName","coinType","amount","SUI_CLOCK_OBJECT_ID","poolCoinName","marketCoin","borrowReferral","loan","generateCoreQuickMethod","normalMethod","scoinNormalMethod","generateSCoinNormalMethod","obligationArg","suiCoin","leftCoin","takeCoin","obligationInfo","updateCoinNames","updateOracles","walletAddress","marketCoinName","sCoinName","sCoinAmount","txResult","amountLeft","leftMarketCoin","takeMarketCoin","assetCoinNames","SUI_CLOCK_OBJECT_ID","generateReferralNormalMethod","builder","txBlock","referralIds","veScaTable","veScaKeyId","SUI_CLOCK_OBJECT_ID","poolCoinName","coinType","ticket","veScaKey","generateReferralQuickMethod","normalMethod","walletAddress","coinNames","SUPPORT_POOLS","objToTransfer","i","rewardCoin","coins","SlippageContract","SlippageTxBuilder","tx","resultCoin","slippage","expectedAmount","coinType","SUI_CLOCK_OBJECT_ID","stakeHelper","builder","txBlock","stakeAccount","coinName","amount","sender","isSCoin","scoinNormalMethod","generateSCoinNormalMethod","spoolNormalMethod","generateSpoolNormalMethod","takeCoin","leftCoin","totalAmount","marketCoin","requireStakeAccountIds","params","stakeMarketCoinName","stakeAccountId","requireSender","getStakeAccounts","account","requireStakeAccounts","stakeAccounts","spoolIds","stakePoolIds","rewardPoolIds","stakeMarketCoinTypes","SUPPORT_SPOOLS","spoolId","rewardId","marketCoinType","stakePoolId","SUI_CLOCK_OBJECT_ID","coin","rewardPoolId","rewardCoinName","spoolRewardCoins","rewardCoinType","generateSpoolQuickMethod","normalMethod","scoinMethod","amountOrMarketCoin","stakeAccountIds","createdStakeAccount","stakedMarketCoinAmount","returnSCoin","toTransfer","amountUnstake","amountToUnstake","sCoin","mergedCoin","rewardCoins","accountId","rewardCoin","SUI_CLOCK_OBJECT_ID","generateNormalVeScaMethod","builder","txBlock","veScaIds","scaCoin","unlockAtInSecondTimestamp","SUI_CLOCK_OBJECT_ID","veScaKey","newUnlockAtInSecondTimestamp","generateQuickVeScaMethod","normalMethod","amountOrCoin","lockPeriodInDays","autoCheck","sender","requireSender","veSca","requireVeSca","transferObjects","coins","SCA_COIN_TYPE","takeCoin","leftCoin","newUnlockAt","checkLockSca","isInitialLock","isLockExpired","unlockedSca","checkExtendLockPeriod","scaAmount","checkExtendLockAmount","scaCoins","checkRenewExpiredVeSca","checkVesca","sca","normalizeStructTag","SUI_CLOCK_OBJECT_ID","DeepBookPools","DeepBookContract","DeepBookHelperContract","DeepBookModuleAndMethod","SUI_CLOCK_OBJECT","SUI_CLOCK_OBJECT_ID","getDeepBookPool","coinAName","coinBName","DeepBookPools","DeepBookTxBuilder","tx","DeepBookContract","DeepBookModuleAndMethod","tokenInObject","baseCoinName","quoteCoinName","clientOrderId","accountCap","scallopUtils","pool","aToB","coinAType","coinBType","parsedAccountCap","DeepBookHelperContract","DeepBookSwap","client","currentAddress","accountCap","scallopUtils","id","tx","accountCapsResponse","normalizeStructTag","DeepBookTxBuilder","tokenObjectIn","baseCoinName","quoteCoinName","ScallopClient","params","address","ScallopUtils","ScallopQuery","ScallopBuilder","DeepBookSwap","ownerAddress","owner","stakeMarketCoinName","walletAddress","txBlock","TransactionBlock","coreQuickMethod","generateCoreQuickMethod","borrowIncentiveMethod","generateBorrowIncentiveQuickMethod","sender","obligationId","obligationKey","hotPotato","collateralCoinName","amount","quickMethod","obligations","specificObligationId","obligation","collateralCoin","poolCoinName","scoinMethod","generateSCoinNormalMethod","marketCoin","parseScoin","SUPPORT_SCOIN","scoin","coin","borrowIncentiveQuickMethod","availableStake","SUPPORT_BORROW_INCENTIVE_POOLS","veScaKey","referralMethod","generateReferralNormalMethod","borrowReferral","marketCoinName","spoolQuickMethod","generateSpoolQuickMethod","stakeAccount","stakeAccountId","SUPPORT_SPOOLS","stakeAccounts","targetStakeAccount","account","unstakeAccount","withdrawCoins","i","wdScoin","wdCoin","returnScoin","marketCoins","lendingIncentive","borrowIncentiveV2","borrowIncentive","borrowIncentiveRewarad","rewardCoins","rewardCoin","rewardCoinName","obligationKeyId","isObligationLocked","isOldBorrowIncentive","lockPeriod","vescaKey","vescaQuickMethod","generateQuickVeScaMethod","coins","SCA_COIN_TYPE","takeCoin","leftCoin","newVescaKey","lockPeriodInDays","isHaveRedeem","redeem","accountPoint","poolPoint","borrowAmount","BigNumber","increasePointRate","vescaMethod","referralTicket","referral","generateReferralQuickMethod","coinsName","scoinNormalMethod","toTransfer","sCoinName","sCoins","toDestroyMarketCoin","mergedMarketCoin","e","sCoin","existSCoins","mergedSCoin","slippage","validSwapAmount","marketCoinType","coinIds","value","coinSwap","coinB","accountCap","SlippageTxBuilder","mintedMarketCoin","Scallop","params","ScallopAddress","ADDRESSES_ID","ScallopClient","builder","query","utils","ScallopAppHelper","input","Scallop","transactionBlock","decoderLending","DecoderLending","decoderReferral","DecoderReferral","decoderVesca","DecoderVesca","result","TransactionType","suiClient","account","network","txSubType","intentionData","intention","SupplyLendingIntention","WithdrawLendingIntention","BorrowIntention","RepayIntention","DepositCollateralIntention","WithdrawCollateralIntention","OpenObligationIntention","StakeSpoolIntention","UnstakeSpoolIntention","ClaimIncentiveRewardIntention","BorrowWithBoostIntention","StakeScaIntention","ExtendStakePeriodIntention","ExtendPeriodAndStakeMoreIntention","RenewExpStakePeriodIntention","WithdrawStakedScaIntention","SupplyAndStakeLendingIntention","WithdrawAndUnstakeLendingIntention","RedeemScaIntention","MigrateAndClaimIntention","BorrowWithReferralIntention","CreateReferralLinkIntention","ClaimRevenueReferralIntention","BindReferralIntention","MigrateScoinIntention","RepayWithBoostIntention","MigrateWusdcToUsdcIntention","TransactionType","LENDING_MARKET_ID","LENDING_MARKET_TYPE","SuilendClient","phantom","LendingMarket","TransactionType","PACKAGE_ID","MODULE","Decoder","transaction","transactionEvents","command","fn","indexFilter","index","commands","coinType","value","TransactionType","events","event","Transaction","sortKeys","SuilendBaseIntention","data","BorrowIntention","_BorrowIntention","SuilendBaseIntention","data","input","suiClient","account","suilendClient","obligationOwnerCaps","obligations","transaction","Transaction","Transaction","DepositIntention","_DepositIntention","SuilendBaseIntention","data","input","suiClient","account","suilendClient","obligationOwnerCaps","transaction","Transaction","Transaction","RepayIntention","_RepayIntention","SuilendBaseIntention","data","input","suiClient","account","suilendClient","obligationOwnerCaps","obligations","transaction","Transaction","Transaction","WithdrawIntention","_WithdrawIntention","SuilendBaseIntention","data","input","suiClient","account","suilendClient","obligationOwnerCaps","obligations","transaction","Transaction","getSuilendClient","suiClient","SuilendClient","LendingMarket","phantom","LENDING_MARKET_TYPE","LENDING_MARKET_ID","getObligationOwnerCaps","account","suilendClient","getObligations","obligationOwnerCaps","ownerCap","SuilendAppHelper","input","transaction","digest","transactionWithEvents","result","Decoder","TransactionType","network","txSubType","intentionData","intention","DepositIntention","WithdrawIntention","BorrowIntention","RepayIntention","TransactionType","TurbosSdk","TransactionType","bcs","normalizeStructTag","normalizeSuiAddress","BN","prixConfig","deepbookConfig","getAtoB","layer","target","swap1Layer","swap2Layer","item","Decoder","txb","turbosSdk","config","address","trans","targets","prixConfig","deepbookConfig","moveCall","atob","routes","index","pool","sqrtPrice","nextTickIndex","BN","coinTypeA","coinTypeB","deadline","amountSpecifiedIsInput","amountA","amountB","result","TransactionType","tickLower","tickLowerIsNeg","tickUpper","tickUpperIsNeg","nft","decreaseLiquidity","collectAmountA","collectAmountB","rewardAmounts","helper","poolId","amountIn","token1","token2","MoveCallHelper","_MoveCallHelper","argIndex","input","strVal","normalizeSuiAddress","bcsType","arg","bcsNums","bcs","bcsVal","normalizeStructTag","TurbosSdk","AddLiquidityIntention","_AddLiquidityIntention","BaseIntentionLegacy","data","input","turbosSdk","TurbosSdk","pool","address","amountA","amountB","slippage","tickLower","tickUpper","deadline","txb","TurbosSdk","BurnIntention","_BurnIntention","BaseIntentionLegacy","data","input","turbosSdk","TurbosSdk","pool","nft","txb","TurbosSdk","CollectFeeIntention","_CollectFeeIntention","BaseIntentionLegacy","data","input","turbosSdk","TurbosSdk","pool","address","nft","collectAmountA","collectAmountB","deadline","txb","TurbosSdk","CollectRewardIntention","_CollectRewardIntention","BaseIntentionLegacy","data","input","turbosSdk","TurbosSdk","pool","address","nft","rewardAmounts","deadline","txb","TurbosSdk","CreatePoolIntention","_CreatePoolIntention","BaseIntentionLegacy","data","input","turbosSdk","TurbosSdk","fee","address","tickLower","tickUpper","sqrtPrice","slippage","coinTypeA","coinTypeB","amountA","amountB","deadline","txb","TurbosSdk","DecreaseLiquidityIntention","_DecreaseLiquidityIntention","BaseIntentionLegacy","data","input","turbosSdk","TurbosSdk","pool","address","amountA","amountB","slippage","nft","decreaseLiquidity","deadline","txb","TurbosSdk","IncreaseLiquidityIntention","_IncreaseLiquidityIntention","BaseIntentionLegacy","data","input","turbosSdk","TurbosSdk","pool","address","amountA","amountB","slippage","nft","deadline","txb","TransactionBlock","SUI_CLOCK_OBJECT_ID","PrixClaimIntention","_PrixClaimIntention","BaseIntentionLegacy","data","input","txb","TransactionBlock","prixConfig","SUI_CLOCK_OBJECT_ID","TransactionBlock","PrixJoinIntention","_PrixJoinIntention","BaseIntentionLegacy","data","input","txb","TransactionBlock","prixConfig","TransactionBlock","TurbosSdk","RemoveLiquidityIntention","_RemoveLiquidityIntention","BaseIntentionLegacy","data","input","turbosSdk","TurbosSdk","txb","TransactionBlock","TurbosSdk","SwapIntention","_SwapIntention","BaseIntentionLegacy","data","input","turbosSdk","TurbosSdk","routes","coinTypeA","coinTypeB","address","amountA","amountB","slippage","amountSpecifiedIsInput","deadline","txb","TurbosSdk","normalizeSuiObjectId","TransactionBlock","unstable_getObjectId","SuiKit","turbosSdk","currentAddress","type","amount","coinObjects","coinFields","resultCoinObjects","currentBalance","coinA","coinB","object","coins","txb","sendCoin","mergeCoin","coin","dynamicFields","deepbookConfig","unstable_getObjectId","cap","token","client_order_id","gasBudget","swap_exact_quote_for_base","options","token1","token2","poolId","amountIn","currentAddress","turbosSdk","txb","TransactionBlock","suiKit","SuiKit","coinsData","sendCoin","mergeCoin","currentAccountCap","accountCap","base_coin_ret","quote_coin_ret","_amount","deepbookConfig","normalizeSuiObjectId","swap_exact_base_for_quote","zero","SwapExactBaseForQuoteIntention","_SwapExactBaseForQuoteIntention","BaseIntentionLegacy","data","input","turbosSdk","TurbosSdk","swap_exact_base_for_quote","TurbosSdk","SwapExactQuoteForBaseIntention","_SwapExactQuoteForBaseIntention","BaseIntentionLegacy","data","input","turbosSdk","TurbosSdk","swap_exact_quote_for_base","TURBOSAppHelper","input","turbosSdk","TurbosSdk","contract","transactionBlock","account","result","Decoder","TransactionType","suiClient","network","intention","CreatePoolIntention","AddLiquidityIntention","IncreaseLiquidityIntention","DecreaseLiquidityIntention","RemoveLiquidityIntention","CollectFeeIntention","CollectRewardIntention","BurnIntention","SwapIntention","PrixJoinIntention","PrixClaimIntention","SwapExactBaseForQuoteIntention","SwapExactQuoteForBaseIntention","TransactionType","TransactionType","bcs","normalizeStructTag","normalizeSuiAddress","config","config_default","Decoder","txb","target","trans","config_default","amount","TransactionType","ticketId","moveCall","MoveCallHelper","_MoveCallHelper","argIndex","input","strVal","normalizeSuiAddress","bcsType","arg","bcsNums","bcs","bcsVal","index","normalizeStructTag","TransactionBlock","ClaimTicketIntention","_ClaimTicketIntention","BaseIntentionLegacy","data","input","tx","TransactionBlock","ticketId","config_default","TransactionBlock","StakeIntention","_StakeIntention","BaseIntentionLegacy","data","input","tx","TransactionBlock","amount","coin","config_default","TransactionBlock","UnStakeIntention","_UnStakeIntention","BaseIntentionLegacy","data","input","tx","TransactionBlock","amount","coins","primaryCoin","mergeCoins","coin","config_default","primaryCoinInput","VoloAppHelper","input","transactionBlock","result","Decoder","TransactionType","suiClient","account","intention","StakeIntention","UnStakeIntention","ClaimTicketIntention","appHelpers","MSafeApps","CoreHelper","NAVIAppHelper","MPayAppHelper","PlainTransactionHelper","CetusHelper","TURBOSAppHelper","ScallopAppHelper","VoloAppHelper","BucketHelper","SuilendAppHelper"]}
1
+ {"version":3,"sources":["../src/apps/bucket/helper.ts","../src/apps/bucket/intentions/psm.ts","../src/apps/interface/sui.ts","../src/apps/bucket/api/psm.ts","../src/apps/bucket/api/config.ts","../src/apps/cetus/helper.ts","../src/apps/cetus/intentions/add-liquidity.ts","../src/apps/cetus/api/config.ts","../src/apps/cetus/api/position.ts","../src/apps/cetus/intentions/claim-fee-and-mining.ts","../src/apps/cetus/intentions/decrease-liquidity.ts","../src/apps/cetus/intentions/farming-add.ts","../src/apps/cetus/api/farming.ts","../src/apps/cetus/intentions/farming-batch-harvest.ts","../src/apps/cetus/intentions/farming-claim-fee-and-rewards.ts","../src/apps/cetus/intentions/farming-decrease.ts","../src/apps/cetus/intentions/farming-harvest.ts","../src/apps/cetus/intentions/farming-increase.ts","../src/apps/cetus/intentions/farming-remove.ts","../src/apps/cetus/intentions/farming-stake.ts","../src/apps/cetus/intentions/farming-unstake.ts","../src/apps/cetus/intentions/increase-liquidity.ts","../src/apps/cetus/intentions/remove-liquidity.ts","../src/apps/cetus/intentions/swap.ts","../src/apps/cetus/api/swap.ts","../src/apps/cetus/intentions/vesting-redeem.ts","../src/apps/cetus/api/vesting.ts","../src/apps/cetus/intentions/xcetus-cancel.ts","../src/apps/cetus/api/xcetus.ts","../src/apps/cetus/intentions/xcetus-claim.ts","../src/apps/cetus/intentions/xcetus-convert.ts","../src/apps/cetus/intentions/xcetus-redeem.ts","../src/apps/cetus/intentions/xcetus-redeem-lock.ts","../src/apps/mpay/cancel-stream.ts","../src/apps/interface/sui-js.ts","../src/apps/mpay/common/env.ts","../src/apps/mpay/config/dev.json","../src/apps/mpay/config/prod.json","../src/apps/mpay/common/globals.ts","../src/apps/mpay/error/base.ts","../src/apps/mpay/error/NoBackendError.ts","../src/apps/mpay/error/WalletNotConnectedError.ts","../src/apps/mpay/stream/backend.ts","../src/apps/mpay/error/BackendError.ts","../src/apps/mpay/stream/client.ts","../src/apps/mpay/builder/MPayBuilder.ts","../src/apps/mpay/builder/CreateStreamHelper.ts","../src/apps/mpay/builder/const.ts","../src/apps/mpay/common/transaction.ts","../src/apps/mpay/contract/InspectViewer.ts","../src/apps/mpay/error/InvalidRpcResultError.ts","../src/apps/mpay/stream/metadata.ts","../src/apps/mpay/error/InvalidInputError.ts","../src/apps/mpay/sui/utils.ts","../src/apps/mpay/types/wallet.ts","../src/apps/mpay/utils/random.ts","../src/apps/mpay/contract/BaseContract.ts","../src/apps/mpay/const.ts","../src/apps/mpay/contract/FeeContract.ts","../src/apps/mpay/contract/StreamContract.ts","../src/apps/mpay/error/SanityError.ts","../src/apps/mpay/sui/iterator/iterator.ts","../src/apps/mpay/error/NotEnoughBalanceError.ts","../src/apps/mpay/sui/iterator/coin.ts","../src/apps/mpay/stream/Stream.ts","../src/apps/mpay/error/NotCreatorError.ts","../src/apps/mpay/error/NotRecipientError.ts","../src/apps/mpay/error/RpcError.ts","../src/apps/mpay/error/StreamNotFoundError.ts","../src/apps/mpay/utils/utils.ts","../src/apps/mpay/stream/helper.ts","../src/apps/mpay/error/TransactionFailedError.ts","../src/apps/mpay/stream/query.ts","../src/apps/mpay/error/InvalidStreamGroupError.ts","../src/apps/mpay/sui/iterator/object.ts","../src/apps/mpay/stream/StreamGroup.ts","../src/apps/mpay/intention.ts","../src/apps/mpay/claim-by-proxy-stream.ts","../src/apps/mpay/claim-stream.ts","../src/apps/mpay/create-stream.ts","../src/apps/mpay/decoder/moveCall.ts","../src/apps/mpay/decoder/create.ts","../src/apps/mpay/decoder/decoder.ts","../src/apps/mpay/set-auto-claim-stream.ts","../src/apps/mpay/helper.ts","../src/apps/msafe-core/helper.ts","../src/apps/msafe-core/coin-transfer.ts","../src/apps/msafe-core/object-transfer.ts","../src/apps/msafe-core/plain-payload.ts","../src/apps/navi/helper.ts","../src/apps/navi/config.ts","../src/apps/navi/decoder.ts","../src/apps/navi/intentions/claim-reward.ts","../src/apps/navi/api/incentiveV2.ts","../src/apps/navi/intentions/entry-borrow.ts","../src/apps/navi/intentions/entry-deposit.ts","../src/apps/navi/utils/token.ts","../src/apps/navi/intentions/entry-repay.ts","../src/apps/navi/intentions/entry-withdraw.ts","../src/apps/plain-transaction/helper.ts","../src/apps/registry.ts","../src/apps/scallop/helper.ts","../src/apps/scallop/decoders/decoderLending.ts","../src/apps/scallop/decoders/decoder.ts","../src/apps/scallop/constants/common.ts","../src/apps/scallop/constants/enum.ts","../src/apps/scallop/utils/moveCallHelper.ts","../src/apps/scallop/utils/splitCoinHelper.ts","../src/apps/scallop/decoders/decoderReferral.ts","../src/apps/scallop/decoders/decoderVesca.ts","../src/apps/scallop/intentions/scallopCoreBaseIntention.ts","../src/apps/scallop/intentions/lending/borrow.ts","../src/apps/scallop/intentions/lending/borrow-with-boost.ts","../src/apps/scallop/intentions/lending/borrow-with-referral.ts","../src/apps/scallop/intentions/lending/claim-incentive-reward.ts","../src/apps/scallop/intentions/lending/deposit-collateral.ts","../src/apps/scallop/intentions/lending/migrate-and-claim.ts","../src/apps/scallop/intentions/lending/migrate-scoin.ts","../src/apps/scallop/intentions/lending/migrate-wusd-to-usdc.ts","../src/apps/scallop/intentions/lending/open-obligation.ts","../src/apps/scallop/intentions/lending/repay.ts","../src/apps/scallop/intentions/lending/repay-with-boost.ts","../src/apps/scallop/intentions/lending/stake-spool.ts","../src/apps/scallop/intentions/lending/supply-lending.ts","../src/apps/scallop/intentions/lending/unstake-spool.ts","../src/apps/scallop/intentions/lending/withdraw-and-unstake-lending.ts","../src/apps/scallop/intentions/lending/withdraw-collateral.ts","../src/apps/scallop/intentions/lending/withdraw-lending.ts","../src/apps/scallop/intentions/referral/bind-referral.ts","../src/apps/scallop/intentions/referral/claim-revenue-referral.ts","../src/apps/scallop/intentions/referral/create-referral-link.ts","../src/apps/scallop/intentions/staking/extend-period-and-stake-more.ts","../src/apps/scallop/intentions/staking/extend-stake-period.ts","../src/apps/scallop/intentions/staking/redeem-sca.ts","../src/apps/scallop/intentions/staking/renew-exp-stake-period.ts","../src/apps/scallop/intentions/staking/stake-sca.ts","../src/apps/scallop/intentions/staking/supply-and-stake-lending.ts","../src/apps/scallop/intentions/staking/withdraw-staked-sca.ts","../src/apps/scallop/models/scallopAddress.ts","../src/apps/scallop/models/scallopClient.ts","../src/apps/scallop/models/scallopBuilder.ts","../src/apps/scallop/queries/coreQuery.ts","../src/apps/scallop/queries/spoolQuery.ts","../src/apps/scallop/queries/borrowIncentiveQuery.ts","../src/apps/scallop/utils/builder.ts","../src/apps/scallop/utils/query.ts","../src/apps/scallop/utils/util.ts","../src/apps/scallop/queries/priceQuery.ts","../src/apps/scallop/queries/vescaQuery.ts","../src/apps/scallop/models/scallopQuery.ts","../src/apps/scallop/models/scallopUtils.ts","../src/apps/scallop/builders/borrowIncentiveBuilder.ts","../src/apps/scallop/builders/coreBuilder.ts","../src/apps/scallop/builders/oracle.ts","../src/apps/scallop/constants/pyth.ts","../src/apps/scallop/models/pythClient.ts","../src/apps/scallop/builders/sCoinBuilder.ts","../src/apps/scallop/builders/referralBuilder.ts","../src/apps/scallop/builders/slipPageBuilder.ts","../src/apps/scallop/builders/spoolBuilder.ts","../src/apps/scallop/builders/vescaBuilder.ts","../src/apps/scallop/swap/deepbook/swap.ts","../src/apps/scallop/swap/deepbook/txbuilder.ts","../src/apps/scallop/swap/deepbook/contract.ts","../src/apps/scallop/models/scallop.ts","../src/apps/suilend/helper.ts","../src/apps/suilend/decoder.ts","../src/apps/suilend/intentions/borrow.ts","../src/apps/suilend/intentions/suilendBaseIntention.ts","../src/apps/suilend/intentions/claimRewards.ts","../src/apps/suilend/intentions/deposit.ts","../src/apps/suilend/intentions/repay.ts","../src/apps/suilend/intentions/withdraw.ts","../src/apps/turbos/helper.ts","../src/apps/turbos/decoder.ts","../src/apps/turbos/config.ts","../src/apps/turbos/intentions/add-liquidity.ts","../src/apps/turbos/intentions/burn.ts","../src/apps/turbos/intentions/collect-fee.ts","../src/apps/turbos/intentions/collect-reward.ts","../src/apps/turbos/intentions/create-pool.ts","../src/apps/turbos/intentions/decrease-liquidity.ts","../src/apps/turbos/intentions/increase-liquidity.ts","../src/apps/turbos/intentions/prix-claim.ts","../src/apps/turbos/intentions/prix-join.ts","../src/apps/turbos/intentions/remove-liquidity.ts","../src/apps/turbos/intentions/swap.ts","../src/apps/turbos/intentions/swap-exact-base-for-quote.ts","../src/apps/turbos/api/deepbook.ts","../src/apps/turbos/utils/sui-kit.ts","../src/apps/turbos/intentions/swap-exact-quote-for-base.ts","../src/apps/volo/helper.ts","../src/apps/volo/decoder.ts","../src/apps/volo/config.ts","../src/apps/volo/intentions/claimTicket.ts","../src/apps/volo/intentions/stake.ts","../src/apps/volo/intentions/unStake.ts","../src/index.ts"],"sourcesContent":["import { TransactionType } from '@msafe/sui3-utils';\nimport { SuiClient } from '@mysten/sui/client';\nimport { Transaction } from '@mysten/sui/transactions';\nimport { IdentifierString, WalletAccount } from '@mysten/wallet-standard';\n\nimport { IAppHelperInternal } from '@/apps/interface/sui';\nimport { SuiNetworks } from '@/types';\n\nimport { PsmIntention } from './intentions/psm';\nimport { BucketIntentionData, TransactionSubType } from './types';\n\nexport type BucketIntention = PsmIntention;\n\nexport class BucketHelper implements IAppHelperInternal<BucketIntentionData> {\n application = 'bucket';\n\n supportSDK = '@mysten/sui' as const;\n\n // TODO: Please refer to the documentation and move the `action` and `txbParams` params into the `appContext` structure.\n async deserialize(input: {\n transaction: Transaction;\n chain: IdentifierString;\n network: SuiNetworks;\n suiClient: SuiClient;\n account: WalletAccount;\n action?: string;\n txbParams?: any;\n }): Promise<{ txType: TransactionType; txSubType: string; intentionData: BucketIntentionData }> {\n console.log('Bucket helper deserialize input: ', input);\n const { txbParams, action } = input;\n\n return {\n txType: TransactionType.Other,\n txSubType: action,\n intentionData: {\n txbParams: { ...txbParams },\n action,\n },\n };\n }\n\n async build(input: {\n intentionData: BucketIntentionData;\n txType: TransactionType;\n txSubType: string;\n suiClient: SuiClient;\n account: WalletAccount;\n network: SuiNetworks;\n }): Promise<Transaction> {\n const { suiClient, account, network } = input;\n\n let intention: BucketIntention;\n switch (input.txSubType) {\n case TransactionSubType.Psm:\n intention = PsmIntention.fromData(input.intentionData);\n break;\n default:\n throw new Error('not implemented');\n }\n\n return intention.build({ suiClient, account, network });\n }\n}\n","import { TransactionType } from '@msafe/sui3-utils';\nimport { SuiClient } from '@mysten/sui/client';\nimport { Transaction } from '@mysten/sui/transactions';\nimport { WalletAccount } from '@mysten/wallet-standard';\n\nimport { BaseIntention } from '@/apps/interface/sui';\nimport { SuiNetworks } from '@/types';\n\nimport { BucketIntentionData, TransactionSubType } from '../types';\nimport { getPsmTx } from '../api/psm';\n\nexport class PsmIntention extends BaseIntention<BucketIntentionData> {\n txType = TransactionType.Other;\n\n txSubType = TransactionSubType.Psm;\n\n constructor(public readonly data: BucketIntentionData) {\n super(data);\n }\n\n async build(input: { network: SuiNetworks; suiClient: SuiClient; account: WalletAccount }): Promise<Transaction> {\n const { account, network } = input;\n const { txbParams } = this.data;\n\n const tx = await getPsmTx(txbParams, account, network);\n return tx;\n }\n\n static fromData(data: BucketIntentionData) {\n return new PsmIntention(data);\n }\n}\n","// interface for @mysten/sui package\nimport { TransactionType } from '@msafe/sui3-utils';\nimport { SuiClient } from '@mysten/sui/client';\nimport { Transaction } from '@mysten/sui/transactions';\nimport { IdentifierString, WalletAccount } from '@mysten/wallet-standard';\nimport sortKeys from 'sort-keys-recursive';\n\nimport { SuiNetworks } from '@/types';\n\nexport interface IAppHelperInternal<T> {\n application: string;\n supportSDK: '@mysten/sui';\n\n deserialize(input: {\n transaction: Transaction;\n chain: IdentifierString;\n network: SuiNetworks;\n suiClient: SuiClient;\n account: WalletAccount;\n appContext?: any;\n }): Promise<{\n txType: TransactionType;\n txSubType: string;\n intentionData: T;\n }>;\n\n build(input: {\n network: SuiNetworks;\n txType: TransactionType;\n txSubType: string;\n intentionData: T;\n suiClient: SuiClient;\n account: WalletAccount;\n }): Promise<Transaction>;\n}\n\nexport interface TransactionIntention<D> {\n txType: TransactionType;\n txSubType: string;\n data: D;\n\n serialize(): string;\n\n build(input: { suiClient: SuiClient; account: WalletAccount; network: SuiNetworks }): Promise<Transaction>;\n}\n\nexport abstract class BaseIntention<D> implements TransactionIntention<D> {\n abstract txType: TransactionType;\n\n abstract txSubType: string;\n\n protected constructor(public readonly data: D) {}\n\n abstract build(input: { network: SuiNetworks; suiClient: SuiClient; account: WalletAccount }): Promise<Transaction>;\n\n serialize() {\n return JSON.stringify(sortKeys(this.data));\n }\n}\n","import { SuiNetworks } from \"@/types\";\nimport { Transaction } from \"@mysten/sui/transactions\";\nimport { WalletAccount } from '@mysten/wallet-standard';\nimport { getBucketClient } from \"./config\";\n\nexport interface PsmIntentionData {\n coin: string;\n amount: string;\n isIn: boolean;\n}\n\nexport const getPsmTx = async (\n txbParams: PsmIntentionData,\n account: WalletAccount,\n network: SuiNetworks,\n): Promise<Transaction> => {\n const { coin, amount, isIn } = txbParams;\n\n const tx = new Transaction();\n const client = getBucketClient(network, account);\n await client.getPsmTx(tx, coin, amount, isIn, account.address);\n\n return tx;\n};\n","import { SuiNetworks } from '@/types';\nimport { WalletAccount } from '@mysten/wallet-standard';\nimport { BucketClient } from 'bucket-protocol-sdk';\n\nexport const getBucketClient = (network: SuiNetworks, account: WalletAccount) => {\n const config = network === 'sui:mainnet' ? 'mainnet' : 'testnet';\n const client = new BucketClient(config, account.address);\n return client;\n};\n","import { TransactionType } from '@msafe/sui3-utils';\nimport { SuiClient } from '@mysten/sui/client';\nimport { Transaction } from '@mysten/sui/transactions';\nimport { IdentifierString, WalletAccount } from '@mysten/wallet-standard';\n\nimport { IAppHelperInternal } from '@/apps/interface/sui';\n\nimport { AddLiquidityIntention } from './intentions/add-liquidity';\nimport { ClaimFeeAndMiningIntention } from './intentions/claim-fee-and-mining';\nimport { DecreaseLiquidityIntention } from './intentions/decrease-liquidity';\nimport { FarmingAddLiquidityIntention } from './intentions/farming-add';\nimport { FarmingBatchHarvestIntention } from './intentions/farming-batch-harvest';\nimport { FarmingClaimFeeAndRewardIntention } from './intentions/farming-claim-fee-and-rewards';\nimport { FarmingDecreaseLiquidityIntention } from './intentions/farming-decrease';\nimport { FarmingHarvestIntention } from './intentions/farming-harvest';\nimport { FarmingIncreaseLiquidityIntention } from './intentions/farming-increase';\nimport { FarmingRemoveLiquidityIntention } from './intentions/farming-remove';\nimport { FarmingStakeIntention } from './intentions/farming-stake';\nimport { FarmingUnstakeIntention } from './intentions/farming-unstake';\nimport { IncreaseLiquidityIntention } from './intentions/increase-liquidity';\nimport { RemoveLiquidityIntention } from './intentions/remove-liquidity';\nimport { SwapIntention } from './intentions/swap';\nimport { VestingRedeemIntention } from './intentions/vesting-redeem';\nimport { XcetusCancelIntention } from './intentions/xcetus-cancel';\nimport { XcetusClaimingStakeRewardsIntention } from './intentions/xcetus-claim';\nimport { XcetusConvertIntention } from './intentions/xcetus-convert';\nimport { XcetusRedeemIntention } from './intentions/xcetus-redeem';\nimport { XcetusRedeemLockIntention } from './intentions/xcetus-redeem-lock';\nimport { SuiNetworks, CetusIntentionData, TransactionSubType } from './types';\n\nexport type CetusIntention =\n | AddLiquidityIntention\n | IncreaseLiquidityIntention\n | FarmingAddLiquidityIntention\n | FarmingIncreaseLiquidityIntention\n | DecreaseLiquidityIntention\n | RemoveLiquidityIntention\n | ClaimFeeAndMiningIntention\n | FarmingDecreaseLiquidityIntention\n | FarmingRemoveLiquidityIntention\n | FarmingClaimFeeAndRewardIntention\n | FarmingHarvestIntention\n | FarmingBatchHarvestIntention\n | FarmingStakeIntention\n | FarmingUnstakeIntention\n | XcetusConvertIntention\n | XcetusRedeemLockIntention\n | XcetusClaimingStakeRewardsIntention\n | XcetusCancelIntention\n | XcetusRedeemIntention\n | VestingRedeemIntention\n | SwapIntention;\n\nexport class CetusHelper implements IAppHelperInternal<CetusIntentionData> {\n application = 'cetus';\n\n supportSDK = '@mysten/sui' as const;\n\n // TODO: Please refer to the documentation and move the `action` and `txbParams` params into the `appContext` structure.\n async deserialize(input: {\n transaction: Transaction;\n chain: IdentifierString;\n network: SuiNetworks;\n suiClient: SuiClient;\n account: WalletAccount;\n action?: string;\n txbParams?: any;\n }): Promise<{ txType: TransactionType; txSubType: string; intentionData: CetusIntentionData }> {\n console.log('Cetus helper deserialize input: ', input);\n const { txbParams, action } = input;\n\n return {\n txType: TransactionType.Other,\n txSubType: action,\n intentionData: {\n txbParams: { ...txbParams },\n action,\n },\n };\n }\n\n async build(input: {\n intentionData: CetusIntentionData;\n txType: TransactionType;\n txSubType: string;\n suiClient: SuiClient;\n account: WalletAccount;\n network: SuiNetworks;\n }): Promise<Transaction> {\n const { suiClient, account, network } = input;\n\n let intention: CetusIntention;\n switch (input.txSubType) {\n case TransactionSubType.OpenAndAddLiquidity:\n intention = AddLiquidityIntention.fromData(input.intentionData);\n break;\n case TransactionSubType.IncreaseLiquidity:\n intention = IncreaseLiquidityIntention.fromData(input.intentionData);\n break;\n case TransactionSubType.DecreaseLiquidity:\n intention = DecreaseLiquidityIntention.fromData(input.intentionData);\n break;\n case TransactionSubType.RemoveLiquidity:\n intention = RemoveLiquidityIntention.fromData(input.intentionData);\n break;\n case TransactionSubType.ClaimFeeAndMining:\n intention = ClaimFeeAndMiningIntention.fromData(input.intentionData);\n break;\n case TransactionSubType.FarmingOpenAndAddLiquidity:\n intention = FarmingAddLiquidityIntention.fromData(input.intentionData);\n break;\n case TransactionSubType.FarmingIncreaseLiquidity:\n intention = FarmingIncreaseLiquidityIntention.fromData(input.intentionData);\n break;\n case TransactionSubType.FarmingDecreaseLiquidity:\n intention = FarmingDecreaseLiquidityIntention.fromData(input.intentionData);\n break;\n case TransactionSubType.FarmingRemoveLiquidity:\n intention = FarmingRemoveLiquidityIntention.fromData(input.intentionData);\n break;\n case TransactionSubType.FarmingClaimFeeAndReward:\n intention = FarmingClaimFeeAndRewardIntention.fromData(input.intentionData);\n break;\n case TransactionSubType.FarmingHarvest:\n intention = FarmingHarvestIntention.fromData(input.intentionData);\n break;\n case TransactionSubType.FarmingBatchHarvest:\n intention = FarmingBatchHarvestIntention.fromData(input.intentionData);\n break;\n case TransactionSubType.FarmingStake:\n intention = FarmingStakeIntention.fromData(input.intentionData);\n break;\n case TransactionSubType.FarmingUnstake:\n intention = FarmingUnstakeIntention.fromData(input.intentionData);\n break;\n case TransactionSubType.xCETUSConvert:\n intention = XcetusConvertIntention.fromData(input.intentionData);\n break;\n case TransactionSubType.xCETUSRedeemLock:\n intention = XcetusRedeemLockIntention.fromData(input.intentionData);\n break;\n case TransactionSubType.xCETUSClaimStakingRwewards:\n intention = XcetusClaimingStakeRewardsIntention.fromData(input.intentionData);\n break;\n case TransactionSubType.xCETUSCancelRedeem:\n intention = XcetusCancelIntention.fromData(input.intentionData);\n break;\n case TransactionSubType.xCETUSRedeem:\n intention = XcetusRedeemIntention.fromData(input.intentionData);\n break;\n case TransactionSubType.VestingRedeem:\n intention = VestingRedeemIntention.fromData(input.intentionData);\n break;\n case TransactionSubType.Swap:\n intention = SwapIntention.fromData(input.intentionData);\n break;\n default:\n throw new Error('not implemented');\n }\n\n return intention.build({ suiClient, account, network });\n }\n}\n","import { TransactionType } from '@msafe/sui3-utils';\nimport { SuiClient } from '@mysten/sui/client';\nimport { Transaction } from '@mysten/sui/transactions';\nimport { WalletAccount } from '@mysten/wallet-standard';\n\nimport { BaseIntention } from '@/apps/interface/sui';\nimport { SuiNetworks } from '@/types';\n\nimport { getAddLiquidityTxb } from '../api/position';\nimport { CetusIntentionData, TransactionSubType } from '../types';\n\nexport class AddLiquidityIntention extends BaseIntention<CetusIntentionData> {\n txType = TransactionType.Other;\n\n txSubType = TransactionSubType.OpenAndAddLiquidity;\n\n constructor(public readonly data: CetusIntentionData) {\n super(data);\n }\n\n async build(input: { network: SuiNetworks; suiClient: SuiClient; account: WalletAccount }): Promise<Transaction> {\n const { account, network } = input;\n const { txbParams } = this.data;\n const txb = await getAddLiquidityTxb(txbParams, account, network);\n return txb;\n }\n\n static fromData(data: CetusIntentionData) {\n return new AddLiquidityIntention(data);\n }\n}\n","import { AggregatorClient, Env } from '@cetusprotocol/aggregator-sdk';\nimport { CetusPeripherySDK, SdkOptions as PeripherySdkOptions } from '@cetusprotocol/cetus-periphery-sdk';\nimport { CetusClmmSDK, SdkOptions } from '@cetusprotocol/cetus-sui-clmm-sdk';\nimport { SuiClient } from '@mysten/sui/client';\nimport { WalletAccount } from '@mysten/wallet-standard';\n\nimport { SuiNetworks } from '../types';\n\nexport const clmmConfig: SdkOptions = {\n fullRpcUrl: 'https://fullnode.mainnet.sui.io/',\n simulationAccount: {\n address: '0x326ce9894f08dcaa337fa232641cc34db957aec9ff6614c1186bc9a7508df0bb',\n },\n cetus_config: {\n package_id: '0x95b8d278b876cae22206131fb9724f701c9444515813042f54f0a426c9a3bc2f',\n published_at: '0x95b8d278b876cae22206131fb9724f701c9444515813042f54f0a426c9a3bc2f',\n config: {\n coin_list_id: '0x8cbc11d9e10140db3d230f50b4d30e9b721201c0083615441707ffec1ef77b23',\n launchpad_pools_id: '0x1098fac992eab3a0ab7acf15bb654fc1cf29b5a6142c4ef1058e6c408dd15115',\n clmm_pools_id: '0x15b6a27dd9ae03eb455aba03b39e29aad74abd3757b8e18c0755651b2ae5b71e',\n admin_cap_id: '0x39d78781750e193ce35c45ff32c6c0c3f2941fa3ddaf8595c90c555589ddb113',\n global_config_id: '0x0408fa4e4a4c03cc0de8f23d0c2bbfe8913d178713c9a271ed4080973fe42d8f',\n coin_list_handle: '0x49136005e90e28c4695419ed4194cc240603f1ea8eb84e62275eaff088a71063',\n launchpad_pools_handle: '0x5e194a8efcf653830daf85a85b52e3ae8f65dc39481d54b2382acda25068375c',\n clmm_pools_handle: '0x37f60eb2d9d227949b95da8fea810db3c32d1e1fa8ed87434fc51664f87d83cb',\n },\n },\n clmm_pool: {\n package_id: '0x1eabed72c53feb3805120a081dc15963c204dc8d091542592abaf7a35689b2fb',\n published_at: '0x70968826ad1b4ba895753f634b0aea68d0672908ca1075a2abdf0fc9e0b2fc6a',\n version: 4,\n config: {\n pools_id: '0xf699e7f2276f5c9a75944b37a0c5b5d9ddfd2471bf6242483b03ab2887d198d0',\n global_config_id: '0xdaa46292632c3c4d8f31f23ea0f9b36a28ff3677e9684980e4438403a67a3d8f',\n global_vault_id: '0xce7bceef26d3ad1f6d9b6f13a953f053e6ed3ca77907516481ce99ae8e588f2b',\n admin_cap_id: '0x89c1a321291d15ddae5a086c9abc533dff697fde3d89e0ca836c41af73e36a75',\n },\n },\n integrate: {\n package_id: '0x996c4d9480708fb8b92aa7acf819fb0497b5ec8e65ba06601cae2fb6db3312c3',\n published_at: '0x8faab90228e4c4df91c41626bbaefa19fc25c514405ac64de54578dec9e6f5ee',\n version: 6,\n },\n deepbook: {\n package_id: '0x000000000000000000000000000000000000000000000000000000000000dee9',\n published_at: '0x000000000000000000000000000000000000000000000000000000000000dee9',\n },\n deepbook_endpoint_v2: {\n package_id: '0x92aee86c01c79146d23938a00c7fff725ee0688c389be36d1bcbe03761b466c6',\n published_at: '0x92aee86c01c79146d23938a00c7fff725ee0688c389be36d1bcbe03761b466c6',\n },\n aggregatorUrl: 'https://api-sui.cetus.zone/router',\n swapCountUrl: 'https://api-sui.cetus.zone/v2/sui/swap/count',\n};\n\nexport const peripheryConfig: PeripherySdkOptions = {\n launchpad: {\n package_id: '0x80d114c5d474eabc2eb2fcd1a0903f1eb5b5096a8dc4184d72453f7a9be728e4',\n published_at: '0x80d114c5d474eabc2eb2fcd1a0903f1eb5b5096a8dc4184d72453f7a9be728e4',\n config: {\n pools_id: '0xfd8d37f7a1276878972d240302c8efe32f577220c1bbc6c8984d8b60dddfcab3',\n admin_cap_id: '0x66c70d58c69353714cc6fe2d3a62492d605a96a9821e2bd8274de17219c69980',\n config_cap_id: '0x02b8d23f033687579966e182c776fe0287cacdbb18bff56c29f141e29a18a4d1',\n },\n },\n ido: {\n package_id: '0x1192c9e20b4b0a8848a73a8c711b43e38f7ea1f307b556aab6ffab4e982e9c59',\n published_at: '0x1192c9e20b4b0a8848a73a8c711b43e38f7ea1f307b556aab6ffab4e982e9c59',\n config: {\n pools_id: '0xefc209b47acf1f23b29d166440904600229e520ad36228aaf2329b7c16be9762',\n admin_cap_id: '0x281859d366951830aeeda90779aa170d8ee6845875545470d33ecb890e78c8ce',\n package_version_id: '0xc93dc996106770af5f4e979b6808518f8cee080f22f35b936f071f59d834bb22',\n },\n },\n xcetus: {\n package_id: '0x9e69acc50ca03bc943c4f7c5304c2a6002d507b51c11913b247159c60422c606',\n published_at: '0x9e69acc50ca03bc943c4f7c5304c2a6002d507b51c11913b247159c60422c606',\n config: {\n xcetus_manager_id: '0x838b3dbade12b1e602efcaf8c8b818fae643e43176462bf14fd196afa59d1d9d',\n lock_manager_id: '0x288b59d9dedb51d0bb6cb5e13bfb30885ecf44f8c9076b6f5221c5ef6644fd28',\n lock_handle_id: '0x7c534bb7b8a2cc21538d0dbedd2437cc64f47106cb4c259b9ff921b5c3cb1a49',\n },\n },\n xcetus_dividends: {\n package_id: '0x785248249ac457dfd378bdc6d2fbbfec9d1daf65e9d728b820eb4888c8da2c10',\n published_at: '0x5aa58e1623885bd93de2331d05c29bf4930e54e56beeabcab8fe5385de2d31dc',\n config: {\n dividend_manager_id: '0x721c990bfc031d074341c6059a113a59c1febfbd2faeb62d49dcead8408fa6b5',\n dividend_admin_id: '0x682ba823134f156eac2bcfb27d85a284954a0e61998dc628c40b9bcb4a46ff30',\n dividend_settle_id: '0xade40abe9f6dd10b83b11085be18f07b63b681cf1c169b041fa16854403388c5',\n venft_dividends_id: '0x9dcdb97b4307684bedaeaf803d381b12321a31ecbb9dad7df2cd5f64384f9456',\n venft_dividends_id_v2: '0xaa21fbc1707786d56302952f8327362f4eb9a431a5bc574834e6d46125390de3',\n },\n },\n cetus_faucet: {\n package_id: '0x6864a6f921804860930db6ddbe2e16acdf8504495ea7481637a1c8b9a8fe54b',\n published_at: '0x6864a6f921804860930db6ddbe2e16acdf8504495ea7481637a1c8b9a8fe54b',\n },\n xtoken: {\n package_id: '',\n published_at: '',\n config: {\n xtoken_manager_id: '',\n lock_manager_id: '',\n lock_handle_id: '',\n },\n },\n xtoken_dividends: {\n package_id: '',\n published_at: '',\n config: {\n dividend_manager_id: '',\n dividend_admin_id: '',\n dividend_settle_id: '',\n },\n },\n token_faucet: {\n package_id: '',\n published_at: '',\n },\n booster: {\n package_id: '',\n published_at: '',\n config: {\n booster_config_id: '',\n booster_pool_handle: '',\n },\n },\n maker_bonus: {\n package_id: '',\n published_at: '',\n config: {\n maker_config_id: '',\n maker_pool_handle: '',\n },\n },\n liquidity_stratefy: {\n package_id: '',\n published_at: '',\n version: undefined,\n config: undefined,\n },\n vaults: {\n package_id: '0xd3453d9be7e35efe222f78a810bb3af1859fd1600926afced8b4936d825c9a05',\n published_at: '0xabbd278f738affe762e9df4765b3409bb1e86a355a4f611ad82b278c18108918',\n version: 1,\n config: {\n admin_cap_id: '0x78a42978709c4032fab7b33b782b5bcef64c1c6603250bf23644650b72144375',\n vaults_manager_id: '0x25b82dd2f5ee486ed1c8af144b89a8931cd9c29dee3a86a1bfe194fdea9d04a6',\n vaults_pool_handle: '0x9036bcc5aa7fd2cceec1659a6a1082871f45bc400c743f50063363457d1738bd',\n haedal: {\n package_id: '0xbde4ba4c2e274a60ce15c1cfff9e5c42e41654ac8b6d906a57efa4bd3c29f47d',\n published_at: '0x1d56b8ec33c3fae897eb7bb1acb79914e8152faed614868928e684c25c8b198d',\n version: 1,\n config: {\n staking_id: '0x47b224762220393057ebf4f70501b6e657c3e56684737568439a04f80849b2ca',\n coin_type: '0xbde4ba4c2e274a60ce15c1cfff9e5c42e41654ac8b6d906a57efa4bd3c29f47d::hasui::HASUI',\n },\n },\n volo: {\n package_id: '0x549e8b69270defbfafd4f94e17ec44cdbdd99820b33bda2278dea3b9a32d3f55',\n published_at: '0x549e8b69270defbfafd4f94e17ec44cdbdd99820b33bda2278dea3b9a32d3f55',\n version: 1,\n config: {\n native_pool: '0x7fa2faa111b8c65bea48a23049bfd81ca8f971a262d981dcd9a17c3825cb5baf',\n vsui_metadata: '0x680cd26af32b2bde8d3361e804c53ec1d1cfe24c7f039eb7f549e8dfde389a60',\n coin_type: '0x549e8b69270defbfafd4f94e17ec44cdbdd99820b33bda2278dea3b9a32d3f55::cert::CERT',\n },\n },\n aftermath: {\n package_id: '0x7f6ce7ade63857c4fd16ef7783fed2dfc4d7fb7e40615abdb653030b76aef0c6',\n published_at: '0x7f6ce7ade63857c4fd16ef7783fed2dfc4d7fb7e40615abdb653030b76aef0c6',\n version: 1,\n config: {\n staked_sui_vault: '0x2f8f6d5da7f13ea37daa397724280483ed062769813b6f31e9788e59cc88994d',\n referral_vault: '0x4ce9a19b594599536c53edb25d22532f82f18038dc8ef618afd00fbbfb9845ef',\n safe: '0xeb685899830dd5837b47007809c76d91a098d52aabbf61e8ac467c59e5cc4610',\n validator_address: '0xd30018ec3f5ff1a3c75656abf927a87d7f0529e6dc89c7ddd1bd27ecb05e3db2',\n coin_type: '0xf325ce1300e8dac124071d3152c5c5ee6174914f8bc2161e88329cf579246efc::afsui::AFSUI',\n },\n },\n },\n },\n limit_order: {\n package_id: '',\n published_at: '',\n version: 1,\n config: {\n rate_orders_indexer_id: '',\n rate_orders_indexer_handle: '',\n global_config_id: '',\n token_list_handle: '',\n user_orders_indexer_id: '',\n user_orders_indexer_handle: '',\n },\n },\n frams: {\n package_id: '0x11ea791d82b5742cc8cab0bf7946035c97d9001d7c3803a93f119753da66f526',\n published_at: '0xd817d90368dafcbf3b051e96546dea6209bffad23289d66025beef80354dcd6b',\n version: 1,\n config: {\n global_config_id: '0x21215f2f6de04b57dd87d9be7bb4e15499aec935e36078e2488f36436d64996e',\n rewarder_manager_id: '0xe0e155a88c77025056da08db5b1701a91b79edb6167462f768e387c3ed6614d5',\n rewarder_manager_handle: '0xb32e312cbb3367d6f3d2b4e57c9225e903d29b7b9f612dae2ddf75bdeb26a5aa',\n admin_cap_id: '0xf10fbf1fea5b7aeaa524b87769461a28c5c977613046360093673991f26d886c',\n },\n },\n dca: {\n package_id: '',\n published_at: '',\n version: 0,\n config: {\n admin_cap_id: '',\n global_config_id: '',\n indexer_id: '',\n user_indexer_id: '',\n in_coin_whitelist_id: '',\n out_coin_whitelist_id: '',\n },\n },\n};\n\nexport const clmmConfigTestnet: SdkOptions = {\n fullRpcUrl: 'https://fullnode.testnet.sui.io/',\n simulationAccount: {\n address: '0xcd0247d0b67e53dde69b285e7a748e3dc390e8a5244eb9dd9c5c53d95e4cf0aa',\n },\n cetus_config: {\n package_id: '0xf5ff7d5ba73b581bca6b4b9fa0049cd320360abd154b809f8700a8fd3cfaf7ca',\n published_at: '0xf5ff7d5ba73b581bca6b4b9fa0049cd320360abd154b809f8700a8fd3cfaf7ca',\n config: {\n coin_list_id: '0x257eb2ba592a5480bba0a97d05338fab17cc3283f8df6998a0e12e4ab9b84478',\n launchpad_pools_id: '0xdc3a7bd66a6dcff73c77c866e87d73826e446e9171f34e1c1b656377314f94da',\n clmm_pools_id: '0x26c85500f5dd2983bf35123918a144de24e18936d0b234ef2b49fbb2d3d6307d',\n admin_cap_id: '0x1a496f6c67668eb2c27c99e07e1d61754715c1acf86dac45020c886ac601edb8',\n global_config_id: '0xe1f3db327e75f7ec30585fa52241edf66f7e359ef550b533f89aa1528dd1be52',\n coin_list_handle: '0x3204350fc603609c91675e07b8f9ac0999b9607d83845086321fca7f469de235',\n launchpad_pools_handle: '0xae67ff87c34aceea4d28107f9c6c62e297a111e9f8e70b9abbc2f4c9f5ec20fd',\n clmm_pools_handle: '0xd28736923703342b4752f5ed8c2f2a5c0cb2336c30e1fed42b387234ce8408ec',\n },\n },\n clmm_pool: {\n package_id: '0x0868b71c0cba55bf0faf6c40df8c179c67a4d0ba0e79965b68b3d72d7dfbf666',\n published_at: '0x1c29d658882c40eeb39a8bb8fe58f71a216a918acb3e3eb3b47d24efd07257f2',\n config: {\n pools_id: '0xc090b101978bd6370def2666b7a31d7d07704f84e833e108a969eda86150e8cf',\n global_config_id: '0x6f4149091a5aea0e818e7243a13adcfb403842d670b9a2089de058512620687a',\n global_vault_id: '0xf3114a74d54cbe56b3e68f9306661c043ede8c6615f0351b0c3a93ce895e1699',\n admin_cap_id: '',\n },\n },\n integrate: {\n package_id: '0x8627c5cdcd8b63bc3daa09a6ab7ed81a829a90cafce6003ae13372d611fbb1a9',\n published_at: '0xf1a5d0c5b0593e41d13f9684ca91365bdfe54a98836c1d33c90e361a031fac74',\n version: 6,\n },\n deepbook: {\n package_id: '0x000000000000000000000000000000000000000000000000000000000000dee9',\n published_at: '0x000000000000000000000000000000000000000000000000000000000000dee9',\n },\n deepbook_endpoint_v2: {\n package_id: '0xa34ffca2c6540e1ca9e53963ab43e7b1eed7b82e37696c743bb7c6179c15dfa6',\n published_at: '0xa34ffca2c6540e1ca9e53963ab43e7b1eed7b82e37696c743bb7c6179c15dfa6',\n },\n aggregatorUrl: 'https://api-sui.devcetus.com/router',\n swapCountUrl: 'https://api-sui.devcetus.com/v2/sui/swap/count',\n};\n\nexport const peripheryConfigTestnet: PeripherySdkOptions = {\n launchpad: {\n package_id: '0x3beee8416089a5cbff9cfd5c0a2ce2937b0452dc7e2a3ab4dc431c7be05c2335',\n published_at: '0x3beee8416089a5cbff9cfd5c0a2ce2937b0452dc7e2a3ab4dc431c7be05c2335',\n config: {\n pools_id: '0xccc10403ab3da4ae943847908e0e674fe1fdab81c6383e4c6dcd0eea0edade3d',\n admin_cap_id: '0x8a72713049dbcfc40902ff209dc5e6066fe455d152baa235957c84d7a3b875ed',\n config_cap_id: '0x16492b4252b01debb60f8a825334020d7fdb9d895b52f8139c98618de30817fc',\n },\n },\n ido: {\n package_id: '0x1352bf18ef20458f7cc773852d4a90b240015a6a54479dda3a1debfc500bf044',\n published_at: '0xbd09a0889ea9970b821512428bab3e2fd01e16809a90a325cd3b3d3573eab6a4',\n config: {\n pools_id: '0x346bee25ab4d15bcfa9484ef5ebd4d7c94eb665ebaa745ff4094936a7f59a8b1',\n admin_cap_id: '0xc1bb19a24d3bb65dfd4f3835637b63347c223c67cde4b0888f1a857974f33cbb',\n package_version_id: '0x3ccf1b38e3259e638b980d4e6b49eac8c5aa94d3cb2ace5e75f0a551c8e67e5e',\n },\n },\n xcetus: {\n package_id: '0xdebaab6b851fd3414c0a62dbdf8eb752d6b0d31f5cfce5e38541bc6c6daa8966',\n published_at: '0xdebaab6b851fd3414c0a62dbdf8eb752d6b0d31f5cfce5e38541bc6c6daa8966',\n config: {\n xcetus_manager_id: '0x3be34cbad122c8b100ed7157d762b9610e68b3c65734e08bc3c3baf857da807d',\n lock_manager_id: '0x7c67e805182e3fecd098bd68a6b06c317f28f8c6249bd771e07904a10b424e60',\n lock_handle_id: '0xc5f3bbfefe9a45c13da7a34bc72cac122ee45d633690476a8ac56bd2c4e78c86',\n },\n },\n xcetus_dividends: {\n package_id: '0x20d948d640edd0c749f533d41efc5f843f212d441220324ad7959c6e1d281828',\n published_at: '0x20d948d640edd0c749f533d41efc5f843f212d441220324ad7959c6e1d281828',\n config: {\n dividend_manager_id: '0x13b7facb704fae1d199ff0038b8acabc253415a77d142b39189dee97d457e442',\n dividend_admin_id: '0x5eb78463007422d4130b21f61c180bcd190819b7792f56e00a61df3b8fb928ef',\n dividend_settle_id: '0x495095e13a170ff494d242ae44ac2c7453011ca6c33cff27498010105e10e4b4',\n venft_dividends_id: '',\n venft_dividends_id_v2: '',\n },\n },\n cetus_faucet: {\n package_id: '0x1a69aee6be709054750949959a67aedbb4200583b39586d5e3eabe57f40012c7',\n published_at: '0x1a69aee6be709054750949959a67aedbb4200583b39586d5e3eabe57f40012c7',\n },\n xtoken: {\n package_id: '',\n published_at: '',\n config: {\n xtoken_manager_id: '',\n lock_manager_id: '',\n lock_handle_id: '',\n },\n },\n xtoken_dividends: {\n package_id: '',\n published_at: '',\n config: {\n dividend_manager_id: '',\n dividend_admin_id: '',\n dividend_settle_id: '',\n },\n },\n token_faucet: {\n package_id: '',\n published_at: '',\n },\n booster: {\n package_id: '',\n published_at: '',\n config: {\n booster_config_id: '',\n booster_pool_handle: '',\n },\n },\n maker_bonus: {\n package_id: '',\n published_at: '',\n config: {\n maker_config_id: '',\n maker_pool_handle: '',\n },\n },\n liquidity_stratefy: {\n package_id: '',\n published_at: '',\n version: undefined,\n config: undefined,\n },\n vaults: {\n package_id: '0x25cff94bdb454bae6a5565d09047bfe2b230025ef3bd2199622ec48d854b86b9',\n published_at: '0x25cff94bdb454bae6a5565d09047bfe2b230025ef3bd2199622ec48d854b86b9',\n config: {\n admin_cap_id: '0x9b2d6f5be2650d16d27cd630c4539a76d7793970343ed3cbb023e13f1637c07c',\n vaults_manager_id: '0xc0a1a937df08880e395d85014ff40c74f13abe7a53abdbffea36f51adaaaf79e',\n vaults_pool_handle: '0x3ab02203de753de9c8198cc0ce7594dc960878f2c34c5c5a4b7742082241860a',\n },\n },\n limit_order: {\n package_id: '',\n published_at: '',\n version: 1,\n config: {\n rate_orders_indexer_id: '',\n rate_orders_indexer_handle: '',\n global_config_id: '',\n token_list_handle: '',\n user_orders_indexer_id: '',\n user_orders_indexer_handle: '',\n },\n },\n frams: {\n package_id: '0xfa0d98e99c1dbdbea1b0fe089fa93ebab40a7719ae4160c42cc78ebfe029fda0',\n published_at: '0xfa0d98e99c1dbdbea1b0fe089fa93ebab40a7719ae4160c42cc78ebfe029fda0',\n config: {\n global_config_id: '0x5082c7a5ee9a758025d7b0a5e8aa08b56625c7cd535b8909d2b7993991e229cc',\n rewarder_manager_id: '0xe789e092dbd9dceadbe89350c4761a6f2e11647aab97f09746a01b151926cc0e',\n rewarder_manager_handle: '0x7e7dd42392b5d82564dc9ad5093a111c5f0598cc9f806cff257d7dacb71f7837',\n admin_cap_id: '0x4ec248bca2d1fc05f39fd7491ab490464a46d128624caa4d3c2a66d957ef40b0',\n },\n },\n dca: {\n package_id: '',\n published_at: '',\n version: 0,\n config: {\n admin_cap_id: '',\n global_config_id: '',\n indexer_id: '',\n user_indexer_id: '',\n in_coin_whitelist_id: '',\n out_coin_whitelist_id: '',\n },\n },\n};\n\nexport const getClmmSdk = (network: SuiNetworks, account: WalletAccount) => {\n const config = network === 'sui:mainnet' ? clmmConfig : clmmConfigTestnet;\n const clmmSdk = new CetusClmmSDK(config);\n clmmSdk.senderAddress = account.address;\n return clmmSdk;\n};\n\nexport const getPeripherySdk = (network: SuiNetworks, account: WalletAccount) => {\n const clmmSdk = getClmmSdk(network, account);\n const config = network === 'sui:mainnet' ? peripheryConfig : peripheryConfigTestnet;\n const peripherySdk = new CetusPeripherySDK(config, clmmSdk);\n return peripherySdk;\n};\n\nconst aggregatorURL = 'https://api-sui.cetus.zone/router_v2/find_routes';\nexport const getAggregatorSdk = (network: SuiNetworks, account: WalletAccount) => {\n const suiClient = new SuiClient({\n url: 'https://fullnode.mainnet.sui.io/',\n });\n const aggregatorSdk = new AggregatorClient(aggregatorURL, account.address, suiClient, Env.Mainnet);\n return aggregatorSdk;\n};\n","import { Transaction } from '@mysten/sui/transactions';\nimport { WalletAccount } from '@mysten/wallet-standard';\n\nimport { SuiNetworks } from '@/types';\n\nimport { getClmmSdk } from './config';\n\nexport const getAddLiquidityTxb = async (\n txbParams: any,\n account: WalletAccount,\n network: SuiNetworks,\n): Promise<Transaction> => {\n const clmmSdk = getClmmSdk(network, account);\n const txb: Transaction = await clmmSdk.Position.createAddLiquidityFixTokenPayload(\n txbParams?.parameter,\n txbParams?.gasEstimateArg,\n );\n return txb;\n};\n\nexport const getIncreaseLiquidityTxb = async (\n txbParams: any,\n account: WalletAccount,\n network: SuiNetworks,\n): Promise<Transaction> => {\n const clmmSdk = getClmmSdk(network, account);\n const txb: Transaction = await clmmSdk.Position.createAddLiquidityFixTokenPayload(\n txbParams?.parameter,\n txbParams?.gasEstimateArg,\n );\n return txb;\n};\n\nexport const getRemoveLiquidityTxb = async (\n txbParams: any,\n account: WalletAccount,\n network: SuiNetworks,\n): Promise<Transaction> => {\n const clmmSdk = getClmmSdk(network, account);\n const txb: Transaction = await clmmSdk.Position.closePositionTransactionPayload(txbParams);\n return txb;\n};\n\nexport const getDecreaseLiquidityTxb = async (\n txbParams: any,\n account: WalletAccount,\n network: SuiNetworks,\n): Promise<Transaction> => {\n const clmmSdk = getClmmSdk(network, account);\n const txb: Transaction = await clmmSdk.Position.removeLiquidityTransactionPayload(txbParams);\n return txb;\n};\n\nexport const getClaimFeeAndMiningTxb = async (\n txbParams: any,\n account: WalletAccount,\n network: SuiNetworks,\n): Promise<Transaction> => {\n const clmmSdk = getClmmSdk(network, account);\n const txb: Transaction = await clmmSdk.Rewarder.collectRewarderTransactionPayload(txbParams);\n return txb;\n};\n","import { TransactionType } from '@msafe/sui3-utils';\nimport { SuiClient } from '@mysten/sui/client';\nimport { Transaction } from '@mysten/sui/transactions';\nimport { WalletAccount } from '@mysten/wallet-standard';\n\nimport { BaseIntention } from '@/apps/interface/sui';\nimport { SuiNetworks } from '@/types';\n\nimport { getClaimFeeAndMiningTxb } from '../api/position';\nimport { CetusIntentionData, TransactionSubType } from '../types';\n\nexport class ClaimFeeAndMiningIntention extends BaseIntention<CetusIntentionData> {\n txType = TransactionType.Other;\n\n txSubType = TransactionSubType.ClaimFeeAndMining;\n\n constructor(public readonly data: CetusIntentionData) {\n super(data);\n }\n\n async build(input: { suiClient: SuiClient; account: WalletAccount; network: SuiNetworks }): Promise<Transaction> {\n const { account, network } = input;\n const { txbParams } = this.data;\n const txb = await getClaimFeeAndMiningTxb(txbParams, account, network);\n return txb;\n }\n\n static fromData(data: CetusIntentionData) {\n return new ClaimFeeAndMiningIntention(data);\n }\n}\n","import { TransactionType } from '@msafe/sui3-utils';\nimport { SuiClient } from '@mysten/sui/client';\nimport { Transaction } from '@mysten/sui/transactions';\nimport { WalletAccount } from '@mysten/wallet-standard';\n\nimport { BaseIntention } from '@/apps/interface/sui';\nimport { SuiNetworks } from '@/types';\n\nimport { getDecreaseLiquidityTxb } from '../api/position';\nimport { CetusIntentionData, TransactionSubType } from '../types';\n\nexport class DecreaseLiquidityIntention extends BaseIntention<CetusIntentionData> {\n txType = TransactionType.Other;\n\n txSubType = TransactionSubType.DecreaseLiquidity;\n\n constructor(public readonly data: CetusIntentionData) {\n super(data);\n }\n\n async build(input: { suiClient: SuiClient; account: WalletAccount; network: SuiNetworks }): Promise<Transaction> {\n const { account, network } = input;\n const { txbParams } = this.data;\n const txb = await getDecreaseLiquidityTxb(txbParams, account, network);\n return txb;\n }\n\n static fromData(data: CetusIntentionData) {\n return new DecreaseLiquidityIntention(data);\n }\n}\n","import { TransactionType } from '@msafe/sui3-utils';\nimport { SuiClient } from '@mysten/sui/client';\nimport { Transaction } from '@mysten/sui/transactions';\nimport { WalletAccount } from '@mysten/wallet-standard';\n\nimport { BaseIntention } from '@/apps/interface/sui';\nimport { SuiNetworks } from '@/types';\n\nimport { getFarmingAddLiquidityTxb } from '../api/farming';\nimport { CetusIntentionData, TransactionSubType } from '../types';\n\nexport class FarmingAddLiquidityIntention extends BaseIntention<CetusIntentionData> {\n txType = TransactionType.Other;\n\n txSubType = TransactionSubType.FarmingOpenAndAddLiquidity;\n\n constructor(public readonly data: CetusIntentionData) {\n super(data);\n }\n\n async build(input: { suiClient: SuiClient; account: WalletAccount; network: SuiNetworks }): Promise<Transaction> {\n const { account, network } = input;\n const { txbParams } = this.data;\n const txb = await getFarmingAddLiquidityTxb(txbParams, account, network);\n return txb;\n }\n\n static fromData(data: CetusIntentionData) {\n return new FarmingAddLiquidityIntention(data);\n }\n}\n","import { Transaction } from '@mysten/sui/transactions';\nimport { WalletAccount } from '@mysten/wallet-standard';\n\nimport { SuiNetworks } from '@/types';\n\nimport { getPeripherySdk } from './config';\n\nexport const getFarmingAddLiquidityTxb = async (\n txbParams: any,\n account: WalletAccount,\n network: SuiNetworks,\n): Promise<Transaction> => {\n const peripherySdk = getPeripherySdk(network, account);\n const txb: Transaction = await peripherySdk.Farms.openPositionAddLiquidityStakePaylod(txbParams);\n return txb;\n};\n\nexport const getFarmingIncreaseLiquidityTxb = async (\n txbParams: any,\n account: WalletAccount,\n network: SuiNetworks,\n): Promise<Transaction> => {\n const peripherySdk = getPeripherySdk(network, account);\n const txb: Transaction = await peripherySdk.Farms.addLiquidityFixCoinPayload(txbParams);\n return txb;\n};\n\nexport const getFarmingDecreaseLiquidityTxb = async (\n txbParams: any,\n account: WalletAccount,\n network: SuiNetworks,\n): Promise<Transaction> => {\n const peripherySdk = getPeripherySdk(network, account);\n const txb: Transaction = await peripherySdk.Farms.removeLiquidityPayload(txbParams);\n return txb;\n};\n\nexport const getFarmingRemoveLiquidityTxb = async (\n txbParams: any,\n account: WalletAccount,\n network: SuiNetworks,\n): Promise<Transaction> => {\n const peripherySdk = getPeripherySdk(network, account);\n const txb: Transaction = await peripherySdk.Farms.removeLiquidityPayload(txbParams);\n return txb;\n};\n\nexport const getFarmingClaimFeeAndRewardTxb = async (\n txbParams: any,\n account: WalletAccount,\n network: SuiNetworks,\n): Promise<Transaction> => {\n const peripherySdk = getPeripherySdk(network, account);\n const txb: Transaction = await peripherySdk.Farms.claimFeeAndClmmReward(txbParams);\n return txb;\n};\n\nexport const getFarmingHarvest = async (\n txbParams: any,\n account: WalletAccount,\n network: SuiNetworks,\n): Promise<Transaction> => {\n const peripherySdk = getPeripherySdk(network, account);\n const txb: Transaction = await peripherySdk.Farms.harvestPayload(txbParams);\n return txb;\n};\n\nexport const getFarmingBatchHarvest = async (\n txbParams: any,\n account: WalletAccount,\n network: SuiNetworks,\n): Promise<Transaction> => {\n const peripherySdk = getPeripherySdk(network, account);\n const params: any = Object.values(txbParams);\n const txb: Transaction = await peripherySdk.Farms.batchHarvestPayload(params);\n return txb;\n};\n\nexport const getFarmingStake = async (\n txbParams: any,\n account: WalletAccount,\n network: SuiNetworks,\n): Promise<Transaction> => {\n const peripherySdk = getPeripherySdk(network, account);\n const txb: Transaction = await peripherySdk.Farms.depositPayload(txbParams);\n return txb;\n};\n\nexport const getFarmingUnstake = async (\n txbParams: any,\n account: WalletAccount,\n network: SuiNetworks,\n): Promise<Transaction> => {\n const peripherySdk = getPeripherySdk(network, account);\n const txb: Transaction = await peripherySdk.Farms.withdrawPayload(txbParams);\n return txb;\n};\n","import { TransactionType } from '@msafe/sui3-utils';\nimport { SuiClient } from '@mysten/sui/client';\nimport { Transaction } from '@mysten/sui/transactions';\nimport { WalletAccount } from '@mysten/wallet-standard';\n\nimport { BaseIntention } from '@/apps/interface/sui';\nimport { SuiNetworks } from '@/types';\n\nimport { getFarmingBatchHarvest } from '../api/farming';\nimport { CetusIntentionData, TransactionSubType } from '../types';\n\nexport class FarmingBatchHarvestIntention extends BaseIntention<CetusIntentionData> {\n txType = TransactionType.Other;\n\n txSubType = TransactionSubType.FarmingBatchHarvest;\n\n constructor(public readonly data: CetusIntentionData) {\n super(data);\n }\n\n async build(input: { suiClient: SuiClient; account: WalletAccount; network: SuiNetworks }): Promise<Transaction> {\n const { account, network } = input;\n const { txbParams } = this.data;\n const txb = await getFarmingBatchHarvest(txbParams, account, network);\n return txb;\n }\n\n static fromData(data: CetusIntentionData) {\n return new FarmingBatchHarvestIntention(data);\n }\n}\n","import { TransactionType } from '@msafe/sui3-utils';\nimport { SuiClient } from '@mysten/sui/client';\nimport { Transaction } from '@mysten/sui/transactions';\nimport { WalletAccount } from '@mysten/wallet-standard';\n\nimport { BaseIntention } from '@/apps/interface/sui';\nimport { SuiNetworks } from '@/types';\n\nimport { getFarmingClaimFeeAndRewardTxb } from '../api/farming';\nimport { CetusIntentionData, TransactionSubType } from '../types';\n\nexport class FarmingClaimFeeAndRewardIntention extends BaseIntention<CetusIntentionData> {\n txType = TransactionType.Other;\n\n txSubType = TransactionSubType.FarmingClaimFeeAndReward;\n\n constructor(public readonly data: CetusIntentionData) {\n super(data);\n }\n\n async build(input: { suiClient: SuiClient; account: WalletAccount; network: SuiNetworks }): Promise<Transaction> {\n const { account, network } = input;\n const { txbParams } = this.data;\n const txb = await getFarmingClaimFeeAndRewardTxb(txbParams, account, network);\n return txb;\n }\n\n static fromData(data: CetusIntentionData) {\n return new FarmingClaimFeeAndRewardIntention(data);\n }\n}\n","import { TransactionType } from '@msafe/sui3-utils';\nimport { SuiClient } from '@mysten/sui/client';\nimport { Transaction } from '@mysten/sui/transactions';\nimport { WalletAccount } from '@mysten/wallet-standard';\n\nimport { BaseIntention } from '@/apps/interface/sui';\nimport { SuiNetworks } from '@/types';\n\nimport { getFarmingDecreaseLiquidityTxb } from '../api/farming';\nimport { CetusIntentionData, TransactionSubType } from '../types';\n\nexport class FarmingDecreaseLiquidityIntention extends BaseIntention<CetusIntentionData> {\n txType = TransactionType.Other;\n\n txSubType = TransactionSubType.FarmingDecreaseLiquidity;\n\n constructor(public readonly data: CetusIntentionData) {\n super(data);\n }\n\n async build(input: { suiClient: SuiClient; account: WalletAccount; network: SuiNetworks }): Promise<Transaction> {\n const { account, network } = input;\n const { txbParams } = this.data;\n const txb = await getFarmingDecreaseLiquidityTxb(txbParams, account, network);\n return txb;\n }\n\n static fromData(data: CetusIntentionData) {\n return new FarmingDecreaseLiquidityIntention(data);\n }\n}\n","import { TransactionType } from '@msafe/sui3-utils';\nimport { SuiClient } from '@mysten/sui/client';\nimport { Transaction } from '@mysten/sui/transactions';\nimport { WalletAccount } from '@mysten/wallet-standard';\n\nimport { BaseIntention } from '@/apps/interface/sui';\nimport { SuiNetworks } from '@/types';\n\nimport { getFarmingHarvest } from '../api/farming';\nimport { CetusIntentionData, TransactionSubType } from '../types';\n\nexport class FarmingHarvestIntention extends BaseIntention<CetusIntentionData> {\n txType = TransactionType.Other;\n\n txSubType = TransactionSubType.FarmingHarvest;\n\n constructor(public readonly data: CetusIntentionData) {\n super(data);\n }\n\n async build(input: { suiClient: SuiClient; account: WalletAccount; network: SuiNetworks }): Promise<Transaction> {\n const { account, network } = input;\n const { txbParams } = this.data;\n const txb = await getFarmingHarvest(txbParams, account, network);\n return txb;\n }\n\n static fromData(data: CetusIntentionData) {\n return new FarmingHarvestIntention(data);\n }\n}\n","import { TransactionType } from '@msafe/sui3-utils';\nimport { SuiClient } from '@mysten/sui/client';\nimport { Transaction } from '@mysten/sui/transactions';\nimport { WalletAccount } from '@mysten/wallet-standard';\n\nimport { BaseIntention } from '@/apps/interface/sui';\nimport { SuiNetworks } from '@/types';\n\nimport { getFarmingIncreaseLiquidityTxb } from '../api/farming';\nimport { CetusIntentionData, TransactionSubType } from '../types';\n\nexport class FarmingIncreaseLiquidityIntention extends BaseIntention<CetusIntentionData> {\n txType = TransactionType.Other;\n\n txSubType = TransactionSubType.FarmingIncreaseLiquidity;\n\n constructor(public readonly data: CetusIntentionData) {\n super(data);\n }\n\n async build(input: { suiClient: SuiClient; account: WalletAccount; network: SuiNetworks }): Promise<Transaction> {\n const { account, network } = input;\n const { txbParams } = this.data;\n const txb = await getFarmingIncreaseLiquidityTxb(txbParams, account, network);\n return txb;\n }\n\n static fromData(data: CetusIntentionData) {\n return new FarmingIncreaseLiquidityIntention(data);\n }\n}\n","import { TransactionType } from '@msafe/sui3-utils';\nimport { SuiClient } from '@mysten/sui/client';\nimport { Transaction } from '@mysten/sui/transactions';\nimport { WalletAccount } from '@mysten/wallet-standard';\n\nimport { BaseIntention } from '@/apps/interface/sui';\nimport { SuiNetworks } from '@/types';\n\nimport { getFarmingRemoveLiquidityTxb } from '../api/farming';\nimport { CetusIntentionData, TransactionSubType } from '../types';\n\nexport class FarmingRemoveLiquidityIntention extends BaseIntention<CetusIntentionData> {\n txType = TransactionType.Other;\n\n txSubType = TransactionSubType.FarmingRemoveLiquidity;\n\n constructor(public readonly data: CetusIntentionData) {\n super(data);\n }\n\n async build(input: { suiClient: SuiClient; account: WalletAccount; network: SuiNetworks }): Promise<Transaction> {\n const { account, network } = input;\n const { txbParams } = this.data;\n const txb = await getFarmingRemoveLiquidityTxb(txbParams, account, network);\n return txb;\n }\n\n static fromData(data: CetusIntentionData) {\n return new FarmingRemoveLiquidityIntention(data);\n }\n}\n","import { TransactionType } from '@msafe/sui3-utils';\nimport { SuiClient } from '@mysten/sui/client';\nimport { Transaction } from '@mysten/sui/transactions';\nimport { WalletAccount } from '@mysten/wallet-standard';\n\nimport { BaseIntention } from '@/apps/interface/sui';\nimport { SuiNetworks } from '@/types';\n\nimport { getFarmingStake } from '../api/farming';\nimport { CetusIntentionData, TransactionSubType } from '../types';\n\nexport class FarmingStakeIntention extends BaseIntention<CetusIntentionData> {\n txType = TransactionType.Other;\n\n txSubType = TransactionSubType.FarmingStake;\n\n constructor(public readonly data: CetusIntentionData) {\n super(data);\n }\n\n async build(input: { suiClient: SuiClient; account: WalletAccount; network: SuiNetworks }): Promise<Transaction> {\n const { account, network } = input;\n const { txbParams } = this.data;\n const txb = await getFarmingStake(txbParams, account, network);\n return txb;\n }\n\n static fromData(data: CetusIntentionData) {\n return new FarmingStakeIntention(data);\n }\n}\n","import { TransactionType } from '@msafe/sui3-utils';\nimport { SuiClient } from '@mysten/sui/client';\nimport { Transaction } from '@mysten/sui/transactions';\nimport { WalletAccount } from '@mysten/wallet-standard';\n\nimport { BaseIntention } from '@/apps/interface/sui';\nimport { SuiNetworks } from '@/types';\n\nimport { getFarmingUnstake } from '../api/farming';\nimport { CetusIntentionData, TransactionSubType } from '../types';\n\nexport class FarmingUnstakeIntention extends BaseIntention<CetusIntentionData> {\n txType = TransactionType.Other;\n\n txSubType = TransactionSubType.FarmingUnstake;\n\n constructor(public readonly data: CetusIntentionData) {\n super(data);\n }\n\n async build(input: { suiClient: SuiClient; account: WalletAccount; network: SuiNetworks }): Promise<Transaction> {\n const { account, network } = input;\n const { txbParams } = this.data;\n const txb = await getFarmingUnstake(txbParams, account, network);\n return txb;\n }\n\n static fromData(data: CetusIntentionData) {\n return new FarmingUnstakeIntention(data);\n }\n}\n","import { TransactionType } from '@msafe/sui3-utils';\nimport { SuiClient } from '@mysten/sui/client';\nimport { Transaction } from '@mysten/sui/transactions';\nimport { WalletAccount } from '@mysten/wallet-standard';\n\nimport { BaseIntention } from '@/apps/interface/sui';\nimport { SuiNetworks } from '@/types';\n\nimport { getIncreaseLiquidityTxb } from '../api/position';\nimport { CetusIntentionData, TransactionSubType } from '../types';\n\nexport class IncreaseLiquidityIntention extends BaseIntention<CetusIntentionData> {\n txType = TransactionType.Other;\n\n txSubType = TransactionSubType.IncreaseLiquidity;\n\n constructor(public readonly data: CetusIntentionData) {\n super(data);\n }\n\n async build(input: { suiClient: SuiClient; account: WalletAccount; network: SuiNetworks }): Promise<Transaction> {\n const { account, network } = input;\n const { txbParams } = this.data;\n const txb = await getIncreaseLiquidityTxb(txbParams, account, network);\n return txb;\n }\n\n static fromData(data: CetusIntentionData) {\n return new IncreaseLiquidityIntention(data);\n }\n}\n","import { TransactionType } from '@msafe/sui3-utils';\nimport { SuiClient } from '@mysten/sui/client';\nimport { Transaction } from '@mysten/sui/transactions';\nimport { WalletAccount } from '@mysten/wallet-standard';\n\nimport { BaseIntention } from '@/apps/interface/sui';\nimport { SuiNetworks } from '@/types';\n\nimport { getRemoveLiquidityTxb } from '../api/position';\nimport { CetusIntentionData, TransactionSubType } from '../types';\n\nexport class RemoveLiquidityIntention extends BaseIntention<CetusIntentionData> {\n txType = TransactionType.Other;\n\n txSubType = TransactionSubType.RemoveLiquidity;\n\n constructor(public readonly data: CetusIntentionData) {\n super(data);\n }\n\n async build(input: { suiClient: SuiClient; account: WalletAccount; network: SuiNetworks }): Promise<Transaction> {\n const { account, network } = input;\n const { txbParams } = this.data;\n const txb = await getRemoveLiquidityTxb(txbParams, account, network);\n return txb;\n }\n\n static fromData(data: CetusIntentionData) {\n return new RemoveLiquidityIntention(data);\n }\n}\n","import { TransactionType } from '@msafe/sui3-utils';\nimport { SuiClient } from '@mysten/sui/client';\nimport { Transaction } from '@mysten/sui/transactions';\nimport { WalletAccount } from '@mysten/wallet-standard';\n\nimport { BaseIntention } from '@/apps/interface/sui';\nimport { SuiNetworks } from '@/types';\n\nimport { getSwapRouterTxb } from '../api/swap';\nimport { CetusIntentionData, TransactionSubType } from '../types';\n\nexport class SwapIntention extends BaseIntention<CetusIntentionData> {\n txType = TransactionType.Other;\n\n txSubType = TransactionSubType.Swap;\n\n constructor(public readonly data: CetusIntentionData) {\n super(data);\n }\n\n async build(input: { suiClient: SuiClient; account: WalletAccount; network: SuiNetworks }): Promise<Transaction> {\n const { account, network } = input;\n const { txbParams } = this.data;\n const txb = await getSwapRouterTxb(txbParams, account, network);\n return txb;\n }\n\n static fromData(data: CetusIntentionData) {\n return new SwapIntention(data);\n }\n}\n","import { restituteMsafeFastRouterSwapParams } from '@cetusprotocol/aggregator-sdk';\nimport { Transaction } from '@mysten/sui/transactions';\nimport { WalletAccount } from '@mysten/wallet-standard';\n\nimport { SuiNetworks } from '@/types';\n\nimport { getAggregatorSdk } from './config';\n\nexport const getSwapRouterTxb = async (\n txbParams: any,\n account: WalletAccount,\n network: SuiNetworks,\n): Promise<Transaction> => {\n const aggregatorSdk = getAggregatorSdk(network, account);\n const txb = new Transaction();\n await aggregatorSdk.fastRouterSwap({\n ...txbParams,\n routers: restituteMsafeFastRouterSwapParams(txbParams.routers),\n txb,\n });\n return txb;\n};\n","import { TransactionType } from '@msafe/sui3-utils';\nimport { SuiClient } from '@mysten/sui/client';\nimport { Transaction } from '@mysten/sui/transactions';\nimport { WalletAccount } from '@mysten/wallet-standard';\n\nimport { BaseIntention } from '@/apps/interface/sui';\nimport { SuiNetworks } from '@/types';\n\nimport { getVestingRedeemTxb } from '../api/vesting';\nimport { CetusIntentionData, TransactionSubType } from '../types';\n\nexport class VestingRedeemIntention extends BaseIntention<CetusIntentionData> {\n txType = TransactionType.Other;\n\n txSubType = TransactionSubType.VestingRedeem;\n\n constructor(public readonly data: CetusIntentionData) {\n super(data);\n }\n\n async build(input: { suiClient: SuiClient; account: WalletAccount; network: SuiNetworks }): Promise<Transaction> {\n const { account, network } = input;\n const { txbParams } = this.data;\n const txb = await getVestingRedeemTxb(txbParams, account, network);\n return txb;\n }\n\n static fromData(data: CetusIntentionData) {\n return new VestingRedeemIntention(data);\n }\n}\n","import { Transaction } from '@mysten/sui/transactions';\nimport { WalletAccount } from '@mysten/wallet-standard';\n\nimport { SuiNetworks } from '@/types';\n\nconst VestingConfing = {\n package_id: '0x355714a1eeb7ab1d80902da6c92001170cda1212edf524c32aa308a3ac177c31',\n published_at: '0x355714a1eeb7ab1d80902da6c92001170cda1212edf524c32aa308a3ac177c31',\n cetus_coin_type: '0x06864a6f921804860930db6ddbe2e16acdf8504495ea7481637a1c8b9a8fe54b::cetus::CETUS',\n};\n\nexport const getVestingRedeemTxb = async (\n txbParams: any,\n account: WalletAccount,\n network: SuiNetworks,\n): Promise<Transaction> => {\n console.log('getVestingRedeemTxb txbParams: ', txbParams);\n console.log('getVestingRedeemTxb account: ', account);\n console.log('getVestingRedeemTxb network: ', network);\n const { pool, nftId, periods, CLOCK_ADDRESS } = txbParams;\n const txb = new Transaction();\n\n periods.forEach((period: any) => {\n txb.moveCall({\n target: `${VestingConfing.published_at}::router::redeem`,\n typeArguments: [VestingConfing.cetus_coin_type],\n arguments: [txb.object(pool), txb.object(nftId), txb.pure(period), txb.object(CLOCK_ADDRESS)],\n });\n });\n\n return txb;\n};\n","import { TransactionType } from '@msafe/sui3-utils';\nimport { SuiClient } from '@mysten/sui/client';\nimport { Transaction } from '@mysten/sui/transactions';\nimport { WalletAccount } from '@mysten/wallet-standard';\n\nimport { BaseIntention } from '@/apps/interface/sui';\nimport { SuiNetworks } from '@/types';\n\nimport { getXcetusCancelRedeemTxb } from '../api/xcetus';\nimport { CetusIntentionData, TransactionSubType } from '../types';\n\nexport class XcetusCancelIntention extends BaseIntention<CetusIntentionData> {\n txType = TransactionType.Other;\n\n txSubType = TransactionSubType.xCETUSCancelRedeem;\n\n constructor(public readonly data: CetusIntentionData) {\n super(data);\n }\n\n async build(input: { suiClient: SuiClient; account: WalletAccount; network: SuiNetworks }): Promise<Transaction> {\n const { account, network } = input;\n const { txbParams } = this.data;\n const txb = await getXcetusCancelRedeemTxb(txbParams, account, network);\n return txb;\n }\n\n static fromData(data: CetusIntentionData) {\n return new XcetusCancelIntention(data);\n }\n}\n","// eslint-disable-next-line import/no-extraneous-dependencies\nimport { Transaction } from '@mysten/sui/transactions';\nimport { WalletAccount } from '@mysten/wallet-standard';\n\nimport { SuiNetworks } from '@/types';\n\nimport { getPeripherySdk } from './config';\n\nexport const getXcetusConvertTxb = async (\n txbParams: any,\n account: WalletAccount,\n network: SuiNetworks,\n): Promise<Transaction> => {\n const peripherySdk = getPeripherySdk(network, account);\n const tx = new Transaction();\n const txb: Transaction = await peripherySdk.XCetusModule.convertPayload(txbParams, tx);\n return txb;\n};\n\nexport const getXcetusRedeemLockTxb = async (\n txbParams: any,\n account: WalletAccount,\n network: SuiNetworks,\n): Promise<Transaction> => {\n const peripherySdk = getPeripherySdk(network, account);\n const txb: Transaction = await peripherySdk.XCetusModule.redeemLockPayload(txbParams);\n return txb;\n};\n\nexport const getXcetusClaimingStakeRewardsTxb = async (\n txbParams: any,\n account: WalletAccount,\n network: SuiNetworks,\n): Promise<Transaction> => {\n const peripherySdk = getPeripherySdk(network, account);\n const txb: Transaction = await peripherySdk.XCetusModule.redeemDividendV3Payload(\n txbParams.phases,\n txbParams.venft_id,\n txbParams.bonus_types,\n txbParams.bonus_types_v2,\n txbParams.xTokenType,\n );\n return txb;\n};\n\nexport const getXcetusCancelRedeemTxb = async (\n txbParams: any,\n account: WalletAccount,\n network: SuiNetworks,\n): Promise<Transaction> => {\n const peripherySdk = getPeripherySdk(network, account);\n const txb: Transaction = await peripherySdk.XCetusModule.cancelRedeemPayload(txbParams);\n return txb;\n};\n\nexport const getXcetusRedeemTxb = async (\n txbParams: any,\n account: WalletAccount,\n network: SuiNetworks,\n): Promise<Transaction> => {\n const peripherySdk = getPeripherySdk(network, account);\n const txb: Transaction = await peripherySdk.XCetusModule.redeemPayload(txbParams);\n return txb;\n};\n","import { TransactionType } from '@msafe/sui3-utils';\nimport { SuiClient } from '@mysten/sui/client';\nimport { Transaction } from '@mysten/sui/transactions';\nimport { WalletAccount } from '@mysten/wallet-standard';\n\nimport { BaseIntention } from '@/apps/interface/sui';\nimport { SuiNetworks } from '@/types';\n\nimport { getXcetusClaimingStakeRewardsTxb } from '../api/xcetus';\nimport { CetusIntentionData, TransactionSubType } from '../types';\n\nexport class XcetusClaimingStakeRewardsIntention extends BaseIntention<CetusIntentionData> {\n txType = TransactionType.Other;\n\n txSubType = TransactionSubType.xCETUSClaimStakingRwewards;\n\n constructor(public readonly data: CetusIntentionData) {\n super(data);\n }\n\n async build(input: { suiClient: SuiClient; account: WalletAccount; network: SuiNetworks }): Promise<Transaction> {\n const { account, network } = input;\n const { txbParams } = this.data;\n const txb = await getXcetusClaimingStakeRewardsTxb(txbParams, account, network);\n return txb;\n }\n\n static fromData(data: CetusIntentionData) {\n return new XcetusClaimingStakeRewardsIntention(data);\n }\n}\n","import { TransactionType } from '@msafe/sui3-utils';\nimport { SuiClient } from '@mysten/sui/client';\nimport { Transaction } from '@mysten/sui/transactions';\nimport { WalletAccount } from '@mysten/wallet-standard';\n\nimport { BaseIntention } from '@/apps/interface/sui';\nimport { SuiNetworks } from '@/types';\n\nimport { getXcetusConvertTxb } from '../api/xcetus';\nimport { CetusIntentionData, TransactionSubType } from '../types';\n\nexport class XcetusConvertIntention extends BaseIntention<CetusIntentionData> {\n txType = TransactionType.Other;\n\n txSubType = TransactionSubType.xCETUSConvert;\n\n constructor(public readonly data: CetusIntentionData) {\n super(data);\n }\n\n async build(input: { suiClient: SuiClient; account: WalletAccount; network: SuiNetworks }): Promise<Transaction> {\n const { account, network } = input;\n const { txbParams } = this.data;\n const txb = await getXcetusConvertTxb(txbParams, account, network);\n return txb;\n }\n\n static fromData(data: CetusIntentionData) {\n return new XcetusConvertIntention(data);\n }\n}\n","import { TransactionType } from '@msafe/sui3-utils';\nimport { SuiClient } from '@mysten/sui/client';\nimport { Transaction } from '@mysten/sui/transactions';\nimport { WalletAccount } from '@mysten/wallet-standard';\n\nimport { BaseIntention } from '@/apps/interface/sui';\nimport { SuiNetworks } from '@/types';\n\nimport { getXcetusRedeemTxb } from '../api/xcetus';\nimport { CetusIntentionData, TransactionSubType } from '../types';\n\nexport class XcetusRedeemIntention extends BaseIntention<CetusIntentionData> {\n txType = TransactionType.Other;\n\n txSubType = TransactionSubType.xCETUSRedeem;\n\n constructor(public readonly data: CetusIntentionData) {\n super(data);\n }\n\n async build(input: { suiClient: SuiClient; account: WalletAccount; network: SuiNetworks }): Promise<Transaction> {\n const { account, network } = input;\n const { txbParams } = this.data;\n const txb = await getXcetusRedeemTxb(txbParams, account, network);\n return txb;\n }\n\n static fromData(data: CetusIntentionData) {\n return new XcetusRedeemIntention(data);\n }\n}\n","import { TransactionType } from '@msafe/sui3-utils';\nimport { SuiClient } from '@mysten/sui/client';\nimport { Transaction } from '@mysten/sui/transactions';\nimport { WalletAccount } from '@mysten/wallet-standard';\n\nimport { BaseIntention } from '@/apps/interface/sui';\nimport { SuiNetworks } from '@/types';\n\nimport { getXcetusRedeemLockTxb } from '../api/xcetus';\nimport { CetusIntentionData, TransactionSubType } from '../types';\n\nexport class XcetusRedeemLockIntention extends BaseIntention<CetusIntentionData> {\n txType = TransactionType.Other;\n\n txSubType = TransactionSubType.xCETUSRedeemLock;\n\n constructor(public readonly data: CetusIntentionData) {\n super(data);\n }\n\n async build(input: { suiClient: SuiClient; account: WalletAccount; network: SuiNetworks }): Promise<Transaction> {\n const { account, network } = input;\n const { txbParams } = this.data;\n const txb = await getXcetusRedeemLockTxb(txbParams, account, network);\n return txb;\n }\n\n static fromData(data: CetusIntentionData) {\n return new XcetusRedeemLockIntention(data);\n }\n}\n","import { CancelStreamIntentionData, TransactionType } from '@msafe/sui3-utils';\nimport { SuiClient } from '@mysten/sui.js/client';\nimport { TransactionBlock } from '@mysten/sui.js/transactions';\nimport { WalletAccount } from '@mysten/wallet-standard';\n\nimport { SuiNetworks } from '@/types';\n\nimport { StreamIntention } from './intention';\nimport { StreamTransactionType } from './types/decode';\n\nexport class CancelStreamIntention extends StreamIntention<CancelStreamIntentionData> {\n txType = TransactionType.Stream;\n\n txSubType = StreamTransactionType.CANCEL;\n\n constructor(public readonly data: CancelStreamIntentionData) {\n super(data);\n }\n\n async build(input: {\n network: SuiNetworks;\n suiClient: SuiClient;\n account: WalletAccount;\n }): Promise<TransactionBlock> {\n const { network, account } = input;\n const mpayClient = this.getClient(network, account);\n const stream = await mpayClient.getStream(this.data.streamId);\n return stream.cancel();\n }\n}\n","import { TransactionType } from '@msafe/sui3-utils';\nimport { SuiClient } from '@mysten/sui.js/client';\nimport { TransactionBlock } from '@mysten/sui.js/transactions';\nimport { SuiSignTransactionBlockInput, WalletAccount } from '@mysten/wallet-standard';\nimport sortKeys from 'sort-keys-recursive';\n\nimport { SuiNetworks } from '@/types';\n\nexport interface IAppHelperInternalLegacy<T> {\n application: string;\n supportSDK: '@mysten/sui.js';\n\n deserialize(\n input: SuiSignTransactionBlockInput & {\n network: SuiNetworks;\n suiClient: SuiClient;\n account: WalletAccount;\n },\n ): Promise<{\n txType: TransactionType;\n txSubType: string;\n intentionData: T;\n }>;\n\n build(input: {\n network: SuiNetworks;\n txType: TransactionType;\n txSubType: string;\n intentionData: T;\n suiClient: SuiClient;\n account: WalletAccount;\n }): Promise<TransactionBlock>;\n}\n\nexport interface TransactionIntentionLegacy<D> {\n txType: TransactionType;\n txSubType: string;\n data: D;\n\n serialize(): string;\n\n build(input: { suiClient: SuiClient; account: WalletAccount; network: SuiNetworks }): Promise<TransactionBlock>;\n}\n\nexport abstract class BaseIntentionLegacy<D> implements TransactionIntentionLegacy<D> {\n abstract txType: TransactionType;\n\n abstract txSubType: string;\n\n protected constructor(public readonly data: D) {}\n\n serialize() {\n return JSON.stringify(sortKeys(this.data));\n }\n\n abstract build(input: {\n suiClient: SuiClient;\n account: WalletAccount;\n network: SuiNetworks;\n }): Promise<TransactionBlock>;\n}\n","import { getFullnodeUrl } from '@mysten/sui.js/client';\n\nimport * as devContractConfig from '../config/dev.json';\nimport * as prodContractConfig from '../config/prod.json';\n\nexport enum Env {\n dev = 'dev',\n stg = 'stg',\n prev = 'prev',\n prod = 'prod',\n}\n\nexport interface EnvConfig {\n env: Env;\n rpc: SuiConfig;\n backend: BackendConfig;\n contract: ContractConfig;\n}\n\nexport interface EnvConfigOptions {\n rpc?: SuiConfig;\n backend?: BackendConfig;\n contract?: ContractConfig;\n}\n\nexport interface BackendConfig {\n url: string;\n}\n\nexport interface SuiConfig {\n url: string;\n}\n\nexport interface ContractConfig {\n contractId: string;\n roleObjId: string;\n vaultObjId: string;\n feeObjId: string;\n}\n\nexport const DEV_RPC_ENDPOINT = getFullnodeUrl('testnet');\nexport const STG_RPC_ENDPOINT = getFullnodeUrl('testnet');\nexport const PREV_RPC_ENDPOINT = getFullnodeUrl('mainnet');\nexport const PROD_RPC_ENDPOINT = getFullnodeUrl('mainnet');\n\nexport const DEV_BE_API = 'https://bc3p6l5unl.execute-api.us-west-1.amazonaws.com/prod';\nexport const STG_BE_API = 'https://rolsbkota7.execute-api.us-west-1.amazonaws.com/prod';\nexport const PREV_BE_API = 'https://6p6mkx33ne.execute-api.us-west-1.amazonaws.com/prod';\nexport const PROD_BE_API = 'https://xrae3mrjv5.execute-api.us-west-1.amazonaws.com/prod';\n\nexport const CONTRACT_DEV: ContractConfig = devContractConfig;\nexport const CONTRACT_PROD: ContractConfig = prodContractConfig;\n\nconst ENV_CONFIG: Map<Env, EnvConfig> = new Map([\n [\n Env.dev,\n {\n env: Env.dev,\n rpc: {\n url: DEV_RPC_ENDPOINT,\n },\n backend: {\n url: DEV_BE_API,\n },\n contract: CONTRACT_DEV,\n },\n ],\n [\n Env.stg,\n {\n env: Env.stg,\n rpc: {\n url: STG_RPC_ENDPOINT,\n },\n backend: {\n url: STG_BE_API,\n },\n contract: CONTRACT_DEV,\n },\n ],\n [\n Env.prev,\n {\n env: Env.prev,\n rpc: {\n url: PREV_RPC_ENDPOINT,\n },\n backend: {\n url: PREV_BE_API,\n },\n contract: CONTRACT_PROD,\n },\n ],\n [\n Env.prod,\n {\n env: Env.prod,\n rpc: {\n url: PROD_RPC_ENDPOINT,\n },\n backend: {\n url: PROD_BE_API,\n },\n contract: CONTRACT_PROD,\n },\n ],\n]);\n\nexport function getConfig(env: Env, options?: EnvConfigOptions): EnvConfig {\n const ec = ENV_CONFIG.get(env);\n if (!ec) {\n throw new Error(`Env not supported: ${env}`);\n }\n if (options && options.rpc) {\n ec.rpc = options.rpc;\n }\n if (options && options.backend) {\n ec.backend = options.backend;\n }\n if (options && options.contract) {\n ec.contract = options.contract;\n }\n return ec;\n}\n","{\n \"transaction\": \"DiBZq4UmVVYiRL6ZJmFKYoHcxtxqrhsCXSkFyT7wUr3j\",\n \"status\": \"success\",\n \"contractId\": \"0x81c960dc653975fbd0072deca8afb92d322898c911622898ba1b2e3ad0c4bd8d\",\n \"roleObjId\": \"0xc6ec0bdee0bb59a72077e9acd2f42457043cf47080b3d3fad4d39abf28bba63a\",\n \"vaultObjId\": \"0xbc4021387fbac149119fd24e92be9e58f745774292f3a2a12e2ac6daf5363e1d\",\n \"feeObjId\": \"0x4178f63970fe2daeb256dc5730ad172e82b3e8eb45f31b33e0daae72cd35e1e1\",\n \"upgradeCapObjId\": \"0xe1e9aa7d222d151bfe6dd83358b0d7fdcb11260f710800cfaf7ccc1b1e245115\"\n}","{\n \"transaction\": \"855FNDV8o8Z3fWULPnQo9qdhLJpsg7wZrkCpNyfw9KfB\",\n \"status\": \"success\",\n \"contractId\": \"0xc357c3985e8fb875d6b37141497af660779aa1bab0ec489b2213efd74067d1fa\",\n \"roleObjId\": \"0x5ab49bdf9fd1413e328ef242b3f8d83dde791b38a0b627bfc87fb25c010d34f1\",\n \"vaultObjId\": \"0xb483558770d8eb26007f193b75db40f0a45f2e36863a687625885d4de6993378\",\n \"feeObjId\": \"0x48453fc4d7cde3fe35aad89e5dfb496608a6a55ea529a1c0274681a808627f94\",\n \"upgradeCapObjId\": \"0x34279779a0d0d36bd5044b04830d607fa1b0ecf316548c8ac3a44151e4f1a42a\"\n}","import { SuiClient } from '@mysten/sui.js/client';\n\nimport { EnvConfig, Env, EnvConfigOptions, getConfig } from './env';\nimport { NoBackendError } from '../error/NoBackendError';\nimport { WalletNotConnectedError } from '../error/WalletNotConnectedError';\nimport { Backend } from '../stream/backend';\nimport { IBackend } from '../types/backend';\nimport { IWallet, WalletType } from '../types/wallet';\n\nexport class Globals {\n public signer: IWallet | undefined;\n\n public readonly suiClient: SuiClient;\n\n public readonly envConfig: EnvConfig;\n\n public _backend?: IBackend;\n\n constructor(envConfig: EnvConfig) {\n this.envConfig = envConfig;\n this.suiClient = new SuiClient({ url: envConfig.rpc.url });\n if (envConfig.backend) {\n this._backend = new Backend(envConfig.backend.url);\n }\n }\n\n static new(env: Env, options?: EnvConfigOptions) {\n const ec = getConfig(env, options);\n return new Globals(ec);\n }\n\n get walletType(): WalletType | 'disconnected' {\n if (!this.wallet) {\n return 'disconnected';\n }\n return this.wallet.type;\n }\n\n get backend(): IBackend {\n if (!this._backend) {\n throw new NoBackendError();\n }\n return this._backend;\n }\n\n // Used for test cases\n set backend(b: IBackend) {\n this._backend = b;\n }\n\n connectWallet(wallet: IWallet) {\n this.signer = wallet;\n }\n\n disconnect() {\n this.signer = undefined;\n }\n\n get wallet(): IWallet {\n if (!this.signer) {\n throw new WalletNotConnectedError();\n }\n return this.signer;\n }\n\n async walletAddress() {\n return this.wallet.address();\n }\n}\n","export enum MPayErrorCode {\n sanity,\n walletNotConnected,\n InvalidInput,\n InvalidRpcResult,\n NotEnoughBalance,\n StreamNotFound,\n RpcError,\n NotCreator,\n NotRecipient,\n InvalidStreamGroup,\n BackendError,\n NoBackend,\n TransactionFailed,\n}\n\nexport type JsonObject =\n | string\n | number\n | bigint\n | boolean\n | null\n | undefined\n | readonly JsonObject[]\n | { readonly [key: string]: JsonObject }\n | { toJSON(): JsonObject };\n\nexport class MPayError extends Error {\n public readonly mpayErrorCode: number;\n\n public readonly context?: JsonObject;\n\n constructor(mpayErrorCode: number, msg: string, options: { cause?: unknown; context?: JsonObject } = {}) {\n const { cause, context } = options;\n if (cause) {\n super(`[MPay] ${msg}: ${cause}`);\n } else {\n super(`[MPay] ${msg}`);\n }\n this.mpayErrorCode = mpayErrorCode;\n this.context = context;\n }\n}\n","import { MPayError, MPayErrorCode } from './base';\n\nexport class NoBackendError extends MPayError {\n constructor() {\n super(MPayErrorCode.NoBackend, 'Backend is not specified');\n }\n}\n","import { MPayError, MPayErrorCode } from './base';\n\nexport class WalletNotConnectedError extends MPayError {\n constructor() {\n super(MPayErrorCode.walletNotConnected, 'Wallet not connected');\n }\n}\n","import axios, { AxiosError, AxiosResponse } from 'axios';\n\nimport { BackendError } from '../error/BackendError';\nimport {\n IBackend,\n BackendIncomingStreamFilterOptions,\n StreamRef,\n BackendOutgoingStreamFilterOptions,\n StreamFilterStatus,\n} from '../types/backend';\nimport { StreamEvent } from '../types/events';\nimport { PaginationOptions, Paginated } from '../types/pagination';\n\nexport class Backend implements IBackend {\n constructor(private apiURL: string) {}\n\n private static parseResponseData(response: AxiosError | AxiosResponse) {\n if (response instanceof AxiosError) {\n throw new BackendError(response.response?.statusText as string);\n }\n if (response.status === 200) {\n if (response.data.success) {\n return response.data.data;\n }\n throw new BackendError(response.data.code);\n }\n throw new BackendError(response.status.toString());\n }\n\n async getIncomingStreams(recipient: string, options?: BackendIncomingStreamFilterOptions): Promise<StreamRef[]> {\n const res = await axios.post(`${this.apiURL}/stream`, {\n recipient,\n ...options,\n });\n return Backend.parseResponseData(res) as StreamRef[];\n }\n\n async getOutgoingStreams(sender: string, options?: BackendOutgoingStreamFilterOptions): Promise<StreamRef[]> {\n const res = await axios.post(`${this.apiURL}/stream`, {\n sender,\n ...options,\n });\n return Backend.parseResponseData(res);\n }\n\n async getStreamHistory(query: {\n streamId?: string;\n groupId?: string;\n pagination?: PaginationOptions;\n }): Promise<Paginated<StreamEvent>> {\n const res = await axios.post(`${this.apiURL}/stream-events`, query);\n const paginatedData = Backend.parseResponseData(res);\n paginatedData.data.forEach((event: StreamEvent) => {\n const formalizedEvent = event;\n if (formalizedEvent.data.type === 'create_stream') {\n formalizedEvent.data.balance = BigInt(formalizedEvent.data.balance);\n } else if (formalizedEvent.data.type === 'cancel_stream') {\n formalizedEvent.data.withdrawAmount = BigInt(formalizedEvent.data.withdrawAmount);\n } else if (formalizedEvent.data.type === 'claim' || formalizedEvent.data.type === 'auto_claim') {\n formalizedEvent.data.claimAmount = BigInt(formalizedEvent.data.claimAmount);\n } else if (formalizedEvent.data.type === 'set_auto_claim') {\n formalizedEvent.data.enabled = !!formalizedEvent.data.enabled;\n }\n formalizedEvent.createdAt = new Date(formalizedEvent.createdAt);\n return formalizedEvent;\n });\n\n return paginatedData;\n }\n\n async getAllCoinTypes(address: string): Promise<string[]> {\n const res = await axios.post(`${this.apiURL}/stream-info`, { address });\n return Backend.parseResponseData(res);\n }\n\n async getAllRecipients(sender: string, options?: StreamFilterStatus): Promise<string[]> {\n const res = await axios.post(`${this.apiURL}/stream-info`, { sender, status: options });\n return Backend.parseResponseData(res);\n }\n\n async getAllSenders(recipient: string, options?: StreamFilterStatus): Promise<string[]> {\n const res = await axios.post(`${this.apiURL}/stream-info`, { recipient, status: options });\n return Backend.parseResponseData(res);\n }\n}\n","import { JsonObject, MPayError, MPayErrorCode } from './base';\n\nexport class BackendError extends MPayError {\n constructor(msg: string, context?: JsonObject) {\n super(MPayErrorCode.BackendError, msg, { context });\n }\n}\n","import { SuiClient } from '@mysten/sui.js/client';\nimport { TransactionBlock } from '@mysten/sui.js/transactions';\nimport { SUI_TYPE_ARG, normalizeStructTag, normalizeSuiAddress } from '@mysten/sui.js/utils';\nimport { WalletAccount } from '@mysten/wallet-standard';\n\nimport { MPayBuilder } from '../builder/MPayBuilder';\nimport { Env, EnvConfigOptions, Globals } from '../common';\nimport { InvalidInputError } from '../error/InvalidInputError';\nimport { SanityError } from '../error/SanityError';\nimport { getCoinsWithAmount } from '../sui/iterator/coin';\nimport { isSameCoinType } from '../sui/utils';\nimport { StreamFilterStatus } from '../types/backend';\nimport {\n CreateStreamInfo,\n IMPayClient,\n IPagedStreamListIterator,\n IncomingStreamQuery,\n OutgoingStreamQuery,\n} from '../types/client';\nimport {\n CoinRequest,\n CoinRequestResponse,\n GAS_OBJECT_SPEC,\n IMSafeAccount,\n ISingleWallet,\n IWallet,\n WalletType,\n} from '../types/wallet';\nimport { Stream } from './Stream';\nimport { MPayHelper } from './helper';\nimport { PagedStreamListIterator } from './query';\n\nexport class MSafeAccountAdapter implements IWallet {\n constructor(private readonly msafe: IMSafeAccount) {}\n\n get type() {\n return WalletType.msafe;\n }\n\n async address() {\n return this.msafe.address();\n }\n\n async requestCoins(reqs: CoinRequest[]): Promise<CoinRequestResponse[]> {\n return this.msafe.requestCoins(reqs);\n }\n}\n\nexport class MSafeSingleWallet {\n constructor(private account: WalletAccount) {}\n\n async address(): Promise<string> {\n return this.account.address;\n }\n}\n\nexport class SingleWalletAdapter implements IWallet {\n constructor(\n private readonly singleWallet: ISingleWallet,\n private readonly suiClient: SuiClient,\n ) {}\n\n get type() {\n return WalletType.single;\n }\n\n async address() {\n return this.singleWallet.address();\n }\n\n async requestCoins(reqs: CoinRequest[]): Promise<CoinRequestResponse[]> {\n return Promise.all(reqs.map((req) => this.requestCoin(req)));\n }\n\n async requestCoin(req: CoinRequest): Promise<CoinRequestResponse> {\n if (isSameCoinType(req.coinType, SUI_TYPE_ARG)) {\n return {\n primaryCoin: GAS_OBJECT_SPEC,\n };\n }\n if (req.amount <= 0) {\n throw new InvalidInputError('Invalid coin request', 'coinAmount', req.amount);\n }\n const coins = await getCoinsWithAmount(this.suiClient, await this.address(), req.amount, req.coinType);\n if (coins.length === 0) {\n throw new SanityError('no coins available');\n }\n return {\n primaryCoin: coins[0].coinObjectId,\n mergedCoins: coins.slice(1).map((coin) => coin.coinObjectId),\n };\n }\n}\n\nexport class MPayClient implements IMPayClient {\n public readonly globals: Globals;\n\n public readonly helper: MPayHelper;\n\n constructor(env: Env, options?: EnvConfigOptions) {\n this.globals = Globals.new(env, options);\n this.helper = new MPayHelper(this.globals);\n }\n\n connectSingleWallet(wallet: ISingleWallet) {\n const adapter = new SingleWalletAdapter(wallet, this.globals.suiClient);\n this.globals.connectWallet(adapter);\n }\n\n connectMSafeAccount(msafe: IMSafeAccount) {\n const adapter = new MSafeAccountAdapter(msafe);\n this.globals.connectWallet(adapter);\n }\n\n async createStream(info: CreateStreamInfo): Promise<TransactionBlock> {\n return this.builder().createStreams(info);\n }\n\n async getStream(streamId: string) {\n return Stream.new(this.globals, streamId);\n }\n\n async getIncomingStreams(query?: IncomingStreamQuery, pageSize = 10): Promise<IPagedStreamListIterator> {\n return PagedStreamListIterator.newIncoming({\n globals: this.globals,\n query,\n pageSize,\n });\n }\n\n async getOutgoingStreams(query?: OutgoingStreamQuery, pageSize = 10): Promise<IPagedStreamListIterator> {\n return PagedStreamListIterator.newOutgoing({\n globals: this.globals,\n query,\n pageSize,\n });\n }\n\n async getCoinTypesForStreamFilter(): Promise<string[]> {\n const address = await this.wallet.address();\n const coinTypes = await this.globals.backend.getAllCoinTypes(address);\n return coinTypes.map((coinType) => normalizeStructTag(coinType));\n }\n\n async getRecipientsForStreamFilter(options?: StreamFilterStatus): Promise<string[]> {\n const address = await this.wallet.address();\n const recipients = await this.globals.backend.getAllRecipients(address, options);\n return recipients.map((recipient) => normalizeSuiAddress(recipient));\n }\n\n async getCreatorsForStreamFilter(options?: StreamFilterStatus): Promise<string[]> {\n const address = await this.wallet.address();\n const creators = await this.globals.backend.getAllSenders(address, options);\n return creators.map((creator) => normalizeSuiAddress(creator));\n }\n\n get wallet() {\n return this.globals.wallet;\n }\n\n private builder() {\n return new MPayBuilder(this.globals);\n }\n}\n","import { TransactionBlock } from '@mysten/sui.js/transactions';\n\nimport { CreateStreamHelper } from './CreateStreamHelper';\nimport { Globals } from '../common';\nimport { FeeContract } from '../contract/FeeContract';\nimport { StreamContract } from '../contract/StreamContract';\nimport { CreateStreamInfo } from '../types/client';\n\n// TODO: add vault and admin control related code.\nexport class MPayBuilder {\n private readonly feeContract: FeeContract;\n\n private readonly streamContract: StreamContract;\n\n constructor(public readonly globals: Globals) {\n const config = globals.envConfig.contract;\n this.feeContract = new FeeContract(config, globals);\n this.streamContract = new StreamContract(config, globals);\n }\n\n async createStreams(info: CreateStreamInfo) {\n const infoInternal = CreateStreamHelper.convertCreateStreamInfoToInternal(info);\n return this.createStreamHelper().buildCreateStreamTransactionBlock(infoInternal);\n }\n\n createStreamHelper() {\n return new CreateStreamHelper(this.globals, this.feeContract, this.streamContract);\n }\n\n setAutoClaim(streamId: string, enabled: boolean, coinType: string) {\n const txb = new TransactionBlock();\n return this.streamContract.setAutoClaim(txb, {\n streamId,\n enabled,\n coinType,\n });\n }\n\n claimStream(streamId: string, coinType: string) {\n const txb = new TransactionBlock();\n return this.streamContract.claimStream(txb, {\n streamId,\n coinType,\n });\n }\n\n claimStreamByProxy(streamId: string, coinType: string) {\n const txb = new TransactionBlock();\n return this.streamContract.claimStreamByProxy(txb, {\n streamId,\n coinType,\n });\n }\n\n cancelStream(streamId: string, coinType: string) {\n const txb = new TransactionBlock();\n this.streamContract.cancelStream(txb, {\n streamId,\n coinType,\n });\n return txb;\n }\n}\n","import { TransactionArgument, TransactionBlock, TransactionObjectArgument } from '@mysten/sui.js/transactions';\nimport { SUI_TYPE_ARG, normalizeStructTag } from '@mysten/sui.js/utils';\n\nimport { CLAIM_FEE_NUMERATOR, FEE_DENOMINATOR, FEE_NUMERATOR, FLAT_FEE_SUI } from './const';\nimport { Globals } from '../common';\nimport { ResultRef } from '../common/transaction';\nimport { FeeContract } from '../contract/FeeContract';\nimport { InspectViewer } from '../contract/InspectViewer';\nimport { StreamContract } from '../contract/StreamContract';\nimport { encodeMetadata } from '../stream/metadata';\nimport { isSameCoinType } from '../sui/utils';\nimport {\n CreateStreamInfo,\n CreateStreamInfoInternal,\n MPayFees,\n PaymentWithFee,\n RecipientInfoInternal,\n} from '../types/client';\nimport { CoinRequest, CoinRequestResponse, GAS_OBJECT_SPEC } from '../types/wallet';\nimport { generateGroupId } from '../utils/random';\n\nexport class CreateStreamHelper {\n constructor(\n public readonly globals: Globals,\n private readonly feeContract: FeeContract,\n private readonly streamContract: StreamContract,\n ) {}\n\n static convertCreateStreamInfoToInternal(info: CreateStreamInfo): CreateStreamInfoInternal {\n return {\n metadata: encodeMetadata({\n name: info.name,\n groupId: generateGroupId(),\n }),\n coinType: normalizeStructTag(info.coinType),\n recipients: info.recipients.map((recipient) => ({\n address: recipient.address,\n cliffAmount: recipient.cliffAmount,\n amountPerEpoch: recipient.amountPerStep,\n })),\n epochInterval: info.interval,\n numberEpoch: info.steps,\n startTime: info.startTimeMs,\n cancelable: info.cancelable,\n };\n }\n\n async buildCreateStreamTransactionBlock(info: CreateStreamInfoInternal): Promise<TransactionBlock> {\n const txb = new TransactionBlock();\n const paymentWithFee = this.calculateFeesInternal(info);\n const coinReqs = this.getCreateStreamCoinRequests(info, paymentWithFee);\n const coinResp = await this.wallet.requestCoins(coinReqs);\n\n const paymentMergedObject = await this.addMergeCoins(txb, coinResp[0]);\n let flatFeeMergedObject: TransactionArgument;\n if (coinReqs.length > 1) {\n flatFeeMergedObject = await this.addMergeCoins(txb, coinResp[1]);\n } else {\n flatFeeMergedObject = paymentMergedObject;\n }\n\n // Create streams\n for (let i = 0; i < info.recipients.length; i++) {\n const recipient = info.recipients[i];\n const paymentAmount = this.amountForRecipient(recipient, info.numberEpoch);\n const feeAmount = this.getStreamFeeLocal(paymentAmount);\n const [paymentCoin] = txb.splitCoins(paymentMergedObject, [txb.pure(paymentAmount + feeAmount, 'u64')]);\n const [flatFeeCoin] = txb.splitCoins(flatFeeMergedObject, [txb.pure(this.flatSuiFee, 'u64')]);\n this.streamContract.createStream(txb, {\n paymentCoin: new ResultRef(paymentCoin as TransactionArgument & TransactionArgument[]),\n flatFeeCoin: new ResultRef(flatFeeCoin as TransactionArgument & TransactionArgument[]),\n metadata: info.metadata,\n recipient: recipient.address,\n timeStart: info.startTime,\n cliff: recipient.cliffAmount,\n epochInterval: info.epochInterval,\n numEpoch: info.numberEpoch,\n amountPerEpoch: recipient.amountPerEpoch,\n cancelable: info.cancelable,\n coinType: info.coinType,\n });\n }\n return txb;\n }\n\n calculateCreateStreamFees(createInfo: CreateStreamInfo) {\n const infoInternal = CreateStreamHelper.convertCreateStreamInfoToInternal(createInfo);\n return this.calculateFeesInternal(infoInternal);\n }\n\n feeParams(): MPayFees {\n return {\n createFeePercent: {\n numerator: FEE_NUMERATOR,\n denominator: FEE_DENOMINATOR,\n },\n claimFeePercent: {\n numerator: CLAIM_FEE_NUMERATOR,\n denominator: FEE_DENOMINATOR,\n },\n flatFeePerStream: FLAT_FEE_SUI,\n };\n }\n\n private async addMergeCoins(txb: TransactionBlock, coins: CoinRequestResponse): Promise<TransactionObjectArgument> {\n let mergedCoin: TransactionObjectArgument;\n if (coins.mergedCoins && coins.mergedCoins.length) {\n txb.mergeCoins(\n txb.object(coins.primaryCoin),\n coins.mergedCoins.map((coinId) => txb.object(coinId)),\n );\n mergedCoin = txb.object(coins.primaryCoin);\n } else if (coins.primaryCoin === GAS_OBJECT_SPEC) {\n mergedCoin = txb.gas;\n } else {\n mergedCoin = txb.object(coins.primaryCoin);\n }\n return mergedCoin;\n }\n\n getCreateStreamCoinRequests(info: CreateStreamInfoInternal, payment: PaymentWithFee): CoinRequest[] {\n const streamCoinType = info.coinType;\n\n if (isSameCoinType(streamCoinType, SUI_TYPE_ARG)) {\n return [\n {\n coinType: streamCoinType,\n amount: payment.totalAmount + payment.streamFeeAmount + payment.flatFeeAmount,\n },\n ];\n }\n return [\n {\n coinType: streamCoinType,\n amount: payment.totalAmount + payment.streamFeeAmount,\n },\n {\n coinType: SUI_TYPE_ARG,\n amount: payment.flatFeeAmount,\n },\n ];\n }\n\n calculateFeesInternal(info: CreateStreamInfoInternal): PaymentWithFee {\n const streamPayment = info.recipients.reduce(\n (sum, recipient) => {\n const totalAmount = this.amountForRecipient(recipient, info.numberEpoch);\n const fee = this.getStreamFeeLocal(totalAmount);\n return {\n totalAmount: sum.totalAmount + totalAmount,\n streamFeeAmount: sum.streamFeeAmount + fee,\n };\n },\n {\n totalAmount: 0n,\n streamFeeAmount: 0n,\n },\n );\n const flatFeeAmount = BigInt(info.recipients.length) * this.flatSuiFee;\n return {\n flatFeeAmount,\n ...streamPayment,\n };\n }\n\n private amountForRecipient(recipient: RecipientInfoInternal, numEpoch: bigint) {\n return BigInt(recipient.amountPerEpoch) * BigInt(numEpoch) + BigInt(recipient.cliffAmount);\n }\n\n get flatSuiFee() {\n return FLAT_FEE_SUI;\n }\n\n getStreamFeeLocal(streamAmount: bigint) {\n return (streamAmount * FEE_NUMERATOR) / FEE_DENOMINATOR;\n }\n\n async getStreamFeeRemote(streamAmount: bigint) {\n const txb = this.feeContract.streamingFee(new TransactionBlock(), streamAmount);\n const res = await this.globals.suiClient.devInspectTransactionBlock({\n sender: await this.globals.walletAddress(),\n transactionBlock: txb,\n });\n const iv = new InspectViewer(res);\n return iv.getU64();\n }\n\n get wallet() {\n return this.globals.wallet;\n }\n}\n","export const FEE_NUMERATOR = 50n;\nexport const FEE_DENOMINATOR = 10000n;\nexport const CLAIM_FEE_NUMERATOR = 25n;\nexport const FLAT_FEE_SUI = 100000000n;\n","import { TransactionArgument, TransactionBlock } from '@mysten/sui.js/transactions';\n\nexport type MoveNumber = bigint | string | number;\nexport type Ref<T> = T | ResultRef;\nexport type ObjectId = string;\n\nexport class MoveObject {\n constructor(public readonly object: string) {}\n\n moveArg(txb: TransactionBlock) {\n return txb.object(this.object);\n }\n}\n\nexport class ObjectVector {\n constructor(public readonly objects: string[]) {}\n\n moveArgs(txb: TransactionBlock) {\n return txb.makeMoveVec({ objects: this.objects.map((o) => txb.object(o)) });\n }\n}\n\nexport class ResultRef {\n constructor(public readonly result: TransactionArgument & TransactionArgument[]) {\n // eslint-disable-next-line no-constructor-return\n return new Proxy(this, {\n set() {\n throw new Error('The transaction result is a proxy, and does not support setting properties directly');\n },\n get(target, property) {\n // This allows this transaction argument to be used in the singular form:\n if (property in target) {\n return Reflect.get(target, property);\n }\n\n const nestedResultFor = (resultIndex: number) => new ResultRef(target.result[resultIndex] as any);\n\n // Support destructuring:\n if (property === Symbol.iterator) {\n return function* () {\n let i = 0;\n while (true) {\n yield nestedResultFor(i);\n i++;\n }\n };\n }\n\n if (typeof property === 'symbol') {\n // eslint-disable-next-line consistent-return\n return;\n }\n\n const resultIndex = parseInt(property, 10);\n if (Number.isNaN(resultIndex) || resultIndex < 0) {\n // eslint-disable-next-line consistent-return\n return;\n }\n return nestedResultFor(resultIndex);\n },\n });\n }\n\n moveArg() {\n return this.result;\n }\n}\n","import { Buffer } from 'buffer';\n\nimport { DevInspectResults, SuiExecutionResult } from '@mysten/sui.js/client';\nimport { normalizeSuiAddress } from '@mysten/sui.js/utils';\n\nimport { InvalidRpcResultError } from '../error/InvalidRpcResultError';\n\nexport class InspectViewer {\n constructor(readonly results: DevInspectResults) {}\n\n callResult(index: number) {\n return this.results.results![index];\n }\n\n returnValue(returned: SuiExecutionResult, index: number) {\n return returned.returnValues![index];\n }\n\n getValue(callIndex = 0, returnIndex = 0) {\n const callResult = this.callResult(callIndex);\n return this.returnValue(callResult, returnIndex);\n }\n\n getAddress(callIndex = 0, returnIndex = 0) {\n const [value, type] = this.getValue(callIndex, returnIndex);\n if (type !== 'address') {\n throw new InvalidRpcResultError('Invalid contract return type.', {\n ctx: {\n expectType: 'address',\n gotType: type,\n },\n });\n }\n return normalizeSuiAddress(Buffer.from(value).toString('hex'));\n }\n\n getU64(callIndex = 0, returnIndex = 0) {\n const [value, type] = this.getValue(callIndex, returnIndex);\n if (type !== 'u64') {\n throw new InvalidRpcResultError('Invalid contract return type.', {\n ctx: {\n expectType: 'u64',\n gotType: type,\n },\n });\n }\n return Buffer.from(value).readBigInt64LE();\n }\n}\n","import { MPayError, JsonObject, MPayErrorCode } from './base';\n\nexport class InvalidRpcResultError extends MPayError {\n constructor(msg: string, ctx?: JsonObject) {\n super(MPayErrorCode.InvalidRpcResult, msg, { context: ctx });\n }\n}\n","import { bcs } from '@mysten/sui.js/bcs';\n\nimport { InvalidInputError } from '../error/InvalidInputError';\nimport { StreamMetadata } from '../types/stream';\n\nexport const metadataBcsType = {\n groupId: 'string',\n name: 'string',\n};\n\nconst MAX_NAME_SIZE = 64;\n\nexport function encodeMetadata(metadata: StreamMetadata) {\n validateMetadata(metadata);\n return bcs.ser(metadataBcsType, metadata).toString('base64');\n}\n\nexport function decodeMetadata(metaStr: string) {\n const metadata = bcs.de(metadataBcsType, metaStr, 'base64') as StreamMetadata;\n validateMetadata(metadata);\n return metadata;\n}\n\nexport function validateMetadata(metadata: StreamMetadata) {\n if (!isAsciiString(metadata.name)) {\n throw new InvalidInputError('Invalid metadata: Name contains unknown character');\n }\n if (!isAsciiString(metadata.groupId)) {\n throw new InvalidInputError('Invalid metadata: Group ID contains unknown character');\n }\n if (metadata.name.length > MAX_NAME_SIZE) {\n throw new InvalidInputError('Invalid metadata: Name exceed max length 64');\n }\n}\n\nfunction isAsciiString(str: string) {\n // eslint-disable-next-line no-control-regex\n const asciiPattern = /^[\\x00-\\x7F]+$/;\n return asciiPattern.test(str);\n}\n","import { MPayError, MPayErrorCode } from './base';\n\nexport class InvalidInputError extends MPayError {\n constructor(msg: string, fieldKey?: string, fieldValue?: any) {\n super(MPayErrorCode.InvalidInput, `Invalid input: ${msg}`, {\n context: {\n fieldKey,\n fieldValue,\n },\n });\n }\n}\n","import { normalizeStructTag } from '@mysten/sui.js/utils';\n\nexport function isSameCoinType(type1: string, type2: string) {\n return normalizeStructTag(type1) === normalizeStructTag(type2);\n}\n\nexport function isSameTarget(target1: string, target2: string): boolean {\n return normalizeStructTag(target1) === normalizeStructTag(target2);\n}\n","export enum WalletType {\n single = 'single',\n msafe = 'msafe',\n}\n\nexport const GAS_OBJECT_SPEC = 'txn.gas';\n\n/**\n * IWallet is the adapted interface of wallet. Supports both single wallet and msafe.\n */\nexport interface IWallet {\n type: WalletType;\n\n address(): Promise<string>;\n\n requestCoins(reqs: CoinRequest[]): Promise<CoinRequestResponse[]>;\n}\n\n/**\n * ISingleWallet is the raw interface of msafe account.\n * Need to adapt to IWallet interface\n */\nexport interface IMSafeAccount {\n address(): Promise<string>;\n\n // return coin objects by amount.\n requestCoins(reqs: CoinRequest[]): Promise<CoinRequestResponse[]>;\n}\n\n/**\n * ISingleWallet is the raw interface of single signer wallet.\n * Need to adapt to IWallet interface\n */\nexport interface ISingleWallet {\n address(): Promise<string>;\n}\n\nexport interface CoinRequest {\n coinType: string;\n amount: bigint;\n}\n\nexport interface CoinRequestResponse {\n primaryCoin: string;\n mergedCoins?: string[];\n}\n","import { nanoid } from 'nanoid';\n\nexport function generateGroupId() {\n return nanoid();\n}\n","import { TransactionBlock, Transactions } from '@mysten/sui.js/transactions';\n\nimport { ContractConfig, Globals } from '../common';\nimport { ObjectVector, MoveObject, ResultRef, Ref, ObjectId } from '../common/transaction';\nimport { CLOCK_ID } from '../const';\n\nexport class BaseContract {\n constructor(\n public readonly moduleName: string,\n public readonly config: ContractConfig,\n public readonly globals: Globals,\n ) {}\n\n addContractCall(txb: TransactionBlock, input: { method: string; arguments: any[]; typeArgs?: string[] }) {\n const target =\n `${this.config.contractId}::${this.moduleName}::${input.method}` as `${string}::${string}::${string}`;\n txb.add(\n Transactions.MoveCall({\n target,\n arguments: input.arguments.map((arg) => {\n if (arg instanceof ObjectVector) {\n return arg.moveArgs(txb);\n }\n if (arg instanceof MoveObject) {\n return arg.moveArg(txb);\n }\n if (arg instanceof ResultRef) {\n return arg.moveArg();\n }\n return txb.pure(arg);\n }),\n typeArguments: input.typeArgs,\n }),\n );\n return txb;\n }\n\n private addTransactionBlock(txb: TransactionBlock, target: string, callArgs: any[] = [], typeArgs: string[] = []) {\n txb.add(\n Transactions.MoveCall({\n target: target as `${string}::${string}::${string}`,\n arguments: callArgs.map((arg) => {\n if (arg instanceof ObjectVector) {\n return arg.moveArgs(txb);\n }\n if (arg instanceof MoveObject) {\n return arg.moveArg(txb);\n }\n if (arg instanceof ResultRef) {\n return arg.moveArg();\n }\n return txb.pure(arg);\n }),\n typeArguments: typeArgs,\n }),\n );\n }\n\n makeObject(object: Ref<ObjectId>) {\n return typeof object === 'string' ? new MoveObject(object) : object;\n }\n\n vaultObject() {\n return new MoveObject(this.config.vaultObjId);\n }\n\n roleObject() {\n return new MoveObject(this.config.roleObjId);\n }\n\n feeObject() {\n return new MoveObject(this.config.feeObjId);\n }\n\n clockObject() {\n return new MoveObject(CLOCK_ID);\n }\n}\n","export const CLOCK_ID = '0x0000000000000000000000000000000000000000000000000000000000000006';\n","import { TransactionBlock } from '@mysten/sui.js/transactions';\n\nimport { BaseContract } from './BaseContract';\nimport { ContractConfig, Globals } from '../common';\nimport { MoveNumber } from '../common/transaction';\n\nexport class FeeContract extends BaseContract {\n static ModuleName = 'fee_module';\n\n static MethodName = {\n set_streaming_fee: 'set_streaming_fee',\n set_claim_fee: 'set_claim_fee',\n set_streaming_flat_fee: 'set_streaming_flat_fee',\n streaming_flat_fee: 'streaming_flat_fee',\n streaming_fee: 'streaming_fee',\n claim_fee: 'claim_fee',\n fee_denominator: 'fee_denominator',\n } as const;\n\n constructor(\n public readonly config: ContractConfig,\n public readonly globals: Globals,\n ) {\n super(FeeContract.ModuleName, config, globals);\n }\n\n setStreamingFee(txb: TransactionBlock, createFeeNumerator: MoveNumber) {\n const roleObject = this.roleObject();\n const feeObject = this.feeObject();\n return this.addContractCall(txb, {\n method: FeeContract.MethodName.set_streaming_fee,\n arguments: [roleObject, feeObject, createFeeNumerator],\n typeArgs: [],\n });\n }\n\n setStreamingFlatFee(txb: TransactionBlock, flatFee: MoveNumber) {\n const roleObject = this.roleObject();\n const feeObject = this.feeObject();\n return this.addContractCall(txb, {\n method: FeeContract.MethodName.set_streaming_flat_fee,\n arguments: [roleObject, feeObject, flatFee],\n typeArgs: [],\n });\n }\n\n setClaimFee(txb: TransactionBlock, claimFee: MoveNumber) {\n const roleObject = this.roleObject();\n const feeObject = this.feeObject();\n return this.addContractCall(txb, {\n method: FeeContract.MethodName.set_claim_fee,\n arguments: [roleObject, feeObject, claimFee],\n typeArgs: [],\n });\n }\n\n streamingFee(txb: TransactionBlock, amount: MoveNumber) {\n const feeObject = this.feeObject();\n return this.addContractCall(txb, {\n method: FeeContract.MethodName.streaming_fee,\n arguments: [feeObject, amount],\n typeArgs: [],\n });\n }\n\n claimFee(txb: TransactionBlock, amount: MoveNumber) {\n return this.addContractCall(txb, {\n method: FeeContract.MethodName.claim_fee,\n arguments: [this.feeObject(), amount],\n typeArgs: [],\n });\n }\n\n feeDenominator(txb: TransactionBlock) {\n return this.addContractCall(txb, {\n method: FeeContract.MethodName.fee_denominator,\n arguments: [this.feeObject()],\n typeArgs: [],\n });\n }\n}\n","import { TransactionBlock } from '@mysten/sui.js/transactions';\n\nimport { BaseContract } from './BaseContract';\nimport { ContractConfig, Globals } from '../common';\nimport { Ref, ObjectId, MoveNumber } from '../common/transaction';\n\nexport class StreamContract extends BaseContract {\n static ModuleName = 'stream';\n\n static MethodName = {\n create_stream: 'create_stream',\n set_auto_claim: 'set_auto_claim',\n cancel_stream: 'cancel_stream',\n claim_stream: 'claim_stream',\n claim_stream_by_proxy: 'claim_stream_by_proxy',\n stream_current_epoch: 'stream_current_epoch',\n now_milli_seconds: 'now_milli_seconds',\n } as const;\n\n constructor(\n public readonly config: ContractConfig,\n public readonly globals: Globals,\n ) {\n super(StreamContract.ModuleName, config, globals);\n }\n\n createStream(\n txb: TransactionBlock,\n input: {\n paymentCoin: Ref<ObjectId>;\n flatFeeCoin: Ref<ObjectId>;\n metadata: string;\n recipient: string;\n timeStart: Ref<MoveNumber>;\n cliff: Ref<MoveNumber>;\n epochInterval: Ref<MoveNumber>;\n numEpoch: Ref<MoveNumber>;\n amountPerEpoch: Ref<MoveNumber>;\n cancelable: boolean;\n coinType: string;\n },\n ) {\n const feeObject = this.feeObject();\n const vaultObject = this.vaultObject();\n const paymentCoinObject = this.makeObject(input.paymentCoin);\n const flatFeeObject = this.makeObject(input.flatFeeCoin);\n const clockObject = this.clockObject();\n return this.addContractCall(txb, {\n method: StreamContract.MethodName.create_stream,\n arguments: [\n feeObject,\n vaultObject,\n paymentCoinObject,\n flatFeeObject,\n input.metadata,\n input.recipient,\n input.timeStart,\n input.cliff,\n input.epochInterval,\n input.numEpoch,\n input.amountPerEpoch,\n input.cancelable,\n clockObject,\n ],\n typeArgs: [input.coinType],\n });\n }\n\n setAutoClaim(\n txb: TransactionBlock,\n input: {\n streamId: Ref<ObjectId>;\n enabled: boolean;\n coinType: string;\n },\n ) {\n const streamObject = this.makeObject(input.streamId);\n return this.addContractCall(txb, {\n method: StreamContract.MethodName.set_auto_claim,\n arguments: [streamObject, input.enabled],\n typeArgs: [input.coinType],\n });\n }\n\n cancelStream(\n txb: TransactionBlock,\n input: {\n streamId: Ref<ObjectId>;\n coinType: string;\n },\n ) {\n const streamObject = this.makeObject(input.streamId);\n const clockObject = this.clockObject();\n return this.addContractCall(txb, {\n method: StreamContract.MethodName.cancel_stream,\n arguments: [streamObject, clockObject],\n typeArgs: [input.coinType],\n });\n }\n\n claimStream(\n txb: TransactionBlock,\n input: {\n streamId: Ref<ObjectId>;\n coinType: string;\n },\n ) {\n const streamObject = this.makeObject(input.streamId);\n const clockObject = this.clockObject();\n return this.addContractCall(txb, {\n method: StreamContract.MethodName.claim_stream,\n arguments: [streamObject, clockObject],\n typeArgs: [input.coinType],\n });\n }\n\n claimStreamByProxy(\n txb: TransactionBlock,\n input: {\n streamId: Ref<ObjectId>;\n coinType: string;\n },\n ) {\n const streamObject = this.makeObject(input.streamId);\n const vaultObject = this.vaultObject();\n const feeObject = this.feeObject();\n const clockObject = this.clockObject();\n return this.addContractCall(txb, {\n method: StreamContract.MethodName.claim_stream_by_proxy,\n arguments: [streamObject, vaultObject, feeObject, clockObject],\n typeArgs: [input.coinType],\n });\n }\n\n get createStreamTarget() {\n return `${this.config.contractId}::${StreamContract.ModuleName}::${StreamContract.MethodName.create_stream}`;\n }\n\n get setAutoClaimTarget() {\n return `${this.config.contractId}::${StreamContract.ModuleName}::${StreamContract.MethodName.set_auto_claim}`;\n }\n\n get cancelStreamTarget() {\n return `${this.config.contractId}::${StreamContract.ModuleName}::${StreamContract.MethodName.cancel_stream}`;\n }\n\n get claimStreamTarget() {\n return `${this.config.contractId}::${StreamContract.ModuleName}::${StreamContract.MethodName.claim_stream}`;\n }\n\n get claimStreamByProxyTarget() {\n return `${this.config.contractId}::${StreamContract.ModuleName}::${StreamContract.MethodName.claim_stream_by_proxy}`;\n }\n}\n","import { MPayError, JsonObject, MPayErrorCode } from './base';\n\n/**\n * SanityError is the error reported because of error in code.\n * For normal user process, the sanity error shall never be thrown.\n */\nexport class SanityError extends MPayError {\n constructor(msg: string, options: { cause?: unknown; context?: JsonObject } = {}) {\n super(MPayErrorCode.sanity, msg, options);\n }\n}\n","import { PagedData, Requester } from './requester';\n\nexport const REQUEST_PAGE_SIZE = 25;\n\nexport interface SuiIterator<T> {\n next: () => Promise<T | undefined>;\n hasNext: () => Promise<boolean>;\n}\n\nexport async function getAllFromIterator<T>(it: SuiIterator<T>): Promise<(T | undefined) | (T | undefined)[]> {\n const res: (T | undefined)[] = [];\n while (await it.hasNext()) {\n const val = await it.next();\n res.push(val);\n }\n if (res && Array.isArray(res[0])) {\n return res.flat(1) as T;\n }\n return res;\n}\n\nexport class PagedIterator<T> implements SuiIterator<(T | undefined)[]> {\n private curPage: PagedData<T> | undefined;\n\n private init: boolean;\n\n constructor(public readonly requester: Requester<T>) {\n this.curPage = undefined;\n this.init = true;\n }\n\n async hasNext(): Promise<boolean> {\n if (this.init) {\n if (!this.curPage) {\n this.curPage = await this.requester.doNextRequest();\n }\n return !!this.curPage.data?.length || this.curPage.hasNext;\n }\n if (!this.curPage) {\n throw new Error('invalid implementation of iterator');\n }\n return this.curPage.hasNext;\n }\n\n async next(): Promise<(T | undefined)[]> {\n if (this.init) {\n this.init = false;\n if (!this.curPage) {\n this.curPage = await this.requester.doNextRequest();\n }\n return this.curPage.data;\n }\n this.curPage = await this.requester.doNextRequest();\n return this.curPage.data;\n }\n}\n\nexport class EntryIterator<T> implements SuiIterator<T> {\n cursor: number;\n\n pager: PagedIterator<T>;\n\n curData: (T | undefined)[];\n\n constructor(public readonly requester: Requester<T>) {\n this.pager = new PagedIterator<T>(requester);\n this.curData = [];\n this.cursor = 0;\n }\n\n async hasNext(): Promise<boolean> {\n if (this.cursor < this.curData.length - 1) {\n return true;\n }\n return this.pager.hasNext();\n }\n\n async next(): Promise<T | undefined> {\n this.cursor += 1;\n while (this.cursor >= this.curData.length) {\n if (!(await this.pager.hasNext())) {\n throw new Error('not more data'); // Shall not happen for legit data source.\n } else {\n this.curData = await this.pager.next();\n this.cursor = 0;\n }\n }\n return this.curData[this.cursor];\n }\n}\n","import { MPayError, MPayErrorCode } from './base';\n\nexport class NotEnoughBalanceError extends MPayError {\n constructor(\n public readonly coinType: string,\n public readonly requestAmount: bigint,\n public readonly gotAmount: bigint,\n ) {\n super(MPayErrorCode.NotEnoughBalance, `Not enough balance: ${coinType}`, {\n context: {\n coinType,\n requestAmount,\n gotAmount,\n },\n });\n }\n}\n","import { SuiClient, CoinStruct } from '@mysten/sui.js/client';\n\nimport { getAllFromIterator, EntryIterator } from './iterator';\nimport { Requester, PagedData } from './requester';\nimport { NotEnoughBalanceError } from '../../error/NotEnoughBalanceError';\nimport { SanityError } from '../../error/SanityError';\n\nconst DEF_REQ_PAGE_SIZE = 25;\n\nexport async function getCoinsWithAmount(\n suiClient: SuiClient,\n owner: string,\n requestAmount: bigint,\n coinType = '0x2::sui::SUI',\n pageSize: number = DEF_REQ_PAGE_SIZE,\n) {\n const it = new OwnedCoinIterator(suiClient, owner, coinType, pageSize);\n let totalAmount = BigInt(0);\n const res: CoinStruct[] = [];\n while ((await it.hasNext()) && totalAmount < requestAmount) {\n const val = await it.next();\n if (!val) {\n continue;\n }\n res.push(val);\n totalAmount += BigInt(val.balance);\n }\n if (totalAmount < requestAmount) {\n throw new NotEnoughBalanceError(coinType, requestAmount, totalAmount);\n }\n return res;\n}\n\nexport async function getAllOwnedCoins(\n suiClient: SuiClient,\n owner: string,\n coinType = '0x2::sui::SUI',\n pageSize: number = DEF_REQ_PAGE_SIZE,\n) {\n const iter = new OwnedCoinIterator(suiClient, owner, coinType, pageSize);\n return (await getAllFromIterator(iter)) as CoinStruct[];\n}\n\nexport class OwnedCoinIterator extends EntryIterator<CoinStruct> {\n constructor(\n private readonly suiClient: SuiClient,\n private readonly owner: string,\n private readonly coinType: string,\n private readonly reqPageSize: number,\n ) {\n super(new OwnedCoinRequester(suiClient, owner, coinType, reqPageSize));\n }\n}\n\nexport class OwnedCoinRequester implements Requester<CoinStruct> {\n nextCursor: string | null | undefined;\n\n constructor(\n private readonly suiClient: SuiClient,\n private readonly owner: string,\n private readonly coinType: string,\n private readonly reqPageSize: number,\n ) {\n if (reqPageSize <= 0) {\n throw new SanityError('Invalid reqPageSize');\n }\n }\n\n async doNextRequest(): Promise<PagedData<CoinStruct>> {\n const res = await this.suiClient.getCoins({\n owner: this.owner,\n coinType: this.coinType,\n cursor: this.nextCursor,\n limit: this.reqPageSize,\n });\n this.nextCursor = res.nextCursor;\n return {\n data: res.data,\n hasNext: res.hasNextPage,\n };\n }\n}\n","import { SuiObjectData, SuiObjectResponse, SuiParsedData } from '@mysten/sui.js/client';\nimport { TransactionBlock } from '@mysten/sui.js/transactions';\nimport { normalizeStructTag, parseStructTag } from '@mysten/sui.js/utils';\nimport { DateTime, Duration } from 'luxon';\n\nimport { decodeMetadata } from './metadata';\nimport { Globals } from '../common';\nimport { StreamContract } from '../contract/StreamContract';\nimport { NotCreatorError } from '../error/NotCreatorError';\nimport { NotRecipientError } from '../error/NotRecipientError';\nimport { RpcError } from '../error/RpcError';\nimport { SanityError } from '../error/SanityError';\nimport { StreamNotFoundError } from '../error/StreamNotFoundError';\nimport { RawStreamData, RawStreamStatusEnum } from '../types/data';\nimport { StreamEvent } from '../types/events';\nimport { PaginationOptions, Paginated } from '../types/pagination';\nimport { IStream, StreamInfo, StreamGroupCommonInfo, StreamProgress, StreamStatus } from '../types/stream';\nimport { MAX_U64, roundDateTime, roundDuration } from '../utils/utils';\n\nexport class Stream implements IStream {\n private readonly streamContract: StreamContract;\n\n public readonly type = 'Stream';\n\n constructor(\n public readonly globals: Globals,\n public readonly streamId: string,\n public rawData: RawStreamData,\n ) {\n this.streamContract = new StreamContract(globals.envConfig.contract, globals);\n }\n\n static async new(globals: Globals, streamId: string) {\n const rawData = await Stream.fetchStreamData(globals, streamId);\n return new Stream(globals, streamId, rawData);\n }\n\n static fromObjectData(globals: Globals, streamId: string, data: SuiObjectResponse) {\n const rawData = Stream.parseRawStreamData(streamId, data);\n return new Stream(globals, streamId, rawData);\n }\n\n get info(): StreamInfo {\n return {\n name: this.name,\n creator: this.creator,\n coinType: this.coinType,\n totalAmount: this.totalAmount,\n start: this.timeStart,\n end: this.timeEnd,\n cancelable: this.cancelable,\n cliffAmount: this.cliff,\n duration: this.duration,\n interval: this.interval,\n steps: this.totalSteps,\n nextReleaseDate: this.nextReleaseDate,\n nextReleaseAmount: this.nextReleaseAmount,\n\n groupId: this.groupId,\n streamId: this.streamId,\n recipient: this.recipient,\n progress: this.progress,\n autoClaim: this.autoClaim,\n };\n }\n\n get groupCommonInfo(): StreamGroupCommonInfo {\n return {\n name: this.name,\n groupId: this.groupId,\n creator: this.creator,\n start: this.timeStart,\n interval: this.interval,\n steps: this.totalSteps,\n cancelable: this.cancelable,\n };\n }\n\n async refresh() {\n this.rawData = await Stream.fetchStreamData(this.globals, this.streamId);\n }\n\n refreshWithData(data: SuiObjectResponse) {\n if (data.data?.objectId !== this.streamId) {\n throw new SanityError('Object Id does not align');\n }\n this.rawData = Stream.parseRawStreamData(this.streamId, data);\n }\n\n async historyEvents(pagination?: PaginationOptions): Promise<Paginated<StreamEvent>> {\n return this.globals.backend.getStreamHistory({\n streamId: this.streamId,\n pagination,\n });\n }\n\n async cancel() {\n if ((await this.globals.walletAddress()) !== this.creator) {\n throw new NotCreatorError();\n }\n const txb = new TransactionBlock();\n this.streamContract.cancelStream(txb, {\n streamId: this.streamId,\n coinType: this.coinType,\n });\n return txb;\n }\n\n async claim() {\n if ((await this.globals.walletAddress()) !== this.recipient) {\n throw new NotRecipientError();\n }\n const txb = new TransactionBlock();\n this.streamContract.claimStream(txb, {\n streamId: this.streamId,\n coinType: this.coinType,\n });\n return txb;\n }\n\n async setAutoClaim(enabled: boolean) {\n if ((await this.globals.walletAddress()) !== this.recipient) {\n throw new NotRecipientError();\n }\n const txb = new TransactionBlock();\n this.streamContract.setAutoClaim(txb, {\n streamId: this.streamId,\n coinType: this.coinType,\n enabled,\n });\n return txb;\n }\n\n async claimByProxy() {\n const txb = new TransactionBlock();\n this.streamContract.claimStreamByProxy(txb, {\n streamId: this.streamId,\n coinType: this.coinType,\n });\n return txb;\n }\n\n get wallet() {\n return this.globals.wallet;\n }\n\n get client() {\n return this.globals.suiClient;\n }\n\n get coinType() {\n return normalizeStructTag(this.rawData.coinType);\n }\n\n get progress(): StreamProgress {\n return {\n status: this.streamStatus,\n total: this.totalAmount,\n streamed: this.streamedAmount,\n claimed: this.claimedAmount,\n claimable: this.claimable,\n canceled: this.canceledAmount,\n };\n }\n\n get balance() {\n return this.rawData.balance;\n }\n\n get autoClaim() {\n return this.rawData.autoClaim;\n }\n\n get amountPerEpoch() {\n return this.rawData.config.amountPerEpoch;\n }\n\n get cancelable() {\n return this.rawData.config.cancelable;\n }\n\n get cliff() {\n return this.rawData.config.cliff;\n }\n\n get creator() {\n return this.rawData.config.creator;\n }\n\n get interval(): Duration {\n return roundDuration(this.rawData.config.epochInterval);\n }\n\n get groupId() {\n const { metadata } = this.rawData.config;\n const md = decodeMetadata(metadata);\n return md.groupId;\n }\n\n get name() {\n const { metadata } = this.rawData.config;\n const md = decodeMetadata(metadata);\n return md.name;\n }\n\n get recipient() {\n return this.rawData.config.recipient;\n }\n\n get timeStart(): DateTime {\n return roundDateTime(this.rawData.config.timeStart);\n }\n\n get duration(): Duration {\n const rawConfig = this.rawData.config;\n const duration = rawConfig.epochInterval * rawConfig.totalEpoch;\n return roundDuration(duration);\n }\n\n get timeEnd(): DateTime {\n return this.timeStart.plus(this.duration);\n }\n\n get totalSteps(): bigint {\n return this.rawData.config.totalEpoch;\n }\n\n get claimable(): bigint {\n return this.streamedAmount - this.claimedAmount;\n }\n\n get nextReleaseDate(): DateTime | null {\n if (this.currentEpoch === -1n) {\n return this.timeStart;\n }\n if (this.currentEpoch >= this.totalSteps || this.isCanceled) {\n return null;\n }\n return roundDateTime((this.currentEpoch + 1n) * this.rawData.config.epochInterval + this.rawData.config.timeStart);\n }\n\n get nextReleaseAmount(): bigint | null {\n if (this.currentEpoch === -1n) {\n return this.cliff;\n }\n if (this.currentEpoch >= this.totalSteps || this.isCanceled) {\n return null;\n }\n return this.amountPerEpoch;\n }\n\n get streamStatus(): StreamStatus {\n const rawStatus = this.rawData.status.status;\n if (rawStatus === RawStreamStatusEnum.CANCELED) {\n return StreamStatus.CANCELED;\n }\n if (rawStatus === RawStreamStatusEnum.CANCELED_COMPLETED) {\n return StreamStatus.SETTLED;\n }\n if (rawStatus === RawStreamStatusEnum.COMPLETED) {\n return StreamStatus.COMPLETED;\n }\n if (this.currentEpoch >= this.totalSteps) {\n return StreamStatus.STREAMED;\n }\n return StreamStatus.STREAMING;\n }\n\n get streamedAmount() {\n if (this.currentEpoch === -1n) {\n return 0n;\n }\n if (this.isCanceled) {\n return this.rawData.status.epochCanceled * this.amountPerEpoch + this.cliff;\n }\n return this.currentEpoch * this.amountPerEpoch + this.cliff;\n }\n\n get claimedAmount() {\n if (this.rawData.status.epochClaimed === MAX_U64) {\n return 0n;\n }\n return this.rawData.status.epochClaimed * this.amountPerEpoch + this.cliff;\n }\n\n get currentEpoch() {\n const timeNowMs = DateTime.now().toMillis();\n const timeStartMs = this.timeStart.toMillis();\n if (timeNowMs < timeStartMs) {\n return -1n;\n }\n const epoch = Math.floor((timeNowMs - timeStartMs) / Number(this.rawData.config.epochInterval));\n return BigInt(epoch) > Number(this.rawData.config.totalEpoch) ? this.rawData.config.totalEpoch : BigInt(epoch);\n }\n\n get totalAmount() {\n const rawConfig = this.rawData.config;\n return rawConfig.amountPerEpoch * rawConfig.totalEpoch + rawConfig.cliff;\n }\n\n get isCanceled() {\n const rawStatus = this.rawData.status.status;\n return rawStatus === RawStreamStatusEnum.CANCELED || rawStatus === RawStreamStatusEnum.CANCELED_COMPLETED;\n }\n\n get canceledAmount() {\n return this.isCanceled ? this.totalAmount - this.streamedAmount : 0n;\n }\n\n private static async fetchStreamData(globals: Globals, streamId: string) {\n const res = await globals.suiClient.getObject({\n id: streamId,\n options: {\n showContent: true,\n showType: true,\n },\n });\n return Stream.parseRawStreamData(streamId, res);\n }\n\n static parseRawStreamData(streamId: string, res: SuiObjectResponse): RawStreamData {\n if (res.error) {\n if (res.error.code === 'notExists') {\n throw new StreamNotFoundError(streamId);\n }\n throw new RpcError(`get stream data: ${res.error.code}`, {\n streamId,\n ...res.error,\n });\n }\n const content = (res.data as SuiObjectData).content as SuiParsedData;\n if (content.dataType !== 'moveObject') {\n throw new RpcError('Unexpected object type', {\n gotType: content.dataType,\n });\n }\n const { typeParams } = parseStructTag(content.type);\n const coinType = normalizeStructTag(typeParams[0]);\n\n const dataFields = content.fields as any;\n const config = dataFields.config.fields as any;\n const status = dataFields.status.fields as any;\n\n return {\n coinType,\n autoClaim: dataFields.auto_claim as boolean,\n balance: BigInt(dataFields.balance.fields.balance),\n config: {\n amountPerEpoch: BigInt(config.amount_per_epoch),\n cancelable: config.cancelable,\n cliff: BigInt(config.cliff),\n creator: config.creator,\n epochInterval: BigInt(config.epoch_interval),\n metadata: config.metadata,\n recipient: config.recipient,\n timeStart: BigInt(config.time_start),\n totalEpoch: BigInt(config.total_epoch),\n },\n status: {\n status: status.status as RawStreamStatusEnum,\n epochCanceled: BigInt(status.epoch_canceled),\n epochClaimed: BigInt(status.epoch_claimed),\n },\n };\n }\n}\n","import { MPayError, MPayErrorCode } from './base';\n\nexport class NotCreatorError extends MPayError {\n constructor() {\n super(MPayErrorCode.NotCreator, 'Connected wallet is not creator');\n }\n}\n","import { MPayError, MPayErrorCode } from './base';\n\nexport class NotRecipientError extends MPayError {\n constructor() {\n super(MPayErrorCode.NotRecipient, 'Connected wallet is not recipient');\n }\n}\n","import { MPayError, JsonObject, MPayErrorCode } from './base';\n\nexport class RpcError extends MPayError {\n constructor(msg: string, context?: JsonObject) {\n super(MPayErrorCode.RpcError, msg, {\n context,\n });\n }\n}\n","import { MPayError, MPayErrorCode } from './base';\n\nexport class StreamNotFoundError extends MPayError {\n constructor(streamId: string) {\n super(MPayErrorCode.StreamNotFound, 'Stream not found', {\n context: {\n streamId,\n },\n });\n }\n}\n","// eslint-disable-next-line no-bitwise\nimport { DateTime, Duration } from 'luxon';\n\n// eslint-disable-next-line no-bitwise\nexport const MAX_U64 = (1n << 64n) - 1n;\n\nexport const TIME_ROUND_UNIT = 1000;\n\n// roundTime round date to seconds\nexport function roundDateTime(date: DateTime | number | bigint) {\n let dateMs: number;\n if (typeof date === 'number') {\n dateMs = date;\n } else if (typeof date === 'bigint') {\n dateMs = Number(date);\n } else {\n dateMs = date.toMillis();\n }\n const roundMs = Math.round(dateMs / TIME_ROUND_UNIT);\n return DateTime.fromMillis(roundMs * TIME_ROUND_UNIT);\n}\n\nexport function roundDuration(duration: Duration | number | bigint) {\n let durationMs: number;\n if (typeof duration === 'number') {\n durationMs = duration;\n } else if (typeof duration === 'bigint') {\n durationMs = Number(duration);\n } else {\n durationMs = duration.toMillis();\n }\n const roundMs = Math.round(durationMs / TIME_ROUND_UNIT);\n return Duration.fromMillis(roundMs * TIME_ROUND_UNIT);\n}\n","import {\n CoinMetadata,\n SuiClient,\n SuiObjectChangeCreated,\n SuiTransactionBlockResponse,\n DevInspectResults,\n} from '@mysten/sui.js/client';\nimport { TransactionBlock } from '@mysten/sui.js/transactions';\nimport { normalizeStructTag, SUI_TYPE_ARG } from '@mysten/sui.js/utils';\nimport { DateTime, Duration } from 'luxon';\n\nimport { CreateStreamHelper } from '../builder/CreateStreamHelper';\nimport { MPayBuilder } from '../builder/MPayBuilder';\nimport { Globals } from '../common';\nimport { InvalidInputError } from '../error/InvalidInputError';\nimport { TransactionFailedError } from '../error/TransactionFailedError';\nimport {\n IMPayHelper,\n CreateStreamInfo,\n PaymentWithFee,\n MPayFees,\n Fraction,\n CalculatedStreamAmount,\n CalculatedTimeline,\n} from '../types/client';\n\n// Minimum time interval is 1 second\nexport const MIN_INTERVAL_MS = 1000;\n\nexport class MPayHelper implements IMPayHelper {\n private readonly coinMetaHelper: CoinMetaHelper;\n\n private readonly createStreamHelper: CreateStreamHelper;\n\n constructor(public readonly globals: Globals) {\n this.coinMetaHelper = new CoinMetaHelper(globals.suiClient);\n this.createStreamHelper = new MPayBuilder(globals).createStreamHelper();\n }\n\n getStreamIdsFromCreateStreamResponse(res: SuiTransactionBlockResponse) {\n if (res.effects?.status.status !== 'success') {\n throw new TransactionFailedError(res.effects?.status.status, res.effects?.status.error);\n }\n return res\n .objectChanges!.filter(\n (change) =>\n change.type === 'created' &&\n change.objectType.startsWith(`${this.globals.envConfig.contract.contractId}::stream::Stream`),\n )\n .map((change) => (change as SuiObjectChangeCreated).objectId);\n }\n\n calculateCreateStreamFees(info: CreateStreamInfo): PaymentWithFee {\n return this.createStreamHelper.calculateCreateStreamFees(info);\n }\n\n feeParams(): MPayFees {\n return this.createStreamHelper.feeParams();\n }\n\n calculateStreamAmount(input: { totalAmount: bigint; steps: bigint; cliff?: Fraction }): CalculatedStreamAmount {\n if (input.steps === 0n) {\n throw new InvalidInputError('Invalid stream steps: 0');\n }\n const cliffFraction = input.cliff\n ? input.cliff\n : {\n numerator: 0n,\n denominator: 100n,\n };\n const cliffAmount = (input.totalAmount * cliffFraction.numerator) / cliffFraction.denominator;\n const amountPerStep = (input.totalAmount - cliffAmount) / input.steps;\n const realTotalAmount = amountPerStep * input.steps + cliffAmount;\n\n const res = {\n realTotalAmount,\n cliffAmount,\n amountPerStep,\n };\n this.validateStreamAmount(res, input.totalAmount);\n return res;\n }\n\n calculateTimelineByInterval(input: { timeStart: DateTime; interval: Duration; steps: bigint }): CalculatedTimeline {\n if (input.steps === 0n) {\n throw new InvalidInputError('Invalid stream steps: 0');\n }\n const timeEnd = input.timeStart.plus(input.interval.toMillis() * Number(input.steps));\n\n const res = {\n timeStart: input.timeStart,\n timeEnd,\n interval: input.interval,\n steps: input.steps,\n };\n this.validateTimeline(res);\n return res;\n }\n\n calculateTimelineByTotalDuration(input: { timeStart: DateTime; total: Duration; steps: bigint }): CalculatedTimeline {\n if (input.steps === 0n) {\n throw new InvalidInputError('Invalid stream steps: 0');\n }\n const intervalMilli = BigInt(input.total.toMillis()) / input.steps;\n const timeEnd = input.timeStart.plus(Duration.fromMillis(Number(intervalMilli * input.steps)));\n const res = {\n timeStart: input.timeStart,\n timeEnd,\n interval: Duration.fromMillis(Number(intervalMilli)),\n steps: input.steps,\n };\n this.validateTimeline(res);\n return res;\n }\n\n async getBalance(address: string, coinType?: string | null) {\n const balance = await this.globals.suiClient.getBalance({\n owner: address,\n coinType,\n });\n const coinMeta = await this.getCoinMeta(coinType);\n return {\n ...balance,\n coinType: normalizeStructTag(balance.coinType),\n coinMeta,\n };\n }\n\n async getAllBalance(address: string) {\n const allBalance = await this.globals.suiClient.getAllBalances({\n owner: address,\n });\n const coinMetas = await Promise.all(allBalance.map((bal) => this.getCoinMeta(bal.coinType)));\n return allBalance.map((bal, i) => ({\n ...bal,\n coinType: normalizeStructTag(bal.coinType),\n coinMeta: coinMetas[i],\n }));\n }\n\n async getCoinMeta(coinType: string | null | undefined) {\n return this.coinMetaHelper.getCoinMeta(coinType);\n }\n\n async simulateTransactionBlock(txb: TransactionBlock): Promise<DevInspectResults> {\n return this.globals.suiClient.devInspectTransactionBlock({\n transactionBlock: txb,\n sender: await this.globals.wallet.address(),\n });\n }\n\n private validateStreamAmount(val: CalculatedStreamAmount, originTotalAmount: bigint) {\n if (val.amountPerStep === 0n) {\n throw new InvalidInputError('Stream amount too small', 'totalAmount', originTotalAmount);\n }\n if (val.cliffAmount > val.realTotalAmount) {\n throw new InvalidInputError('Invalid cliff settings');\n }\n }\n\n private validateTimeline(val: CalculatedTimeline) {\n if (val.interval.toMillis() < MIN_INTERVAL_MS) {\n throw new InvalidInputError('Interval shall be at least 1 second', 'interval', val.interval);\n }\n }\n}\n\nexport class CoinMetaHelper {\n private coinMetaReg: Map<string, CoinMetadata>;\n\n constructor(private readonly suiClient: SuiClient) {\n this.coinMetaReg = new Map();\n }\n\n async getCoinMeta(coinType: string | null | undefined): Promise<CoinMetadata | undefined> {\n const normalized = normalizeStructTag(coinType || SUI_TYPE_ARG);\n if (this.coinMetaReg.has(normalized)) {\n return this.coinMetaReg.get(normalized);\n }\n const meta = await this.queryCoinMeta(normalized);\n if (meta) {\n this.coinMetaReg.set(normalized, meta);\n }\n return meta;\n }\n\n private async queryCoinMeta(coinType: string): Promise<CoinMetadata | undefined> {\n const res = await this.suiClient.getCoinMetadata({ coinType });\n return res || undefined;\n }\n}\n","import { MPayError, MPayErrorCode } from './base';\n\nexport class TransactionFailedError extends MPayError {\n constructor(status: string | undefined, msg: string | undefined) {\n super(MPayErrorCode.TransactionFailed, `Transaction failed: ${msg}`, {\n context: {\n status,\n msg,\n },\n });\n }\n}\n","import { SuiObjectResponse } from '@mysten/sui.js/client';\nimport { normalizeStructTag, normalizeSuiAddress } from '@mysten/sui.js/utils';\nimport { DateTime } from 'luxon';\n\nimport { Stream } from './Stream';\nimport { StreamGroup } from './StreamGroup';\nimport { Globals } from '../common';\nimport { InvalidInputError } from '../error/InvalidInputError';\nimport { SanityError } from '../error/SanityError';\nimport { SuiIterator } from '../sui/iterator/iterator';\nimport { ObjectBatchIterator, ListOidIterator } from '../sui/iterator/object';\nimport {\n StreamRef,\n BackendIncomingStreamFilterOptions,\n BackendOutgoingStreamFilterOptions,\n StreamFilterStatus,\n} from '../types/backend';\nimport { IPagedStreamListIterator, IncomingStreamQuery, OutgoingStreamQuery } from '../types/client';\nimport { IStream, IStreamGroup, StreamStatus } from '../types/stream';\n\nexport class PagedStreamListIterator implements IPagedStreamListIterator {\n private constructor(\n public readonly it: StreamListIterator,\n public readonly pageSize: number,\n ) {}\n\n static async newIncoming(input: {\n globals: Globals;\n query?: IncomingStreamQuery;\n pageSize: number;\n }): Promise<PagedStreamListIterator> {\n const it = await StreamListIterator.newIncoming(input);\n return new PagedStreamListIterator(it, input.pageSize);\n }\n\n static async newOutgoing(input: {\n globals: Globals;\n query?: OutgoingStreamQuery;\n pageSize: number;\n }): Promise<PagedStreamListIterator> {\n const it = await StreamListIterator.newOutgoing(input);\n return new PagedStreamListIterator(it, input.pageSize);\n }\n\n async hasNext() {\n return this.it.hasNext();\n }\n\n async next(): Promise<(IStream | IStreamGroup)[]> {\n const res: (IStream | IStreamGroup)[] = [];\n while (res.length < this.pageSize && (await this.it.hasNext())) {\n res.push(await this.it.next());\n }\n return res;\n }\n}\n\nexport class StreamListIterator implements SuiIterator<IStream | IStreamGroup> {\n cachedNext: IStream | IStreamGroup | undefined | null;\n\n private constructor(private readonly requester: StreamListRequester) {}\n\n static async newIncoming(input: { globals: Globals; query?: IncomingStreamQuery }) {\n const requester = await StreamListRequester.newIncomingQuery(input);\n return new StreamListIterator(requester);\n }\n\n static async newOutgoing(input: { globals: Globals; query?: OutgoingStreamQuery }) {\n const requester = await StreamListRequester.newOutgoingQuery(input);\n return new StreamListIterator(requester);\n }\n\n async hasNext(): Promise<boolean> {\n if (this.cachedNext === undefined) {\n this.cachedNext = await this.requester.doNextRequest();\n }\n return this.cachedNext !== null;\n }\n\n async next(): Promise<IStream | IStreamGroup> {\n if (this.cachedNext === undefined) {\n const res = await this.requester.doNextRequest();\n if (res === null) {\n throw new SanityError('No more results');\n }\n return res;\n }\n const res = this.cachedNext;\n this.cachedNext = undefined;\n if (res === null) {\n throw new SanityError('No more results');\n }\n return res as IStream | IStreamGroup;\n }\n}\n\nexport class StreamListRequester {\n public current = 0;\n\n public objectIter: ObjectBatchIterator;\n\n private constructor(\n public readonly globals: Globals,\n public readonly recipient: string,\n public readonly groupRefs: StreamRef[][],\n public readonly query?: IncomingStreamQuery | OutgoingStreamQuery,\n ) {\n this.current = 0;\n const oidIter = new ListOidIterator(groupRefs.flat().map((ref) => ref.streamId));\n this.objectIter = new ObjectBatchIterator(globals.suiClient, oidIter);\n }\n\n static async newIncomingQuery(input: { globals: Globals; query?: IncomingStreamQuery }) {\n const backendQuery = convertToIncomingBackendQuery(input.query);\n const recipient = await input.globals.walletAddress();\n const refs = await input.globals.backend.getIncomingStreams(recipient, backendQuery);\n const filtered = refs.filter((ref: any) => normalizeSuiAddress(ref.recipient) === normalizeSuiAddress(recipient));\n const groupedRefs = groupAndSortRefs(filtered);\n\n return new StreamListRequester(input.globals, recipient, groupedRefs, input.query);\n }\n\n static async newOutgoingQuery(input: { globals: Globals; query?: OutgoingStreamQuery }) {\n const backendQuery = convertToOutgoingBackendQuery(input.query);\n const sender = await input.globals.walletAddress();\n const refs = await input.globals.backend.getOutgoingStreams(sender, backendQuery);\n const groupedRefs = groupAndSortRefs(refs);\n return new StreamListRequester(input.globals, sender, groupedRefs, input.query);\n }\n\n async doNextRequest(): Promise<IStream | IStreamGroup | null> {\n if (this.current >= this.groupRefs.length) {\n return null;\n }\n const stRefs = this.groupRefs[this.current];\n if (stRefs.length === 1) {\n const stream = await getStreamFromIterator(this.globals, stRefs[0].streamId, this.objectIter);\n this.current++;\n return isStreamOfQuery(stream, this.query) ? stream : this.doNextRequest();\n }\n if (stRefs.length > 1) {\n const sg = await getStreamGroupFromIterator(\n this.globals,\n stRefs.map((ref) => ref.streamId),\n this.objectIter,\n );\n this.current++;\n return isStreamGroupOfQuery(sg, this.query) ? sg : this.doNextRequest();\n }\n throw new SanityError('Stream group with no stream');\n }\n}\n\nexport function groupAndSortRefs(refs: StreamRef[]) {\n const m = new Map<string, StreamRef[]>();\n refs.forEach((ref) => {\n const groupList = m.get(ref.groupId);\n if (groupList) {\n groupList.push(ref);\n m.set(ref.groupId, groupList);\n } else {\n m.set(ref.groupId, [ref]);\n }\n });\n return Array.from(m.values()).sort(\n (gl1, gl2) => DateTime.fromISO(gl2[0].createDate).toMillis() - DateTime.fromISO(gl1[0].createDate).toMillis(),\n );\n}\n\nfunction isStreamOfQuery(stream: IStream, query: IncomingStreamQuery | OutgoingStreamQuery | undefined) {\n if (query === undefined) {\n return true;\n }\n const isStatus = isStreamOfStatus(stream, query.status);\n if (query && 'claimable' in query && query.claimable !== undefined) {\n const isClaimable = query.claimable ? stream.progress.claimable !== 0n : stream.progress.claimable === 0n;\n return isStatus && isClaimable;\n }\n return isStatus;\n}\n\nfunction isStreamOfStatus(stream: IStream, filter: StreamStatus | StreamStatus[] | undefined): boolean {\n if (filter === undefined) {\n return true;\n }\n if (!Array.isArray(filter)) {\n return stream.progress.status === filter;\n }\n return filter.includes(stream.progress.status);\n}\n\nfunction isStreamGroupOfQuery(sg: IStreamGroup, query: IncomingStreamQuery | OutgoingStreamQuery | undefined): boolean {\n if (!query) {\n return true;\n }\n let isStatus = false;\n sg.streams.forEach((stream) => {\n if (isStreamOfQuery(stream, query)) {\n isStatus = true;\n }\n });\n return isStatus;\n}\n\nasync function getStreamFromIterator(globals: Globals, streamId: string, it: ObjectBatchIterator) {\n const data = await getStreamObjectResponseFromIter(it, streamId);\n return Stream.fromObjectData(globals, streamId, data);\n}\n\nasync function getStreamGroupFromIterator(globals: Globals, streamIds: string[], it: ObjectBatchIterator) {\n const objResponses: SuiObjectResponse[] = [];\n while (objResponses.length < streamIds.length) {\n const data = await getStreamObjectResponseFromIter(it, streamIds[objResponses.length]);\n objResponses.push(data);\n }\n return StreamGroup.newFromObjectResponse(globals, streamIds, objResponses);\n}\n\nasync function getStreamObjectResponseFromIter(it: ObjectBatchIterator, streamId: string) {\n if (!(await it.hasNext())) {\n throw new SanityError('object iterator has been consumed');\n }\n const data = await it.next();\n if (!data || data.error || data.data === undefined || data.data === null) {\n throw new SanityError(`object iterator undefined response`, {\n cause: data?.error,\n });\n }\n if (data?.data?.objectId !== streamId) {\n throw new SanityError('stream id not aligned');\n }\n return data;\n}\n\n// Convert IncomingStreamQuery to BackendIncomingStreamFilterOptions\nfunction convertToIncomingBackendQuery(query?: IncomingStreamQuery): BackendIncomingStreamFilterOptions {\n return {\n status: convertStreamStatus(query?.status),\n coinType: normalizeCoinTypeFilter(query?.coinType),\n sender: normalizeAddressFilter(query?.sender),\n };\n}\n\nfunction convertToOutgoingBackendQuery(query?: OutgoingStreamQuery): BackendOutgoingStreamFilterOptions {\n return {\n status: convertStreamStatus(query?.status),\n coinType: normalizeCoinTypeFilter(query?.coinType),\n recipient: normalizeAddressFilter(query?.recipient),\n };\n}\n\nexport function convertStreamStatus(status: undefined | StreamStatus | StreamStatus[]): StreamFilterStatus {\n if (status === undefined || status.length === 0) {\n return 'all';\n }\n if (!Array.isArray(status)) {\n return convertStreamStatusSingle(status);\n }\n return status.reduce((res: StreamFilterStatus | undefined, st) => {\n const sts = convertStreamStatus(st);\n if (!res) {\n return sts;\n }\n if (res === sts) {\n return sts;\n }\n return 'all';\n }, undefined) as StreamFilterStatus;\n}\n\nfunction convertStreamStatusSingle(status: StreamStatus): StreamFilterStatus {\n switch (status) {\n case 'STREAMING':\n case 'STREAMED':\n case 'CANCELED':\n return 'active';\n case 'COMPLETED':\n case 'SETTLED':\n return 'inactive';\n default:\n throw new InvalidInputError('Unknown stream filtered status');\n }\n}\n\nfunction normalizeCoinTypeFilter(coinType: string | string[] | undefined) {\n if (!coinType) {\n return undefined;\n }\n if (!Array.isArray(coinType)) {\n return normalizeStructTag(coinType);\n }\n return coinType.length !== 0 ? coinType.map((ct) => normalizeStructTag(ct)) : undefined;\n}\n\nfunction normalizeAddressFilter(address: string | string[] | undefined) {\n if (!address) {\n return undefined;\n }\n if (!Array.isArray(address)) {\n return normalizeSuiAddress(address);\n }\n return address.length !== 0 ? address.map((addr) => normalizeSuiAddress(addr)) : undefined;\n}\n","import { MPayError, JsonObject, MPayErrorCode } from './base';\n\nexport class InvalidStreamGroupError extends MPayError {\n constructor(msg: string, context?: JsonObject) {\n super(MPayErrorCode.InvalidStreamGroup, `Invalid stream group: ${msg}`, { context });\n }\n}\n","import { SuiClient, SuiObjectDataOptions, SuiObjectResponse } from '@mysten/sui.js/client';\n\nimport { SuiIterator, getAllFromIterator, EntryIterator } from './iterator';\nimport { Requester, PagedData } from './requester';\n\nexport type ObjectFilter = (objRes: SuiObjectResponse) => boolean;\n\nexport const REQUEST_PAGE_SIZE = 25;\n\n// OidIter is the iterator to give the list of object ids\nexport type OidIter = SuiIterator<string>;\nexport interface BatchObjectOptions {\n filter?: ObjectFilter;\n pageSize?: number;\n objectOptions?: SuiObjectDataOptions;\n}\n\n// getObjectsById get the list of objects by id.\n// Compared with the multiGetObject method defined by SUI, this method will do the pagination\n// for get object requests.\nexport async function getObjectsById(\n suiClient: SuiClient,\n ids: string[],\n options?: BatchObjectOptions,\n): Promise<(SuiObjectResponse | undefined)[]> {\n const oidIter = new ListOidIterator(ids);\n const iter = new ObjectBatchIterator(suiClient, oidIter, options);\n return (await getAllFromIterator(iter)) as SuiObjectResponse[];\n}\n\n// ListOidIterator is the iterator that iterate through a list of ids.\n// This iterator shall be used when the number requested objects is big\n// which is inappropriate to fit the requested objects into a single\n// request.\nexport class ListOidIterator implements OidIter {\n cursor: number;\n\n constructor(public readonly ids: string[]) {\n this.cursor = -1;\n }\n\n async hasNext(): Promise<boolean> {\n return this.cursor < this.ids.length - 1;\n }\n\n async next(): Promise<string> {\n this.cursor += 1;\n if (this.cursor >= this.ids.length) {\n throw new Error('invalid iterator implementation'); // Shall be unreachable\n }\n return this.ids[this.cursor];\n }\n}\n\nexport class ObjectBatchIterator extends EntryIterator<SuiObjectResponse> {\n constructor(\n public readonly suiClient: SuiClient,\n public readonly idIter: OidIter,\n public readonly options?: BatchObjectOptions,\n ) {\n super(new ObjectBatchRequester(suiClient, idIter, options));\n }\n}\n\n// TODO: Unit test this class\nexport class ObjectBatchRequester implements Requester<SuiObjectResponse> {\n filter: ObjectFilter | undefined;\n\n pageSize: number;\n\n objectOptions: SuiObjectDataOptions;\n\n constructor(\n public readonly suiClient: SuiClient,\n public readonly stringIter: OidIter,\n public options?: BatchObjectOptions,\n ) {\n this.filter = options?.filter;\n this.pageSize = options?.pageSize || REQUEST_PAGE_SIZE;\n this.objectOptions = options?.objectOptions || {\n showType: true,\n showContent: true,\n };\n }\n\n async doNextRequest(): Promise<PagedData<SuiObjectResponse>> {\n const requestPage: string[] = [];\n while (requestPage.length < this.pageSize) {\n const hasNext = await this.stringIter.hasNext();\n if (!hasNext) {\n break;\n }\n const objId = await this.stringIter.next();\n if (objId) {\n requestPage.push(objId);\n }\n }\n const res = await this.suiClient.multiGetObjects({\n ids: requestPage,\n options: this.objectOptions,\n });\n let filtered: SuiObjectResponse[];\n if (this.filter) {\n const { filter } = this;\n filtered = res.filter((r: SuiObjectResponse) => filter?.(r));\n } else {\n filtered = res;\n }\n return {\n data: filtered,\n hasNext: await this.stringIter.hasNext(),\n };\n }\n}\n","import { SuiObjectResponse } from '@mysten/sui.js/client';\n\nimport { Stream } from './Stream';\nimport { Globals } from '../common';\nimport { InvalidInputError } from '../error/InvalidInputError';\nimport { InvalidStreamGroupError } from '../error/InvalidStreamGroupError';\nimport { SanityError } from '../error/SanityError';\nimport { getObjectsById } from '../sui/iterator/object';\nimport { StreamEvent } from '../types/events';\nimport { PaginationOptions, Paginated } from '../types/pagination';\nimport { IStreamGroup, StreamGroupInfo, StreamGroupProgress, StreamGroupCommonInfo } from '../types/stream';\n\nexport class StreamGroup implements IStreamGroup {\n public readonly type = 'StreamGroup';\n\n constructor(\n public readonly globals: Globals,\n public readonly streams: Stream[],\n ) {\n if (streams.length === 0) {\n throw new InvalidStreamGroupError('stream size 0');\n }\n const gids = streams.map((st) => st.groupId);\n const set = new Set(gids);\n if (set.size !== 1) {\n throw new InvalidInputError('Stream does not have same group ID');\n }\n }\n\n static async new(globals: Globals, ids: string[]) {\n const streamObjs = await getObjectsById(globals.suiClient, ids);\n streamObjs.forEach((obj) => {\n if (!obj) {\n throw new SanityError('stream group object data undefined');\n }\n });\n return StreamGroup.newFromObjectResponse(globals, ids, streamObjs as SuiObjectResponse[]);\n }\n\n static async newFromObjectResponse(globals: Globals, ids: string[], responses: SuiObjectResponse[]) {\n const streams = await StreamGroup.parseGroupStreams(globals, ids, responses);\n return new StreamGroup(globals, streams);\n }\n\n static checkStreamGroup(streams: Stream[]) {\n const commonInfos = streams.map((stream) => stream.groupCommonInfo);\n const expInfo = commonInfos[0];\n let isEqual = true;\n commonInfos.forEach((info) => {\n if (!isEqualStreamGroupCommonInfo(expInfo, info)) {\n isEqual = false;\n }\n });\n return isEqual;\n }\n\n async refresh() {\n const streamObjs = await getObjectsById(\n this.globals.suiClient,\n this.streams.map((stream) => stream.streamId),\n );\n this.streams.forEach((stream, i) => {\n stream.refreshWithData(streamObjs[i] as SuiObjectResponse);\n });\n }\n\n get groupId() {\n return this.streams[0].groupId;\n }\n\n get creator() {\n return this.streams[0].creator;\n }\n\n get info(): StreamGroupInfo {\n return {\n groupId: this.groupId,\n streamIds: this.streams.map((st) => st.streamId),\n progress: this.progress,\n\n name: this.streams[0].name,\n creator: this.creator,\n coinType: this.streams[0].coinType,\n totalAmount: this.streams.reduce((sum, st) => sum + st.totalAmount, 0n),\n start: this.streams[0].timeStart,\n end: this.streams[0].timeEnd,\n cancelable: this.streams[0].cancelable,\n cliffAmount: this.streams.reduce((sum, st) => sum + st.cliff, 0n),\n duration: this.streams[0].duration,\n interval: this.streams[0].interval,\n steps: this.streams[0].totalSteps,\n nextReleaseAmount: this.streams.reduce((sum, st) => {\n if (st.nextReleaseAmount === null) {\n return sum;\n }\n return sum + st.nextReleaseAmount;\n }, 0n),\n nextReleaseDate: this.streams[0].nextReleaseDate,\n };\n }\n\n get progress(): StreamGroupProgress {\n return {\n total: this.streams.reduce((sum, st) => sum + st.totalAmount, 0n),\n streamed: this.streams.reduce((sum, st) => sum + st.streamedAmount, 0n),\n claimed: this.streams.reduce((sum, st) => sum + st.claimedAmount, 0n),\n claimable: this.streams.reduce((sum, st) => sum + st.claimable, 0n),\n canceled: this.streams.reduce((sum, st) => sum + st.canceledAmount, 0n),\n };\n }\n\n async historyEvents(pagination?: PaginationOptions): Promise<Paginated<StreamEvent>> {\n return this.globals.backend.getStreamHistory({\n groupId: this.groupId,\n pagination,\n });\n }\n\n private static async parseGroupStreams(globals: Globals, ids: string[], responses: SuiObjectResponse[]) {\n const streams = responses\n .map((obj, i) => Stream.fromObjectData(globals, ids[i], obj))\n .filter((stream) => !!stream) as Stream[];\n\n if (new Set(streams.map((st) => st.groupId)).size !== 1) {\n throw new InvalidStreamGroupError('Not same group ID');\n }\n if (!this.checkStreamGroup(streams)) {\n throw new InvalidStreamGroupError('Not same stream settings');\n }\n return streams;\n }\n}\n\nfunction isEqualStreamGroupCommonInfo(info1: StreamGroupCommonInfo, info2: StreamGroupCommonInfo): boolean {\n return (\n info1.name === info2.name &&\n info1.groupId === info2.groupId &&\n info1.creator === info2.creator &&\n info1.start.toMillis() === info2.start.toMillis() &&\n info1.interval.toMillis() === info2.interval.toMillis() &&\n info1.steps === info2.steps &&\n info1.cancelable === info2.cancelable\n );\n}\n","import { WalletAccount } from '@mysten/wallet-standard';\n\nimport { BaseIntentionLegacy } from '@/apps/interface/sui-js';\nimport { SuiNetworks } from '@/types';\n\nimport { Env } from './common';\nimport { MPayClient, MSafeSingleWallet } from './stream/client';\n\nexport abstract class StreamIntention<T> extends BaseIntentionLegacy<T> {\n public application = 'mpay';\n\n getClient(network: SuiNetworks, account: WalletAccount): MPayClient {\n const mpayClient = new MPayClient(network === 'sui:mainnet' ? Env.prod : Env.dev);\n mpayClient.connectSingleWallet(new MSafeSingleWallet(account));\n return mpayClient;\n }\n}\n","import { ClaimByProxyStreamIntentionData, TransactionType } from '@msafe/sui3-utils';\nimport { SuiClient } from '@mysten/sui.js/client';\nimport { TransactionBlock } from '@mysten/sui.js/transactions';\nimport { WalletAccount } from '@mysten/wallet-standard';\n\nimport { SuiNetworks } from '@/types';\n\nimport { StreamIntention } from './intention';\nimport { StreamTransactionType } from './types/decode';\n\nexport class ClaimByProxyStreamIntention extends StreamIntention<ClaimByProxyStreamIntentionData> {\n txType = TransactionType.Stream;\n\n txSubType = StreamTransactionType.CLAIM_BY_PROXY;\n\n constructor(public readonly data: ClaimByProxyStreamIntentionData) {\n super(data);\n }\n\n async build(input: {\n network: SuiNetworks;\n suiClient: SuiClient;\n account: WalletAccount;\n }): Promise<TransactionBlock> {\n const { network, account } = input;\n const mpayClient = this.getClient(network, account);\n const stream = await mpayClient.getStream(this.data.streamId);\n return stream.claimByProxy();\n }\n}\n","import { ClaimStreamIntentionData, TransactionType } from '@msafe/sui3-utils';\nimport { SuiClient } from '@mysten/sui.js/client';\nimport { TransactionBlock } from '@mysten/sui.js/transactions';\nimport { WalletAccount } from '@mysten/wallet-standard';\n\nimport { SuiNetworks } from '@/types';\n\nimport { StreamIntention } from './intention';\nimport { StreamTransactionType } from './types/decode';\n\nexport class ClaimStreamIntention extends StreamIntention<ClaimStreamIntentionData> {\n txType = TransactionType.Stream;\n\n txSubType = StreamTransactionType.CLAIM;\n\n constructor(public readonly data: ClaimStreamIntentionData) {\n super(data);\n }\n\n async build(input: {\n network: SuiNetworks;\n suiClient: SuiClient;\n account: WalletAccount;\n }): Promise<TransactionBlock> {\n const { network, account } = input;\n const mpayClient = this.getClient(network, account);\n const stream = await mpayClient.getStream(this.data.streamId);\n return stream.claim();\n }\n}\n","import { CreateStreamIntentionData, TransactionType } from '@msafe/sui3-utils';\nimport { SuiClient } from '@mysten/sui.js/client';\nimport { TransactionBlock } from '@mysten/sui.js/transactions';\nimport { WalletAccount } from '@mysten/wallet-standard';\n\nimport { SuiNetworks } from '@/types';\n\nimport { StreamIntention } from './intention';\nimport { StreamTransactionType } from './types/decode';\n\nexport class CreateStreamIntention extends StreamIntention<CreateStreamIntentionData> {\n txType = TransactionType.Stream;\n\n txSubType = StreamTransactionType.CREATE_STREAM;\n\n constructor(public readonly data: CreateStreamIntentionData) {\n super(data);\n }\n\n async build(input: {\n network: SuiNetworks;\n suiClient: SuiClient;\n account: WalletAccount;\n }): Promise<TransactionBlock> {\n const { network, account } = input;\n const mpayClient = this.getClient(network, account);\n return mpayClient.createStream(this.data);\n }\n}\n","// Helper class to decode move call\nimport { bcs } from '@mysten/sui.js/bcs';\nimport { MoveCallTransaction } from '@mysten/sui.js/dist/cjs/transactions';\nimport { TransactionBlock, TransactionBlockInput } from '@mysten/sui.js/transactions';\nimport { normalizeStructTag, normalizeSuiAddress } from '@mysten/sui.js/utils';\n\nexport class MoveCallHelper {\n constructor(\n public readonly moveCall: MoveCallTransaction,\n public readonly txb: TransactionBlock,\n ) {}\n\n decodeSharedObjectId(argIndex: number) {\n const input = this.getInputParam(argIndex);\n return MoveCallHelper.getSharedObjectId(input);\n }\n\n decodeOwnedObjectId(argIndex: number) {\n const input = this.getInputParam(argIndex);\n return MoveCallHelper.getOwnedObjectId(input);\n }\n\n decodeInputU64(argIndex: number) {\n const strVal = this.decodePureArg<string>(argIndex, 'u64');\n return BigInt(strVal);\n }\n\n decodeInputAddress(argIndex: number) {\n const input = this.decodePureArg<string>(argIndex, 'address');\n return normalizeSuiAddress(input);\n }\n\n decodeInputString(argIndex: number) {\n return this.decodePureArg<string>(argIndex, 'string');\n }\n\n decodeInputBool(argIndex: number) {\n return this.decodePureArg<boolean>(argIndex, 'bool');\n }\n\n decodePureArg<T>(argIndex: number, bcsType: string) {\n const input = this.getInputParam(argIndex);\n return MoveCallHelper.getPureInputValue<T>(input, bcsType);\n }\n\n getInputParam(argIndex: number) {\n const arg = this.moveCall.arguments[argIndex];\n if (arg.kind !== 'Input') {\n throw new Error('not input type');\n }\n return this.txb.blockData.inputs[arg.index];\n }\n\n static getPureInputValue<T>(input: TransactionBlockInput, bcsType: string) {\n if (input.type !== 'pure') {\n throw new Error('not pure argument');\n }\n if (typeof input.value === 'object' && 'Pure' in input.value) {\n const bcsNums = input.value.Pure;\n return bcs.de(bcsType, new Uint8Array(bcsNums)) as T;\n }\n return input.value as T;\n }\n\n static getOwnedObjectId(input: TransactionBlockInput) {\n if (input.type !== 'object') {\n throw new Error(`not object argument: ${JSON.stringify(input)}`);\n }\n if (typeof input.value === 'object') {\n if (!('Object' in input.value) || !('ImmOrOwned' in input.value.Object)) {\n throw new Error('not ImmOrOwned');\n }\n return normalizeSuiAddress(input.value.Object.ImmOrOwned.objectId as string);\n }\n return normalizeSuiAddress(input.value as string);\n }\n\n static getSharedObjectId(input: TransactionBlockInput) {\n if (input.type !== 'object') {\n throw new Error(`not object argument: ${JSON.stringify(input)}`);\n }\n if (typeof input.value !== 'object') {\n return normalizeSuiAddress(input.value as string);\n }\n if (!('Object' in input.value) || !('Shared' in input.value.Object)) {\n throw new Error('not Shared');\n }\n return normalizeSuiAddress(input.value.Object.Shared.objectId as string);\n }\n\n static getPureInput<T>(input: TransactionBlockInput, bcsType: string) {\n if (input.type !== 'pure') {\n throw new Error('not pure argument');\n }\n if (typeof input.value !== 'object') {\n return input.value as T;\n }\n if (!('Pure' in input.value)) {\n throw new Error('Pure not in value');\n }\n const bcsVal = input.value.Pure;\n return bcs.de(bcsType, new Uint8Array(bcsVal)) as T;\n }\n\n typeArg(index: number) {\n return normalizeStructTag(this.moveCall.typeArguments[index]);\n }\n\n txArg(index: number) {\n return this.moveCall.arguments[index];\n }\n}\n","import { MoveCallTransaction } from '@mysten/sui.js/dist/cjs/transactions';\nimport { TransactionArgument, TransactionBlock } from '@mysten/sui.js/transactions';\n\nimport { CreateStreamHelper } from '../builder/CreateStreamHelper';\nimport { Globals } from '../common';\nimport { FeeContract } from '../contract/FeeContract';\nimport { StreamContract } from '../contract/StreamContract';\nimport { InvalidInputError } from '../error/InvalidInputError';\nimport { SanityError } from '../error/SanityError';\nimport { decodeMetadata } from '../stream/metadata';\nimport { isSameTarget } from '../sui/utils';\nimport { CreateStreamInfo, RecipientWithAmount } from '../types/client';\nimport { DecodedCreateStream, StreamTransactionType } from '../types/decode';\nimport { MoveCallHelper } from './moveCall';\n\nexport class CreateStreamDecodeHelper {\n constructor(\n public readonly globals: Globals,\n public readonly txb: TransactionBlock,\n ) {}\n\n decode(): DecodedCreateStream {\n const streamInfo = this.decodeCreateStreamInfo();\n const fees = this.createStreamHelper().calculateCreateStreamFees(streamInfo);\n return {\n type: StreamTransactionType.CREATE_STREAM,\n info: streamInfo,\n fees,\n };\n }\n\n private decodeCreateStreamInfo(): CreateStreamInfo {\n const moveCalls = this.createStreamTransactions();\n const infos = moveCalls.map((moveCall) => this.getCreationInfoFromMoveCall(moveCall));\n return this.aggregateGroupStreamInfo(infos);\n }\n\n private createStreamTransactions(): MoveCallHelper[] {\n const txs = this.transactions.filter(\n (tx) => tx.kind === 'MoveCall' && isSameTarget(tx.target, this.contract.createStreamTarget),\n ) as MoveCallTransaction[];\n if (txs.length === 0) {\n throw new SanityError('No create stream transactions');\n }\n return txs.map((tx) => new MoveCallHelper(tx, this.txb));\n }\n\n private getCreationInfoFromMoveCall(moveCall: MoveCallHelper): SingleStreamCreationInfo {\n const metadata = moveCall.decodeInputString(4);\n const { name, groupId } = decodeMetadata(metadata);\n\n const recipient = moveCall.decodeInputAddress(5);\n const timeStart = moveCall.decodeInputU64(6);\n const cliff = moveCall.decodeInputU64(7);\n const epochInterval = moveCall.decodeInputU64(8);\n const totalEpoch = moveCall.decodeInputU64(9);\n const amountPerEpoch = moveCall.decodeInputU64(10);\n const cancelable = moveCall.decodeInputBool(11);\n const coinType = moveCall.typeArg(0);\n\n return {\n name,\n groupId,\n recipient,\n timeStart,\n cliff,\n epochInterval,\n totalEpoch,\n amountPerEpoch,\n cancelable,\n coinType,\n };\n }\n\n private aggregateGroupStreamInfo(infos: SingleStreamCreationInfo[]): CreateStreamInfo {\n const commonInfoSet = new Set(\n infos.map((info) =>\n JSON.stringify({\n name: info.name,\n groupId: info.groupId,\n timeStart: String(info.timeStart),\n epochInterval: String(info.epochInterval),\n totalEpoch: String(info.totalEpoch),\n cancelable: info.cancelable,\n coinType: info.coinType,\n }),\n ),\n );\n if (commonInfoSet.size !== 1) {\n throw new InvalidInputError('Stream group not have common info');\n }\n const recipients: RecipientWithAmount[] = infos.map((info) => ({\n address: info.recipient,\n amountPerStep: info.amountPerEpoch,\n cliffAmount: info.cliff,\n }));\n return {\n name: infos[0].name,\n coinType: infos[0].coinType,\n recipients,\n interval: infos[0].epochInterval,\n steps: infos[0].totalEpoch,\n startTimeMs: infos[0].timeStart,\n cancelable: infos[0].cancelable,\n };\n }\n\n private mergeCoinTransactions() {\n return this.transactions.filter((tx) => tx.kind === 'MergeCoins');\n }\n\n private get transactions() {\n return this.txb.blockData.transactions;\n }\n\n private get contract() {\n return new StreamContract(this.globals.envConfig.contract, this.globals);\n }\n\n private get feeContract() {\n return new FeeContract(this.globals.envConfig.contract, this.globals);\n }\n\n private createStreamHelper() {\n return new CreateStreamHelper(this.globals, this.feeContract, this.contract);\n }\n\n private getInputArg(arg: TransactionArgument) {\n if (arg.kind !== 'Input') {\n throw new Error('not input type');\n }\n return 'value' in arg ? arg : this.txb.blockData.inputs[arg.index];\n }\n}\n\ninterface SingleStreamCreationInfo {\n name: string;\n groupId: string;\n recipient: string;\n timeStart: bigint;\n cliff: bigint;\n epochInterval: bigint;\n totalEpoch: bigint;\n amountPerEpoch: bigint;\n cancelable: boolean;\n coinType: string;\n}\n","import { MoveCallTransaction } from '@mysten/sui.js/dist/cjs/transactions';\nimport { TransactionBlock } from '@mysten/sui.js/transactions';\n\nimport { CreateStreamDecodeHelper } from './create';\nimport { MoveCallHelper } from './moveCall';\nimport { Globals } from '../common';\nimport { StreamContract } from '../contract/StreamContract';\nimport { isSameTarget } from '../sui/utils';\nimport {\n DecodedCancelStream,\n DecodedClaimByProxy,\n DecodedClaimStream,\n DecodedCreateStream,\n DecodedSetAutoClaim,\n StreamDecodedTransaction,\n StreamTransactionType,\n} from '../types/decode';\n\nexport class StreamTransactionDecoder {\n static decodeTransaction(globals: Globals, txb: TransactionBlock): StreamDecodedTransaction {\n const helper = new DecodeHelper(globals, txb);\n return helper.decode();\n }\n}\n\nexport class DecodeHelper {\n private readonly contract: StreamContract;\n\n constructor(\n public readonly globals: Globals,\n public readonly txb: TransactionBlock,\n ) {\n this.contract = new StreamContract(globals.envConfig.contract, globals);\n }\n\n decode(): StreamDecodedTransaction {\n if (this.isCreateStreamTransaction()) {\n return this.decodeCreateStreamTransaction();\n }\n if (this.isClaimByProxyTransaction()) {\n return this.decodeClaimByProxyTransaction();\n }\n if (this.isSetAutoClaimTransaction()) {\n return this.decodeSetAutoClaimTransaction();\n }\n if (this.isCancelStreamTransaction()) {\n return this.decodeCancelStreamTransaction();\n }\n if (this.isClaimStreamTransaction()) {\n return this.decodeClaimTransaction();\n }\n throw new Error('Unknown stream transaction type');\n }\n\n private get transactions() {\n return this.txb.blockData.transactions;\n }\n\n private isCreateStreamTransaction() {\n const createStreamIndex = this.transactions.findIndex(\n (tx) => tx.kind === 'MoveCall' && isSameTarget(tx.target, this.contract.createStreamTarget),\n );\n return createStreamIndex !== -1;\n }\n\n private isSetAutoClaimTransaction() {\n return (\n this.transactions.length === 1 &&\n this.transactions[0].kind === 'MoveCall' &&\n isSameTarget(this.transactions[0].target, this.contract.setAutoClaimTarget)\n );\n }\n\n private isCancelStreamTransaction() {\n return (\n this.transactions.length === 1 &&\n this.transactions[0].kind === 'MoveCall' &&\n isSameTarget(this.transactions[0].target, this.contract.cancelStreamTarget)\n );\n }\n\n private isClaimStreamTransaction(): boolean {\n return (\n this.transactions.length === 1 &&\n this.transactions[0].kind === 'MoveCall' &&\n isSameTarget(this.transactions[0].target, this.contract.claimStreamTarget)\n );\n }\n\n private isClaimByProxyTransaction(): boolean {\n return (\n this.transactions.length === 1 &&\n this.transactions[0].kind === 'MoveCall' &&\n isSameTarget(this.transactions[0].target, this.contract.claimStreamByProxyTarget)\n );\n }\n\n private decodeCreateStreamTransaction(): DecodedCreateStream {\n const helper = new CreateStreamDecodeHelper(this.globals, this.txb);\n return helper.decode();\n }\n\n private decodeSetAutoClaimTransaction(): DecodedSetAutoClaim {\n const streamId = this.helper.decodeSharedObjectId(0);\n const enabled = this.helper.decodeInputBool(1);\n return {\n type: StreamTransactionType.SET_AUTO_CLAIM,\n streamId,\n enabled,\n };\n }\n\n private decodeClaimTransaction(): DecodedClaimStream {\n const streamId = this.helper.decodeSharedObjectId(0);\n return {\n type: StreamTransactionType.CLAIM,\n streamId,\n };\n }\n\n private decodeClaimByProxyTransaction(): DecodedClaimByProxy {\n const streamId = this.helper.decodeSharedObjectId(0);\n return {\n type: StreamTransactionType.CLAIM_BY_PROXY,\n streamId,\n };\n }\n\n private decodeCancelStreamTransaction(): DecodedCancelStream {\n const streamId = this.helper.decodeSharedObjectId(0);\n return {\n type: StreamTransactionType.CANCEL,\n streamId,\n };\n }\n\n private get helper() {\n const moveCall = this.transactions[0] as MoveCallTransaction;\n return new MoveCallHelper(moveCall, this.txb);\n }\n}\n","import { SetAutoClaimIntentionData, TransactionType } from '@msafe/sui3-utils';\nimport { SuiClient } from '@mysten/sui.js/client';\nimport { TransactionBlock } from '@mysten/sui.js/transactions';\nimport { WalletAccount } from '@mysten/wallet-standard';\n\nimport { SuiNetworks } from '@/types';\n\nimport { StreamIntention } from './intention';\nimport { StreamTransactionType } from './types/decode';\n\nexport class SetAutoClaimStreamIntention extends StreamIntention<SetAutoClaimIntentionData> {\n txType = TransactionType.Stream;\n\n txSubType = StreamTransactionType.SET_AUTO_CLAIM;\n\n constructor(public readonly data: SetAutoClaimIntentionData) {\n super(data);\n }\n\n async build(input: {\n network: SuiNetworks;\n suiClient: SuiClient;\n account: WalletAccount;\n }): Promise<TransactionBlock> {\n const { network, account } = input;\n const mpayClient = this.getClient(network, account);\n const stream = await mpayClient.getStream(this.data.streamId);\n return stream.setAutoClaim(this.data.enabled);\n }\n}\n","import {\n CancelStreamIntentionData,\n ClaimByProxyStreamIntentionData,\n ClaimStreamIntentionData,\n CreateStreamIntentionData,\n SetAutoClaimIntentionData,\n TransactionType,\n} from '@msafe/sui3-utils';\nimport { SuiClient } from '@mysten/sui.js/client';\nimport { TransactionBlock } from '@mysten/sui.js/transactions';\nimport { SuiSignTransactionBlockInput, WalletAccount } from '@mysten/wallet-standard';\n\nimport { IAppHelperInternalLegacy } from '@/apps/interface/sui-js';\nimport { SuiNetworks } from '@/types';\n\nimport { CancelStreamIntention } from './cancel-stream';\nimport { ClaimByProxyStreamIntention } from './claim-by-proxy-stream';\nimport { ClaimStreamIntention } from './claim-stream';\nimport { Env, Globals } from './common';\nimport { CreateStreamIntention } from './create-stream';\nimport { DecodeHelper } from './decoder/decoder';\nimport { SetAutoClaimStreamIntention } from './set-auto-claim-stream';\nimport { StreamTransactionType } from './types/decode';\n\nexport type MPayIntention =\n | CreateStreamIntention\n | SetAutoClaimStreamIntention\n | ClaimStreamIntention\n | CancelStreamIntention\n | ClaimByProxyStreamIntention;\n\nexport type MPayIntentionData =\n | CreateStreamIntentionData\n | SetAutoClaimIntentionData\n | ClaimStreamIntentionData\n | ClaimByProxyStreamIntentionData\n | CancelStreamIntentionData;\n\nexport class MPayAppHelper implements IAppHelperInternalLegacy<MPayIntentionData> {\n application = 'mpay';\n\n supportSDK = '@mysten/sui.js' as const;\n\n async deserialize(\n input: SuiSignTransactionBlockInput & { network: SuiNetworks; suiClient: SuiClient; account: WalletAccount },\n ): Promise<{ txType: TransactionType; txSubType: string; intentionData: MPayIntentionData }> {\n const { network, transactionBlock } = input;\n const globals = Globals.new(network === 'sui:mainnet' ? Env.prod : Env.dev);\n const decoder = new DecodeHelper(globals, transactionBlock);\n const result = decoder.decode();\n\n let intention: MPayIntention;\n\n switch (result.type) {\n case StreamTransactionType.CREATE_STREAM:\n intention = new CreateStreamIntention(result.info);\n break;\n case StreamTransactionType.SET_AUTO_CLAIM:\n intention = new SetAutoClaimStreamIntention({ streamId: result.streamId, enabled: result.enabled });\n break;\n case StreamTransactionType.CLAIM:\n intention = new ClaimStreamIntention({ streamId: result.streamId });\n break;\n case StreamTransactionType.CLAIM_BY_PROXY:\n intention = new ClaimByProxyStreamIntention({ streamId: result.streamId });\n break;\n case StreamTransactionType.CANCEL:\n intention = new CancelStreamIntention({ streamId: result.streamId });\n break;\n default:\n throw new Error(`Unknown transaction type: ${result}`);\n }\n\n return {\n txType: intention.txType,\n txSubType: intention.txSubType,\n intentionData: intention.data,\n };\n }\n\n async build(input: {\n intentionData: MPayIntentionData;\n txType: TransactionType;\n txSubType: string;\n suiClient: SuiClient;\n account: WalletAccount;\n network: SuiNetworks;\n }): Promise<TransactionBlock> {\n const { intentionData } = input;\n let intention: MPayIntention;\n switch (input.txSubType as StreamTransactionType) {\n case StreamTransactionType.CREATE_STREAM:\n intention = new CreateStreamIntention(intentionData as CreateStreamIntentionData);\n break;\n case StreamTransactionType.CLAIM:\n intention = new ClaimStreamIntention(intentionData as ClaimStreamIntentionData);\n break;\n case StreamTransactionType.CLAIM_BY_PROXY:\n intention = new ClaimByProxyStreamIntention(intentionData as ClaimByProxyStreamIntentionData);\n break;\n case StreamTransactionType.SET_AUTO_CLAIM:\n intention = new SetAutoClaimStreamIntention(intentionData as SetAutoClaimIntentionData);\n break;\n case StreamTransactionType.CANCEL:\n intention = new CancelStreamIntention(intentionData as CancelStreamIntentionData);\n break;\n default:\n throw new Error('not implemented');\n }\n return intention.build({ ...input });\n }\n}\n","import { TransactionDefaultApplication, TransactionSubTypes, TransactionType } from '@msafe/sui3-utils';\nimport { SuiClient } from '@mysten/sui.js/client';\nimport { TransactionBlock } from '@mysten/sui.js/transactions';\nimport { WalletAccount } from '@mysten/wallet-standard';\n\nimport { IAppHelperInternalLegacy } from '@/apps/interface/sui-js';\nimport { CoinTransferIntention, CoinTransferIntentionData } from '@/apps/msafe-core/coin-transfer';\n\nimport { ObjectTransferIntention, ObjectTransferIntentionData } from './object-transfer';\nimport { PlainPayloadIntention, PlainPayloadIntentionData } from './plain-payload';\n\nexport type CoreIntention = CoinTransferIntention | ObjectTransferIntention | PlainPayloadIntention;\n\nexport type CoreIntentionData = CoinTransferIntentionData | ObjectTransferIntentionData | PlainPayloadIntentionData;\n\nexport class CoreHelper implements IAppHelperInternalLegacy<CoreIntentionData> {\n application = 'msafe-core';\n\n supportSDK = '@mysten/sui.js' as const;\n\n constructor() {\n this.application = TransactionDefaultApplication;\n }\n\n deserialize(): Promise<{ txType: TransactionType; txSubType: string; intentionData: CoreIntentionData }> {\n throw new Error('MSafe core transaction intention should be build from API');\n }\n\n async build(input: {\n intentionData: CoreIntentionData;\n txType: TransactionType;\n txSubType: string;\n suiClient: SuiClient;\n account: WalletAccount;\n }): Promise<TransactionBlock> {\n const { suiClient, account } = input;\n let intention: CoreIntention;\n switch (input.txSubType) {\n case TransactionSubTypes.assets.coin.send:\n intention = CoinTransferIntention.fromData(input.intentionData as CoinTransferIntentionData);\n break;\n case TransactionSubTypes.assets.object.send:\n intention = ObjectTransferIntention.fromData(input.intentionData as ObjectTransferIntentionData);\n break;\n case TransactionSubTypes.others.plain:\n intention = PlainPayloadIntention.fromData(input.intentionData as PlainPayloadIntentionData);\n break;\n default:\n throw new Error('not implemented');\n }\n return intention.build({ suiClient, account });\n }\n}\n","import { TransactionType, buildCoinTransferTxb } from '@msafe/sui3-utils';\nimport { SuiClient } from '@mysten/sui.js/client';\nimport { TransactionBlock } from '@mysten/sui.js/transactions';\nimport { WalletAccount } from '@mysten/wallet-standard';\n\nimport { BaseIntentionLegacy } from '@/apps/interface/sui-js';\n\nexport interface CoinTransferIntentionData {\n recipient: string;\n coinType: string;\n amount: string;\n}\n\nexport class CoinTransferIntention extends BaseIntentionLegacy<CoinTransferIntentionData> {\n txType: TransactionType.Assets;\n\n txSubType: 'SendCoin';\n\n constructor(public readonly data: CoinTransferIntentionData) {\n super(data);\n }\n\n async build(input: { suiClient: SuiClient; account: WalletAccount }): Promise<TransactionBlock> {\n const { suiClient, account } = input;\n return buildCoinTransferTxb(suiClient, this.data, account.address);\n }\n\n static fromData(data: CoinTransferIntentionData) {\n return new CoinTransferIntention(data);\n }\n}\n","import { TransactionType, buildObjectTransferTxb } from '@msafe/sui3-utils';\nimport { SuiClient } from '@mysten/sui.js/client';\nimport { TransactionBlock } from '@mysten/sui.js/transactions';\nimport { WalletAccount } from '@mysten/wallet-standard';\n\nimport { BaseIntentionLegacy } from '@/apps/interface/sui-js';\n\nexport interface ObjectTransferIntentionData {\n receiver: string;\n objectType: string;\n objectId: string;\n}\n\nexport class ObjectTransferIntention extends BaseIntentionLegacy<ObjectTransferIntentionData> {\n txType: TransactionType.Assets;\n\n txSubType: 'SendObject';\n\n constructor(public readonly data: ObjectTransferIntentionData) {\n super(data);\n }\n\n async build(input: { suiClient: SuiClient; account: WalletAccount }): Promise<TransactionBlock> {\n const { suiClient, account } = input;\n return buildObjectTransferTxb(suiClient, this.data, account.address);\n }\n\n static fromData(data: ObjectTransferIntentionData) {\n return new ObjectTransferIntention(data);\n }\n}\n","import { TransactionType, isSameAddress } from '@msafe/sui3-utils';\nimport { SuiClient } from '@mysten/sui.js/client';\nimport { TransactionBlock } from '@mysten/sui.js/transactions';\nimport { WalletAccount } from '@mysten/wallet-standard';\n\nimport { BaseIntentionLegacy } from '@/apps/interface/sui-js';\n\nexport interface PlainPayloadIntentionData {\n content: string;\n}\n\nexport class PlainPayloadIntention extends BaseIntentionLegacy<PlainPayloadIntentionData> {\n txType: TransactionType.Other;\n\n txSubType: 'PlainPayload';\n\n constructor(public readonly data: PlainPayloadIntentionData) {\n super(data);\n }\n\n async build(input: { suiClient: SuiClient; account: WalletAccount }): Promise<TransactionBlock> {\n const { account } = input;\n const tb = TransactionBlock.from(this.data.content);\n\n if (!isSameAddress(tb.blockData.sender, account.address)) {\n throw new Error('Invalid sender address');\n }\n\n return tb;\n }\n\n static fromData(data: PlainPayloadIntentionData) {\n return new PlainPayloadIntention(data);\n }\n}\n","import { TransactionType } from '@msafe/sui3-utils';\nimport { SuiClient } from '@mysten/sui.js/client';\nimport { TransactionBlock } from '@mysten/sui.js/transactions';\nimport { WalletAccount, SuiSignTransactionBlockInput } from '@mysten/wallet-standard';\n\nimport { IAppHelperInternalLegacy } from '@/apps/interface/sui-js';\nimport { SuiNetworks } from '@/types';\n\nimport { updatePackageId } from './config';\nimport { Decoder } from './decoder';\nimport { ClaimRewardIntention, ClaimRewardIntentionData } from './intentions/claim-reward';\nimport { EntryBorrowIntention, EntryBorrowIntentionData } from './intentions/entry-borrow';\nimport { EntryDepositIntention, EntryDepositIntentionData } from './intentions/entry-deposit';\nimport { EntryRepayIntention, EntryRepayIntentionData } from './intentions/entry-repay';\nimport { EntryWithdrawIntention, EntryWithdrawIntentionData } from './intentions/entry-withdraw';\nimport { TransactionSubType } from './types';\n\nexport type NAVIIntention =\n | EntryDepositIntention\n | EntryBorrowIntention\n | EntryRepayIntention\n | EntryWithdrawIntention\n | ClaimRewardIntention;\n\nexport type NAVIIntentionData =\n | EntryDepositIntentionData\n | EntryBorrowIntentionData\n | EntryRepayIntentionData\n | EntryWithdrawIntentionData\n | ClaimRewardIntentionData;\n\nexport class NAVIAppHelper implements IAppHelperInternalLegacy<NAVIIntentionData> {\n application = 'navi';\n\n supportSDK = '@mysten/sui.js' as const;\n\n async deserialize(\n input: SuiSignTransactionBlockInput & { network: SuiNetworks; suiClient: SuiClient; account: WalletAccount },\n ): Promise<{ txType: TransactionType; txSubType: TransactionSubType; intentionData: NAVIIntentionData }> {\n await updatePackageId();\n const { transactionBlock } = input;\n const decoder = new Decoder(transactionBlock);\n const result = decoder.decode();\n return {\n txType: TransactionType.Other,\n txSubType: result.type,\n intentionData: result.intentionData,\n };\n }\n\n async build(input: {\n intentionData: NAVIIntentionData;\n txType: TransactionType;\n txSubType: string;\n suiClient: SuiClient;\n account: WalletAccount;\n }): Promise<TransactionBlock> {\n const { suiClient, account } = input;\n let intention: NAVIIntention;\n await updatePackageId();\n switch (input.txSubType) {\n case TransactionSubType.EntryDeposit:\n intention = EntryDepositIntention.fromData(input.intentionData as EntryDepositIntentionData);\n break;\n case TransactionSubType.EntryBorrow:\n intention = EntryBorrowIntention.fromData(input.intentionData as EntryBorrowIntentionData);\n break;\n case TransactionSubType.EntryRepay:\n intention = EntryRepayIntention.fromData(input.intentionData as EntryRepayIntentionData);\n break;\n case TransactionSubType.EntryWithdraw:\n intention = EntryWithdrawIntention.fromData(input.intentionData as EntryWithdrawIntentionData);\n break;\n case TransactionSubType.ClaimReward:\n intention = ClaimRewardIntention.fromData(input.intentionData as ClaimRewardIntentionData);\n break;\n default:\n throw new Error('not implemented');\n }\n return intention.build({ suiClient, account });\n }\n}\n","import { CoinType, type Pool } from './types';\n\nlet updated = false;\n\nconst config = {\n ProtocolPackage: '0xc6374c7da60746002bfee93014aeb607e023b2d6b25c9e55a152b826dbc8c1ce',\n StorageId: '0xbb4e2f4b6205c2e2a2db47aeb4f830796ec7c005f88537ee775986639bc442fe',\n Incentive: '0xaaf735bf83ff564e1b219a0d644de894ef5bdc4b2250b126b2a46dd002331821',\n IncentiveV2: '0xf87a8acb8b81d14307894d12595541a73f19933f88e1326d5be349c7a6f7559c', // The new incentive version: V2\n gasBudget: 50_000_000,\n PriceOracle: '0x1568865ed9a0b5ec414220e8f79b3d04c77acc82358f6e5ae4635687392ffbef',\n ReserveParentId: '0xe6d4c6610b86ce7735ea754596d71d72d10c7980b5052fc3c8cdf8d09fea9b4b', // get it from storage object id. storage.reserves\n pool: {\n sui: {\n name: 'SUI',\n assetId: 0,\n poolId: '0x96df0fce3c471489f4debaaa762cf960b3d97820bd1f3f025ff8190730e958c5',\n fondPoolId: '0xf975bc2d4cca10e3ace8887e20afd77b46c383b4465eac694c4688344955dea4',\n type: '0x2::sui::SUI',\n coinType: CoinType.sui,\n reserveObjectId: '0xab644b5fd11aa11e930d1c7bc903ef609a9feaf9ffe1b23532ad8441854fbfaf',\n borrowBalanceParentId: '0xe7ff0daa9d090727210abe6a8b6c0c5cd483f3692a10610386e4dc9c57871ba7',\n supplyBalanceParentId: '0x589c83af4b035a3bc64c40d9011397b539b97ea47edf7be8f33d643606bf96f8',\n },\n wusdc: {\n name: 'wUSDC',\n assetId: 1,\n coinType: CoinType.wusdc,\n poolId: '0xa02a98f9c88db51c6f5efaaf2261c81f34dd56d86073387e0ef1805ca22e39c8',\n type: '0x5d4b302506645c37ff133b98c4b50a5ae14841659738d6d733d59d0d217a93bf::coin::COIN',\n reserveObjectId: '0xeb3903f7748ace73429bd52a70fff278aac1725d3b58afa781f25ce3450ac203',\n borrowBalanceParentId: '0x8a3aaa817a811131c624658f6e77cba04ab5829293d2c49c1a9cce8ac9c8dec4',\n supplyBalanceParentId: '0x8d0a4467806458052d577c8cd2be6031e972f2b8f5f77fce98aa12cd85330da9',\n },\n usdt: {\n name: 'USDT',\n coinType: CoinType.usdt,\n assetId: 2,\n poolId: '0x0e060c3b5b8de00fb50511b7a45188c8e34b6995c01f69d98ea5a466fe10d103',\n type: '0xc060006111016b8a020ad5b33834984a437aaa7d3c74c18e09a95d48aceab08c::coin::COIN',\n reserveObjectId: '0xb8c5eab02a0202f638958cc79a69a2d30055565caad1684b3c8bbca3bddcb322',\n borrowBalanceParentId: '0xc14d8292a7d69ae31164bafab7ca8a5bfda11f998540fe976a674ed0673e448f',\n supplyBalanceParentId: '0x7e2a49ff9d2edd875f82b76a9b21e2a5a098e7130abfd510a203b6ea08ab9257',\n },\n weth: {\n name: 'WETH',\n coinType: CoinType.weth,\n assetId: 3,\n poolId: '0x71b9f6e822c48ce827bceadce82201d6a7559f7b0350ed1daa1dc2ba3ac41b56',\n type: '0xaf8cd5edc19c4512f4259f0bee101a40d41ebed738ade5874359610ef8eeced5::coin::COIN',\n reserveObjectId: '0xafecf4b57899d377cc8c9de75854c68925d9f512d0c47150ca52a0d3a442b735',\n borrowBalanceParentId: '0x7568d06a1b6ffc416a36c82791e3daf0e621cf19d4a2724fc6f74842661b6323',\n supplyBalanceParentId: '0xa668905b1ad445a3159b4d29b1181c4a62d864861b463dd9106cc0d97ffe8f7f',\n },\n cetus: {\n name: 'CETUS',\n coinType: CoinType.cetus,\n assetId: 4,\n poolId: '0x3c376f857ec4247b8ee456c1db19e9c74e0154d4876915e54221b5052d5b1e2e',\n type: '0x06864a6f921804860930db6ddbe2e16acdf8504495ea7481637a1c8b9a8fe54b::cetus::CETUS',\n reserveObjectId: '0x66a807c06212537fe46aa6719a00e4fa1e85a932d0b53ce7c4b1041983645133',\n borrowBalanceParentId: '0x4c3da45ffff6432b4592a39cdb3ce12f4a28034cbcb804bb071facc81fdd923d',\n supplyBalanceParentId: '0x6adc72faf2a9a15a583c9fb04f457c6a5f0b456bc9b4832413a131dfd4faddae',\n },\n voloSui: {\n name: 'VoloSui',\n coinType: CoinType.voloSui,\n assetId: 5,\n poolId: '0x9790c2c272e15b6bf9b341eb531ef16bcc8ed2b20dfda25d060bf47f5dd88d01',\n fondPoolId: '0xe2b5ada45273676e0da8ae10f8fe079a7cec3d0f59187d3d20b1549c275b07ea',\n type: '0x549e8b69270defbfafd4f94e17ec44cdbdd99820b33bda2278dea3b9a32d3f55::cert::CERT',\n reserveObjectId: '0xd4fd7e094af9819b06ea3136c13a6ae8da184016b78cf19773ac26d2095793e2',\n borrowBalanceParentId: '0x8fa5eccbca2c4ba9aae3b87fd44aa75aa5f5b41ea2d9be4d5321379384974984',\n supplyBalanceParentId: '0xe6457d247b6661b1cac123351998f88f3e724ff6e9ea542127b5dcb3176b3841',\n },\n haSui: {\n name: 'HaedalSui',\n coinType: CoinType.haSui,\n assetId: 6,\n poolId: '0x6fd9cb6ebd76bc80340a9443d72ea0ae282ee20e2fd7544f6ffcd2c070d9557a',\n fondPoolId: '0xa20e18085ce04be8aa722fbe85423f1ad6b1ae3b1be81ffac00a30f1d6d6ab51',\n type: '0xbde4ba4c2e274a60ce15c1cfff9e5c42e41654ac8b6d906a57efa4bd3c29f47d::hasui::HASUI',\n reserveObjectId: '0x0c9f7a6ca561dc566bd75744bcc71a6af1dc3caf7bd32c099cd640bb5f3bb0e3',\n borrowBalanceParentId: '0x01f36898e020be6c3423e5c95d9f348868813cd4d0be39b0c8df9d8de4722b00',\n supplyBalanceParentId: '0x278b8e3d09c3548c60c51ed2f8eed281876ea58c392f71b7ff650cc9286d095b',\n },\n navx: {\n name: 'NAVX',\n coinType: CoinType.navx,\n assetId: 7,\n poolId: '0xc0e02e7a245e855dd365422faf76f87d9f5b2148a26d48dda6e8253c3fe9fa60',\n fondPoolId: '0x9dae0cf104a193217904f88a48ce2cf0221e8cd9073878edd05101d6b771fa09',\n type: '0xa99b8952d4f7d947ea77fe0ecdcc9e5fc0bcab2841d6e2a5aa00c3044e5544b5::navx::NAVX',\n reserveObjectId: '0x2e13b2f1f714c0c5fa72264f147ef7632b48ec2501f810c07df3ccb59d6fdc81',\n borrowBalanceParentId: '0xa5bf13075aa400cbdd4690a617c5f008e1fae0511dcd4f7121f09817df6c8d8b',\n supplyBalanceParentId: '0x59dedca8dc44e8df50b190f8b5fe673098c1273ac6168c0a4addf3613afcdee5',\n },\n wbtc: {\n name: 'WBTC',\n coinType: CoinType.wbtc,\n assetId: 8,\n poolId: '0xd162cbe40f8829ce71c9b3d3bf3a83859689a79fa220b23d70dc0300b777ae6e',\n type: '0x027792d9fed7f9844eb4839566001bb6f6cb4804f66aa2da6fe1ee242d896881::coin::COIN',\n reserveObjectId: '0x8b4d81f004e4e9faf4540951a896b6d96e42598a270e6375f598b99742db767e',\n borrowBalanceParentId: '0x55e1f3c9e6e5cf9fff563bdd61db07a3826458c56ef72c455e049ab3b1b0e99c',\n supplyBalanceParentId: '0x821e505a0091b089edba94deaa14c2f2230d026bbaa7b85680554441aad447e0',\n },\n ausd: {\n name: 'AUSD',\n coinType: CoinType.ausd,\n assetId: 9,\n poolId: '0xc9208c1e75f990b2c814fa3a45f1bf0e85bb78404cfdb2ae6bb97de58bb30932',\n type: '0x2053d08c1e2bd02791056171aab0fd12bd7cd7efad2ab8f6b9c8902f14df2ff2::ausd::AUSD',\n reserveObjectId: '0x918889c6a9d9b93108531d4d59a4ebb9cc4d41689798ffc1d4aed6e1ae816ec0',\n borrowBalanceParentId: '0x551300b9441c9a3a16ca1d7972c1dbb4715e15004ccd5f001b2c2eee22fd92c1',\n supplyBalanceParentId: '0xe151af690355de8be1c0281fbd0d483c099ea51920a57c4bf8c9666fd36808fd',\n },\n nusdc: {\n name: 'USDC',\n assetId: 10,\n coinType: CoinType.nusdc,\n poolId: '0xa3582097b4c57630046c0c49a88bfc6b202a3ec0a9db5597c31765f7563755a8',\n type: '0xdba34672e30cb065b1f93e3ab55318768fd6fef66c15942c9f7cb846e2f900e7::usdc::USDC',\n reserveObjectId: '0x4c8a2c72a22ae8da803a8519798d312c86e74a9e0d6ec0eec2bfcf7e4b3fef5e',\n borrowBalanceParentId: '0xb0b0c7470e96cabbb4f1e8d06bef2fbea65f4dbac52afae8635d9286b1ea9a09',\n supplyBalanceParentId: '0x08b5ce8574ac3bc9327e66ad5decd34d07ee798f724ad01058e8855ac9acb605',\n },\n eth: {\n name: 'ETH',\n assetId: 11,\n coinType: CoinType.eth,\n poolId: '0x78ba01c21d8301be15690d3c30dc9f111871e38cfb0b2dd4b70cc6052fba41bb',\n type: '0xd0e89b2af5e4910726fbcd8b8dd37bb79b29e5f83f7491bca830e94f7f226d29::eth::ETH',\n reserveObjectId: '0x376faea6dfbffab9ea808474cb751d91222b6d664f38c0f1d23de442a8edb1ce',\n borrowBalanceParentId: '0xf0c6ce5cfaee96073876a5fab7426043f3a798b79502c4caeb6d9772cd35af1f',\n supplyBalanceParentId: '0xc0a0cb43620eb8a84d5a4a50a85650e7fa7ba81e660f9cc2863404fd84591d4b',\n },\n usdy: {\n name: 'USDY',\n assetId: 12,\n coinType: CoinType.usdy,\n poolId: '0x4b6253a9f8cf7f5d31e6d04aed4046b9e325a1681d34e0eff11a8441525d4563',\n type: '0x960b531667636f39e85867775f52f6b1f220a058c4de786905bdf761e06a56bb::usdy::USDY',\n reserveObjectId: '',\n borrowBalanceParentId: '',\n supplyBalanceParentId: '',\n },\n } as Pool,\n borrowFee: 0.003,\n borrowFeeAddress: '0x70b9b10704263cf53392849e33b1f5fd16005869b4198ed5524836bad1234ea2',\n};\n\nexport async function updatePackageId() {\n if (updated) {\n return;\n }\n try {\n const data = await fetch('https://open-api.naviprotocol.io/api/msafe').then((res) => res.json());\n const { packageId, borrowFee, borrowFeeAddress, pool } = data;\n if (packageId) {\n config.ProtocolPackage = packageId;\n }\n if (borrowFee) {\n config.borrowFee = borrowFee;\n }\n if (borrowFeeAddress) {\n config.borrowFeeAddress = borrowFeeAddress;\n }\n if (pool) {\n config.pool = pool;\n }\n updated = true;\n } catch (e: any) {\n console.error(e.message);\n }\n}\n\nexport default config;\n","import { TransactionType } from '@msafe/sui3-utils';\nimport { bcs } from '@mysten/sui.js/bcs';\nimport { MoveCallTransaction } from '@mysten/sui.js/dist/cjs/transactions';\nimport { TransactionBlock, TransactionBlockInput } from '@mysten/sui.js/transactions';\nimport { normalizeStructTag, normalizeSuiAddress } from '@mysten/sui.js/utils';\n\nimport config from './config';\nimport { CoinType, TransactionSubType } from './types';\n\nexport function isSameCoinType(type1: string, type2: string) {\n return normalizeStructTag(type1) === normalizeStructTag(type2);\n}\n\nexport function isSameTarget(target1: string, target2: string): boolean {\n return normalizeStructTag(target1) === normalizeStructTag(target2);\n}\n\ntype DecodeResult = {\n txType: TransactionType;\n type: TransactionSubType;\n intentionData: any;\n};\n\nexport class Decoder {\n constructor(public readonly txb: TransactionBlock) {}\n\n decode() {\n console.log('txb', this.txb);\n if (this.isClaimRewardTransaction()) {\n return this.decodeClaimReward();\n }\n if (this.isEntryBorrowTransaction()) {\n return this.decodeEntryBorrow();\n }\n if (this.isEntryBorrowWithFeeTransaction()) {\n return this.decodeEntryBorrow();\n }\n if (this.isEntryDepositTransaction()) {\n return this.decodeEntryDeposit();\n }\n if (this.isEntryRepayTransaction()) {\n return this.decodeEntryRepay();\n }\n if (this.isEntryWithdrawTransaction()) {\n return this.decodeEntryWithdraw();\n }\n throw new Error(`Unknown transaction type`);\n }\n\n private get transactions() {\n return this.txb.blockData.transactions;\n }\n\n private getMoveCallTransaction(target: string) {\n return this.transactions.find((trans) => trans.kind === 'MoveCall' && trans.target === target);\n }\n\n private isClaimRewardTransaction() {\n return !!this.getMoveCallTransaction(`${config.ProtocolPackage}::incentive_v2::claim_reward`);\n }\n\n private isEntryBorrowTransaction() {\n return !!this.getMoveCallTransaction(`${config.ProtocolPackage}::incentive_v2::entry_borrow`);\n }\n\n private isEntryBorrowWithFeeTransaction() {\n return !!this.getMoveCallTransaction(`${config.ProtocolPackage}::incentive_v2::borrow`);\n }\n\n private isEntryDepositTransaction() {\n return !!this.getMoveCallTransaction(`${config.ProtocolPackage}::incentive_v2::entry_deposit`);\n }\n\n private isEntryRepayTransaction(): boolean {\n return !!this.getMoveCallTransaction(`${config.ProtocolPackage}::incentive_v2::entry_repay`);\n }\n\n private isEntryWithdrawTransaction(): boolean {\n return !!this.getMoveCallTransaction(`${config.ProtocolPackage}::incentive_v2::entry_withdraw`);\n }\n\n private findPoolByAssetId(assetId: number) {\n const findPool = Object.values(config.pool).find((pool) => pool.assetId === assetId);\n if (!findPool) {\n throw new Error('Pool not found');\n }\n return findPool;\n }\n\n private decodeClaimReward(): DecodeResult {\n const claims = [] as {\n coinType: CoinType;\n option: number;\n poolId: string;\n assetId: number;\n typeArguments: string[];\n }[];\n this.transactions.forEach((trans) => {\n if (trans.kind === 'MoveCall' && trans.target === `${config.ProtocolPackage}::incentive_v2::claim_reward`) {\n const helper = new MoveCallHelper(trans, this.txb);\n const assetId = helper.decodeInputU8(4);\n const optionId = helper.decodeInputU8(5);\n const poolId = helper.decodeSharedObjectId(2);\n const pool = this.findPoolByAssetId(assetId);\n const typeArguments = [...trans.typeArguments];\n claims.push({\n coinType: pool.coinType,\n option: optionId,\n typeArguments,\n assetId,\n poolId,\n });\n }\n });\n console.log('decode claims', claims);\n return {\n txType: TransactionType.Other,\n type: TransactionSubType.ClaimReward,\n intentionData: {\n claims,\n },\n };\n }\n\n private decodeEntryBorrow(): DecodeResult {\n const assetId = this.helper.decodeInputU8(4);\n const amount = this.helper.decodeInputU64(5);\n const pool = this.findPoolByAssetId(assetId);\n return {\n txType: TransactionType.Other,\n type: TransactionSubType.EntryBorrow,\n intentionData: {\n amount,\n coinType: pool.coinType,\n },\n };\n }\n\n private decodeEntryDeposit(): DecodeResult {\n const assetId = this.helper.decodeInputU8(3);\n const amount = this.helper.decodeInputU64(5);\n const pool = this.findPoolByAssetId(assetId);\n return {\n txType: TransactionType.Other,\n type: TransactionSubType.EntryDeposit,\n intentionData: {\n amount,\n coinType: pool.coinType,\n },\n };\n }\n\n private decodeEntryRepay(): DecodeResult {\n const assetId = this.helper.decodeInputU8(4);\n const amount = this.helper.decodeInputU64(6);\n const pool = this.findPoolByAssetId(assetId);\n return {\n txType: TransactionType.Other,\n type: TransactionSubType.EntryRepay,\n intentionData: {\n amount,\n coinType: pool.coinType,\n },\n };\n }\n\n private decodeEntryWithdraw(): DecodeResult {\n const assetId = this.helper.decodeInputU8(4);\n const amount = this.helper.decodeInputU64(5);\n const pool = this.findPoolByAssetId(assetId);\n return {\n txType: TransactionType.Other,\n type: TransactionSubType.EntryWithdraw,\n intentionData: {\n amount,\n coinType: pool.coinType,\n },\n };\n }\n\n private get helper() {\n const moveCall = this.transactions.find(\n (trans) => trans.kind === 'MoveCall' && trans.target.startsWith(config.ProtocolPackage),\n ) as MoveCallTransaction;\n return new MoveCallHelper(moveCall, this.txb);\n }\n}\n\nexport class MoveCallHelper {\n constructor(\n public readonly moveCall: MoveCallTransaction,\n public readonly txb: TransactionBlock,\n ) {}\n\n decodeSharedObjectId(argIndex: number) {\n const input = this.getInputParam(argIndex);\n return MoveCallHelper.getSharedObjectId(input);\n }\n\n decodeOwnedObjectId(argIndex: number) {\n const input = this.getInputParam(argIndex);\n return MoveCallHelper.getOwnedObjectId(input);\n }\n\n decodeInputU64(argIndex: number) {\n const strVal = this.decodePureArg<string>(argIndex, 'u64');\n return Number(strVal);\n }\n\n decodeInputU8(argIndex: number) {\n const strVal = this.decodePureArg<string>(argIndex, 'u8');\n return Number(strVal);\n }\n\n decodeInputAddress(argIndex: number) {\n const input = this.decodePureArg<string>(argIndex, 'address');\n return normalizeSuiAddress(input);\n }\n\n decodeInputString(argIndex: number) {\n return this.decodePureArg<string>(argIndex, 'string');\n }\n\n decodeInputBool(argIndex: number) {\n return this.decodePureArg<boolean>(argIndex, 'bool');\n }\n\n decodePureArg<T>(argIndex: number, bcsType: string) {\n const input = this.getInputParam(argIndex);\n return MoveCallHelper.getPureInputValue<T>(input, bcsType);\n }\n\n getInputParam(argIndex: number) {\n const arg = this.moveCall.arguments[argIndex];\n if (arg.kind !== 'Input') {\n throw new Error('not input type');\n }\n return this.txb.blockData.inputs[arg.index];\n }\n\n static getPureInputValue<T>(input: TransactionBlockInput, bcsType: string) {\n if (input.type !== 'pure') {\n throw new Error('not pure argument');\n }\n if (typeof input.value === 'object' && 'Pure' in input.value) {\n const bcsNums = input.value.Pure;\n return bcs.de(bcsType, new Uint8Array(bcsNums)) as T;\n }\n return input.value as T;\n }\n\n static getOwnedObjectId(input: TransactionBlockInput) {\n if (input.type !== 'object') {\n throw new Error(`not object argument: ${JSON.stringify(input)}`);\n }\n if (typeof input.value === 'object') {\n if (!('Object' in input.value) || !('ImmOrOwned' in input.value.Object)) {\n throw new Error('not ImmOrOwned');\n }\n return normalizeSuiAddress(input.value.Object.ImmOrOwned.objectId as string);\n }\n return normalizeSuiAddress(input.value as string);\n }\n\n static getSharedObjectId(input: TransactionBlockInput) {\n if (input.type !== 'object') {\n throw new Error(`not object argument: ${JSON.stringify(input)}`);\n }\n if (typeof input.value !== 'object') {\n return normalizeSuiAddress(input.value as string);\n }\n if (!('Object' in input.value) || !('Shared' in input.value.Object)) {\n throw new Error('not Shared');\n }\n return normalizeSuiAddress(input.value.Object.Shared.objectId as string);\n }\n\n static getPureInput<T>(input: TransactionBlockInput, bcsType: string) {\n if (input.type !== 'pure') {\n throw new Error('not pure argument');\n }\n if (typeof input.value !== 'object') {\n return input.value as T;\n }\n if (!('Pure' in input.value)) {\n throw new Error('Pure not in value');\n }\n const bcsVal = input.value.Pure;\n return bcs.de(bcsType, new Uint8Array(bcsVal)) as T;\n }\n\n typeArg(index: number) {\n return normalizeStructTag(this.moveCall.typeArguments[index]);\n }\n\n txArg(index: number) {\n return this.moveCall.arguments[index];\n }\n}\n","import { TransactionType } from '@msafe/sui3-utils';\nimport { TransactionBlock } from '@mysten/sui.js/transactions';\n\nimport { BaseIntentionLegacy } from '@/apps/interface/sui-js';\n\nimport { claimReward } from '../api/incentiveV2';\nimport { CoinType, TransactionSubType, OptionType } from '../types';\n\nexport interface ClaimRewardIntentionData {\n claims: {\n coinType: CoinType;\n option: OptionType;\n poolId: string;\n assetId: number;\n typeArguments: string[];\n }[];\n}\n\nexport class ClaimRewardIntention extends BaseIntentionLegacy<ClaimRewardIntentionData> {\n txType: TransactionType.Other;\n\n txSubType: TransactionSubType.ClaimReward;\n\n constructor(public readonly data: ClaimRewardIntentionData) {\n super(data);\n }\n\n async build(): Promise<TransactionBlock> {\n const { claims } = this.data;\n const tx = new TransactionBlock();\n\n claims.forEach((claim) => {\n const { assetId, poolId, option, typeArguments } = claim;\n\n claimReward(tx, assetId, poolId, option, typeArguments);\n });\n\n return tx;\n }\n\n static fromData(data: ClaimRewardIntentionData) {\n return new ClaimRewardIntention(data);\n }\n}\n","import { TransactionBlock } from '@mysten/sui.js/transactions';\n\nimport config from '../config';\nimport { OptionType, PoolConfig } from '../types';\n\nexport function depositToken(txb: TransactionBlock, pool: PoolConfig, coinObject: any, amount: number) {\n txb.moveCall({\n target: `${config.ProtocolPackage}::incentive_v2::entry_deposit`,\n arguments: [\n txb.object('0x06'),\n txb.object(config.StorageId),\n txb.object(pool.poolId),\n txb.pure(pool.assetId),\n coinObject,\n txb.pure(amount),\n txb.object(config.Incentive),\n txb.object(config.IncentiveV2),\n ],\n typeArguments: [pool.type],\n });\n return txb;\n}\n\nexport function withdrawToken(txb: TransactionBlock, pool: PoolConfig, amount: number) {\n txb.moveCall({\n target: `${config.ProtocolPackage}::incentive_v2::entry_withdraw`,\n arguments: [\n txb.object('0x06'),\n txb.object(config.PriceOracle),\n txb.object(config.StorageId),\n txb.object(pool.poolId),\n txb.pure(pool.assetId),\n txb.pure(amount),\n txb.object(config.Incentive),\n txb.object(config.IncentiveV2),\n ],\n typeArguments: [pool.type],\n });\n return txb;\n}\n\nexport function borrowToken(tx: TransactionBlock, pool: PoolConfig, amount: number, userAddress: string) {\n const borrowBalance = tx.moveCall({\n target: `${config.ProtocolPackage}::incentive_v2::borrow`,\n arguments: [\n tx.object('0x06'),\n tx.object(config.PriceOracle),\n tx.object(config.StorageId),\n tx.object(pool.poolId),\n tx.pure(pool.assetId),\n tx.pure(amount),\n tx.object(config.IncentiveV2),\n ],\n typeArguments: [pool.type],\n });\n\n const [borrowCoin] = tx.moveCall({\n target: `0x02::coin::from_balance`,\n typeArguments: [pool.type],\n arguments: [borrowBalance],\n });\n if (config.borrowFee > 0) {\n const [borrowFeeCoin] = tx.splitCoins(borrowCoin, [tx.pure(Math.floor(amount * config.borrowFee))]);\n tx.transferObjects([borrowCoin], tx.pure(userAddress));\n tx.transferObjects([borrowFeeCoin], tx.pure(config.borrowFeeAddress));\n } else {\n tx.transferObjects([borrowCoin], tx.pure(userAddress));\n }\n\n return tx;\n}\n\nexport function repayToken(txb: TransactionBlock, pool: PoolConfig, coinObject: any, amount: number) {\n txb.moveCall({\n target: `${config.ProtocolPackage}::incentive_v2::entry_repay`,\n arguments: [\n txb.object('0x06'),\n txb.object(config.PriceOracle),\n txb.object(config.StorageId),\n txb.object(pool.poolId),\n txb.pure(pool.assetId),\n coinObject,\n txb.pure(amount),\n txb.object(config.IncentiveV2),\n ],\n typeArguments: [pool.type],\n });\n return txb;\n}\n\nexport function claimReward(\n txb: TransactionBlock,\n assetId: number,\n poolId: string,\n option: OptionType,\n typeArguments: string[],\n) {\n txb.moveCall({\n target: `${config.ProtocolPackage}::incentive_v2::claim_reward`,\n arguments: [\n txb.object('0x06'),\n txb.object(config.IncentiveV2),\n txb.object(poolId),\n txb.object(config.StorageId),\n txb.pure(assetId),\n txb.pure(option),\n ],\n typeArguments,\n });\n return txb;\n}\n","import { TransactionType } from '@msafe/sui3-utils';\nimport { TransactionBlock } from '@mysten/sui.js/transactions';\nimport { WalletAccount } from '@mysten/wallet-standard';\n\nimport { BaseIntentionLegacy } from '@/apps/interface/sui-js';\n\nimport { borrowToken } from '../api/incentiveV2';\nimport config from '../config';\nimport { CoinType, TransactionSubType } from '../types';\n\nexport interface EntryBorrowIntentionData {\n amount: number;\n coinType: CoinType;\n}\n\nexport class EntryBorrowIntention extends BaseIntentionLegacy<EntryBorrowIntentionData> {\n txType: TransactionType.Other;\n\n txSubType: TransactionSubType.EntryBorrow;\n\n constructor(public readonly data: EntryBorrowIntentionData) {\n super(data);\n }\n\n async build(input: { account: WalletAccount }): Promise<TransactionBlock> {\n const { coinType, amount } = this.data;\n const tx = new TransactionBlock();\n console.log('build', this.data);\n\n const pool = config.pool[coinType];\n\n if (!pool) {\n throw new Error(`${coinType} not support, please use ${Object.keys(config.pool).join(', ')}.`);\n }\n\n return borrowToken(tx, pool, amount, input.account.address);\n }\n\n static fromData(data: EntryBorrowIntentionData) {\n return new EntryBorrowIntention(data);\n }\n}\n","import { TransactionType } from '@msafe/sui3-utils';\nimport { SuiClient } from '@mysten/sui.js/client';\nimport { TransactionBlock } from '@mysten/sui.js/transactions';\nimport { WalletAccount } from '@mysten/wallet-standard';\n\nimport { BaseIntentionLegacy } from '@/apps/interface/sui-js';\n\nimport { depositToken } from '../api/incentiveV2';\nimport config from '../config';\nimport { CoinType, TransactionSubType } from '../types';\nimport { getTokenObjs } from '../utils/token';\n\nexport interface EntryDepositIntentionData {\n amount: number;\n coinType: CoinType;\n}\n\nexport class EntryDepositIntention extends BaseIntentionLegacy<EntryDepositIntentionData> {\n txType: TransactionType.Other;\n\n txSubType: TransactionSubType.EntryDeposit;\n\n constructor(public readonly data: EntryDepositIntentionData) {\n super(data);\n }\n\n async build(input: { suiClient: SuiClient; account: WalletAccount }): Promise<TransactionBlock> {\n const { suiClient, account } = input;\n const { coinType, amount } = this.data;\n const tx = new TransactionBlock();\n console.log('build', this.data);\n\n if (coinType === 'sui') {\n const [toDeposit] = tx.splitCoins(tx.gas, [amount]);\n return depositToken(tx, config.pool.sui, toDeposit, amount);\n }\n\n const pool = config.pool[coinType];\n\n if (!pool) {\n throw new Error(`${coinType} not support, please use ${Object.keys(config.pool).join(', ')}.`);\n }\n\n const tokenInfo = await getTokenObjs(suiClient, account.address, pool.type);\n if (!tokenInfo.data[0]) {\n throw new Error(`Insufficient balance for ${pool.name} Token`);\n }\n\n const coinObj = tokenInfo.data[0].coinObjectId;\n\n if (tokenInfo.data.length >= 2) {\n let i = 1;\n while (i < tokenInfo.data.length) {\n tx.mergeCoins(coinObj, [tokenInfo.data[i].coinObjectId]);\n i++;\n }\n }\n\n return depositToken(tx, pool, tx.object(coinObj), amount);\n }\n\n static fromData(data: EntryDepositIntentionData) {\n return new EntryDepositIntention(data);\n }\n}\n","import { SuiClient } from '@mysten/sui.js/client';\n\nexport async function getTokenAmount(client: SuiClient, sender: string, coinType: string): Promise<number> {\n if (!sender) {\n throw new Error('Sender is undefined.');\n }\n if (!client) {\n throw new Error('Client is undefined.');\n }\n const coinInfo = await client.getBalance({\n owner: sender,\n coinType,\n });\n const tokenBalance = Number(coinInfo.totalBalance);\n return tokenBalance;\n}\n\nexport async function getTokenObjs(client: SuiClient, sender: string, coinType: string): Promise<any> {\n const result = await client.getCoins({\n owner: sender,\n coinType,\n });\n console.log('getTokenObjs', sender, result);\n return result;\n}\n","import { TransactionType } from '@msafe/sui3-utils';\nimport { SuiClient } from '@mysten/sui.js/client';\nimport { TransactionBlock } from '@mysten/sui.js/transactions';\nimport { WalletAccount } from '@mysten/wallet-standard';\n\nimport { BaseIntentionLegacy } from '@/apps/interface/sui-js';\n\nimport { repayToken } from '../api/incentiveV2';\nimport config from '../config';\nimport { CoinType, TransactionSubType } from '../types';\nimport { getTokenObjs } from '../utils/token';\n\nexport interface EntryRepayIntentionData {\n amount: number;\n coinType: CoinType;\n}\n\nexport class EntryRepayIntention extends BaseIntentionLegacy<EntryRepayIntentionData> {\n txType: TransactionType.Other;\n\n txSubType: TransactionSubType.EntryRepay;\n\n constructor(public readonly data: EntryRepayIntentionData) {\n super(data);\n }\n\n async build(input: { suiClient: SuiClient; account: WalletAccount }): Promise<TransactionBlock> {\n const { suiClient, account } = input;\n const { coinType, amount } = this.data;\n const tx = new TransactionBlock();\n console.log('build', this.data);\n\n if (coinType === 'sui') {\n const [toDeposit] = tx.splitCoins(tx.gas, [amount]);\n return repayToken(tx, config.pool.sui, toDeposit, amount);\n }\n\n const pool = config.pool[coinType];\n\n if (!pool) {\n throw new Error(`${coinType} not support, please use ${Object.keys(config.pool).join(', ')}.`);\n }\n\n const tokenInfo = await getTokenObjs(suiClient, account.address, pool.type);\n if (!tokenInfo.data[0]) {\n throw new Error(`Insufficient balance for ${pool.name} Token`);\n }\n\n const coinObj = tokenInfo.data[0].coinObjectId;\n\n if (tokenInfo.data.length >= 2) {\n let i = 1;\n while (i < tokenInfo.data.length) {\n tx.mergeCoins(coinObj, [tokenInfo.data[i].coinObjectId]);\n i++;\n }\n }\n\n return repayToken(tx, pool, tx.object(coinObj), amount);\n }\n\n static fromData(data: EntryRepayIntentionData) {\n return new EntryRepayIntention(data);\n }\n}\n","import { TransactionType } from '@msafe/sui3-utils';\nimport { TransactionBlock } from '@mysten/sui.js/transactions';\n\nimport { BaseIntentionLegacy } from '@/apps/interface/sui-js';\n\nimport { withdrawToken } from '../api/incentiveV2';\nimport config from '../config';\nimport { CoinType, TransactionSubType } from '../types';\n\nexport interface EntryWithdrawIntentionData {\n amount: number;\n coinType: CoinType;\n}\n\nexport class EntryWithdrawIntention extends BaseIntentionLegacy<EntryWithdrawIntentionData> {\n txType: TransactionType.Other;\n\n txSubType: TransactionSubType.EntryWithdraw;\n\n constructor(public readonly data: EntryWithdrawIntentionData) {\n super(data);\n }\n\n async build(): Promise<TransactionBlock> {\n const { coinType, amount } = this.data;\n const tx = new TransactionBlock();\n console.log('build', this.data);\n\n const pool = config.pool[coinType];\n\n if (!pool) {\n throw new Error(`${coinType} not support, please use ${Object.keys(config.pool).join(', ')}.`);\n }\n\n return withdrawToken(tx, pool, amount);\n }\n\n static fromData(data: EntryWithdrawIntentionData) {\n return new EntryWithdrawIntention(data);\n }\n}\n","import { TransactionSubTypes, TransactionType } from '@msafe/sui3-utils';\nimport { fromHEX, toHEX } from '@mysten/bcs';\nimport { SuiClient } from '@mysten/sui/client';\nimport { Transaction } from '@mysten/sui/transactions';\nimport { IdentifierString, WalletAccount } from '@mysten/wallet-standard';\nimport sortKeys from 'sort-keys-recursive';\n\nimport { IAppHelperInternal, TransactionIntention } from '@/apps/interface/sui';\nimport { SuiNetworks } from '@/types';\n\nexport type PlainTransactionData = {\n content: string;\n};\n\nexport const PlainTransactionApplication = 'msafe-plain-tx';\nexport const PlainTransactionType = TransactionSubTypes.others.plain;\n\nexport class PlainTransactionIntention implements TransactionIntention<PlainTransactionData> {\n application = PlainTransactionApplication;\n\n txType = TransactionType.Other;\n\n txSubType = PlainTransactionType;\n\n protected constructor(public readonly data: PlainTransactionData) {}\n\n serialize() {\n return JSON.stringify(sortKeys(this.data));\n }\n\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n async build(input: { suiClient: SuiClient; account: WalletAccount; network: SuiNetworks }): Promise<Transaction> {\n return Transaction.from(fromHEX(this.data.content));\n }\n\n static fromData(data: PlainTransactionData) {\n return new PlainTransactionIntention(data);\n }\n}\n\nexport class PlainTransactionHelper implements IAppHelperInternal<PlainTransactionData> {\n application: string;\n\n supportSDK = '@mysten/sui' as const;\n\n constructor() {\n this.application = PlainTransactionApplication;\n }\n\n async deserialize(input: {\n transaction: Transaction;\n chain: IdentifierString;\n network: SuiNetworks;\n suiClient: SuiClient;\n account: WalletAccount;\n }): Promise<{ txType: TransactionType; txSubType: string; intentionData: PlainTransactionData }> {\n const { transaction } = input;\n\n const content = await transaction.build({ client: input.suiClient });\n\n return {\n txType: TransactionType.Other,\n txSubType: PlainTransactionType,\n intentionData: { content: toHEX(content) },\n };\n }\n\n async build(input: {\n network: SuiNetworks;\n txType: TransactionType;\n txSubType: string;\n intentionData: PlainTransactionData;\n suiClient: SuiClient;\n account: WalletAccount;\n }): Promise<Transaction> {\n const { account } = input;\n\n const intention = PlainTransactionIntention.fromData(input.intentionData);\n const tx = await intention.build({ suiClient: input.suiClient, network: input.network, account: input.account });\n const client = input.suiClient;\n const inspectResult = await client.devInspectTransactionBlock({\n transactionBlock: tx,\n sender: account.address,\n });\n const success = inspectResult.effects.status.status === 'success';\n if (!success) {\n throw new Error(inspectResult.effects.status.error);\n }\n\n return tx;\n }\n}\n","import { TransactionType } from '@msafe/sui3-utils';\nimport { SuiClient } from '@mysten/sui/client';\nimport { Transaction } from '@mysten/sui/transactions';\nimport { SuiClient as SuiClientLegacy } from '@mysten/sui.js/client';\nimport { TransactionBlock } from '@mysten/sui.js/transactions';\nimport { SuiSignTransactionBlockInput, WalletAccount } from '@mysten/wallet-standard';\n\nimport { IAppHelper } from '@/apps/interface/common';\nimport { IAppHelperInternal } from '@/apps/interface/sui';\nimport { IAppHelperInternalLegacy } from '@/apps/interface/sui-js';\nimport { SuiNetworks } from '@/types';\n\nexport class MSafeApps {\n apps: Map<string, IAppHelper<any>>;\n\n private constructor() {\n this.apps = new Map<string, IAppHelper<any>>();\n }\n\n static fromHelpers(apps: (IAppHelperInternalLegacy<any> | IAppHelperInternal<any>)[]) {\n const mApps = new MSafeApps();\n for (let i = 0; i < apps.length; i++) {\n const app = apps[i];\n switch (app.supportSDK) {\n case '@mysten/sui.js':\n mApps.addLegacyHelper(app);\n break;\n case '@mysten/sui':\n mApps.addHelper(app);\n break;\n default:\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n throw new Error(`${app.application}: ${app.supportSDK} SDK not supported`);\n }\n }\n return mApps;\n }\n\n addLegacyHelper(app: IAppHelperInternalLegacy<any>) {\n this.apps.set(app.application, new SuiJsSdkAdapter(app));\n }\n\n addHelper(app: IAppHelperInternal<any>) {\n this.apps.set(app.application, new SuiSdkAdapter(app));\n }\n\n getAppHelper(appName: string): IAppHelper<any> {\n const app = this.apps.get(appName);\n if (!app) {\n throw new Error(`${appName} not registered`);\n }\n return app;\n }\n}\n\n/*\n SuiSdkAdapter adapts IAppHelperInternal with @mysten/sui to IAppHelper\n TODO: build to @mysten/sui Transaction after update sdk and api\n */\nexport class SuiSdkAdapter implements IAppHelper<any> {\n constructor(public helper: IAppHelperInternal<any>) {}\n\n async deserialize(\n input: SuiSignTransactionBlockInput & {\n network: SuiNetworks;\n clientUrl: string;\n account: WalletAccount;\n },\n ) {\n const client = new SuiClient({ url: input.clientUrl });\n const clientLegacy = new SuiClientLegacy({ url: input.clientUrl });\n const build = await input.transactionBlock.build({ client: clientLegacy });\n const tx = Transaction.from(build);\n return this.helper.deserialize({ ...input, suiClient: client, transaction: tx });\n }\n\n async build(input: {\n intentionData: any;\n txType: TransactionType;\n txSubType: string;\n clientUrl: string;\n account: WalletAccount;\n network: SuiNetworks;\n }): Promise<TransactionBlock> {\n const client = new SuiClient({ url: input.clientUrl });\n const tx = await this.helper.build({ ...input, suiClient: client });\n tx.setSender(input.account.address);\n const bytes = await tx.build({ client });\n return TransactionBlock.from(bytes);\n }\n}\n\n/*\n SuiJsSdkAdapter adapts IAppHelperInternalLegacy with @mysten/sui.js to IAppHelper\n TODO: build to @mysten/sui Transaction after update sdk and api\n */\nexport class SuiJsSdkAdapter implements IAppHelper<any> {\n constructor(public helper: IAppHelperInternalLegacy<any>) {}\n\n async deserialize(\n input: SuiSignTransactionBlockInput & {\n network: SuiNetworks;\n clientUrl: string;\n account: WalletAccount;\n },\n ) {\n const client = new SuiClientLegacy({ url: input.clientUrl });\n return this.helper.deserialize({ ...input, transactionBlock: input.transactionBlock, suiClient: client });\n }\n\n async build(input: {\n intentionData: any;\n txType: TransactionType;\n txSubType: string;\n clientUrl: string;\n account: WalletAccount;\n network: SuiNetworks;\n }): Promise<TransactionBlock> {\n const client = new SuiClientLegacy({ url: input.clientUrl });\n return this.helper.build({ ...input, suiClient: client });\n }\n}\n","import { TransactionType } from '@msafe/sui3-utils';\nimport { SuiClient } from '@mysten/sui.js/client';\nimport { TransactionBlock } from '@mysten/sui.js/transactions';\nimport { SuiSignTransactionBlockInput, WalletAccount } from '@mysten/wallet-standard';\n\nimport { IAppHelperInternalLegacy } from '@/apps/interface/sui-js';\n\nimport { DecoderLending } from './decoders/decoderLending';\nimport { DecoderReferral } from './decoders/decoderReferral';\nimport { DecoderVesca } from './decoders/decoderVesca';\nimport { BorrowIntention, BorrowIntentionData } from './intentions/lending/borrow';\nimport { BorrowWithBoostIntention, BorrowWithBoostIntentionData } from './intentions/lending/borrow-with-boost';\nimport {\n BorrowWithReferralIntention,\n BorrowWithReferralIntentionData,\n} from './intentions/lending/borrow-with-referral';\nimport {\n ClaimIncentiveRewardIntention,\n ClaimIncentiveRewardIntentionData,\n} from './intentions/lending/claim-incentive-reward';\nimport { DepositCollateralIntention, DepositCollateralIntentionData } from './intentions/lending/deposit-collateral';\nimport { MigrateAndClaimIntention, MigrateAndClaimIntentionData } from './intentions/lending/migrate-and-claim';\nimport { MigrateScoinIntention, MigrateScoinIntentionData } from './intentions/lending/migrate-scoin';\nimport {\n MigrateWusdcToUsdcIntention,\n MigrateWusdcToUsdcIntentionData,\n} from './intentions/lending/migrate-wusd-to-usdc';\nimport { OpenObligationIntention, OpenObligationIntentionData } from './intentions/lending/open-obligation';\nimport { RepayIntention, RepayIntentionData } from './intentions/lending/repay';\nimport { RepayWithBoostIntention, RepayWithBoostIntentionData } from './intentions/lending/repay-with-boost';\nimport { StakeSpoolIntention, StakeSpoolIntentionData } from './intentions/lending/stake-spool';\nimport { SupplyLendingIntention, SupplyLendingIntentionData } from './intentions/lending/supply-lending';\nimport { UnstakeSpoolIntention, UnstakeSpoolIntentionData } from './intentions/lending/unstake-spool';\nimport {\n WithdrawAndUnstakeLendingIntention,\n WithdrawAndUnstakeLendingIntentionData,\n} from './intentions/lending/withdraw-and-unstake-lending';\nimport { WithdrawCollateralIntention, WithdrawCollateralIntentionData } from './intentions/lending/withdraw-collateral';\nimport { WithdrawLendingIntention, WithdrawLendingIntentionData } from './intentions/lending/withdraw-lending';\nimport { BindReferralIntention, BindReferralIntentionData } from './intentions/referral/bind-referral';\nimport {\n ClaimRevenueReferralIntention,\n ClaimRevenueReferralIntentionData,\n} from './intentions/referral/claim-revenue-referral';\nimport {\n CreateReferralLinkIntention,\n CreateReferralLinkIntentionData,\n} from './intentions/referral/create-referral-link';\nimport {\n ExtendPeriodAndStakeMoreIntention,\n ExtendPeriodAndStakeMoreIntentionData,\n} from './intentions/staking/extend-period-and-stake-more';\nimport { ExtendStakePeriodIntention, ExtendStakePeriodIntentionData } from './intentions/staking/extend-stake-period';\nimport { RedeemScaIntention, RedeemScaIntentionData } from './intentions/staking/redeem-sca';\nimport {\n RenewExpStakePeriodIntention,\n RenewExpStakePeriodIntentionData,\n} from './intentions/staking/renew-exp-stake-period';\nimport { StakeScaIntention, StakeScaIntentionData } from './intentions/staking/stake-sca';\nimport {\n SupplyAndStakeLendingIntention,\n SupplyAndStakeLendingIntentionData,\n} from './intentions/staking/supply-and-stake-lending';\nimport { WithdrawStakedScaIntention, WithdrawStakedScaIntentionData } from './intentions/staking/withdraw-staked-sca';\nimport { Scallop } from './models/scallop';\nimport { SuiNetworks } from './types';\nimport { TransactionSubType } from './types/utils';\n\nexport type ScallopIntention =\n | SupplyLendingIntention\n | WithdrawLendingIntention\n | BorrowIntention\n | RepayIntention\n | DepositCollateralIntention\n | WithdrawCollateralIntention\n | OpenObligationIntention\n | StakeSpoolIntention\n | UnstakeSpoolIntention\n | ClaimIncentiveRewardIntention\n | BorrowWithBoostIntention\n | StakeScaIntention\n | ExtendStakePeriodIntention\n | ExtendPeriodAndStakeMoreIntention\n | RenewExpStakePeriodIntention\n | WithdrawStakedScaIntention\n | SupplyAndStakeLendingIntention\n | WithdrawAndUnstakeLendingIntention\n | RedeemScaIntention\n | MigrateAndClaimIntention\n | BorrowWithReferralIntention\n | CreateReferralLinkIntention\n | ClaimRevenueReferralIntention\n | BindReferralIntention\n | MigrateScoinIntention\n | RepayWithBoostIntention\n | MigrateWusdcToUsdcIntention;\n\nexport type ScallopIntentionData =\n | SupplyLendingIntentionData\n | WithdrawLendingIntentionData\n | BorrowIntentionData\n | RepayIntentionData\n | DepositCollateralIntentionData\n | WithdrawCollateralIntentionData\n | OpenObligationIntentionData\n | StakeSpoolIntentionData\n | UnstakeSpoolIntentionData\n | ClaimIncentiveRewardIntentionData\n | BorrowWithBoostIntentionData\n | StakeScaIntentionData\n | ExtendStakePeriodIntentionData\n | ExtendPeriodAndStakeMoreIntentionData\n | RenewExpStakePeriodIntentionData\n | WithdrawStakedScaIntentionData\n | SupplyAndStakeLendingIntentionData\n | WithdrawAndUnstakeLendingIntentionData\n | RedeemScaIntentionData\n | MigrateAndClaimIntentionData\n | BorrowWithReferralIntentionData\n | CreateReferralLinkIntentionData\n | ClaimRevenueReferralIntentionData\n | BindReferralIntentionData\n | MigrateScoinIntentionData\n | RepayWithBoostIntentionData\n | MigrateWusdcToUsdcIntentionData;\n\nexport class ScallopAppHelper implements IAppHelperInternalLegacy<ScallopIntentionData> {\n application = 'scallop';\n\n supportSDK = '@mysten/sui.js' as const;\n\n private scallop: Scallop | undefined;\n\n async deserialize(\n input: SuiSignTransactionBlockInput & { network: SuiNetworks; suiClient: SuiClient; account: WalletAccount },\n ): Promise<{\n txType: TransactionType;\n txSubType: TransactionSubType;\n intentionData: ScallopIntentionData;\n }> {\n if (!this.scallop) {\n this.scallop = new Scallop({\n client: input.suiClient,\n walletAddress: input.account.address,\n });\n await this.scallop.init();\n }\n\n const { transactionBlock } = input;\n console.log('transactionBlock', transactionBlock);\n const decoderLending = new DecoderLending(transactionBlock, this.scallop);\n const decoderReferral = new DecoderReferral(transactionBlock, this.scallop);\n const decoderVesca = new DecoderVesca(transactionBlock, this.scallop);\n const result = decoderLending.decode() || decoderReferral.decode() || decoderVesca.decode();\n if (!result) {\n throw new Error('Unknown transaction type');\n }\n return {\n txType: TransactionType.Other,\n txSubType: result.type,\n intentionData: result.intentionData,\n };\n }\n\n async build(input: {\n intentionData: ScallopIntentionData;\n txType: TransactionType;\n txSubType: string;\n suiClient: SuiClient;\n account: WalletAccount;\n network: SuiNetworks;\n }): Promise<TransactionBlock> {\n const { suiClient, account, network, txSubType, intentionData } = input;\n if (!this.scallop) {\n this.scallop = new Scallop({\n client: input.suiClient,\n walletAddress: input.account.address,\n });\n await this.scallop.init();\n }\n\n let intention: ScallopIntention;\n switch (txSubType) {\n case TransactionSubType.SupplyLending:\n intention = SupplyLendingIntention.fromData(intentionData as SupplyLendingIntentionData);\n break;\n case TransactionSubType.WithdrawLending:\n intention = WithdrawLendingIntention.fromData(intentionData as WithdrawLendingIntentionData);\n break;\n case TransactionSubType.Borrow:\n intention = BorrowIntention.fromData(intentionData as BorrowIntentionData);\n break;\n case TransactionSubType.Repay:\n intention = RepayIntention.fromData(intentionData as RepayIntentionData);\n break;\n case TransactionSubType.DepositCollateral:\n intention = DepositCollateralIntention.fromData(intentionData as DepositCollateralIntentionData);\n break;\n case TransactionSubType.WithdrawCollateral:\n intention = WithdrawCollateralIntention.fromData(intentionData as WithdrawCollateralIntentionData);\n break;\n case TransactionSubType.OpenObligation:\n intention = OpenObligationIntention.fromData(intentionData as OpenObligationIntentionData);\n break;\n case TransactionSubType.StakeSpool:\n intention = StakeSpoolIntention.fromData(intentionData as StakeSpoolIntentionData);\n break;\n case TransactionSubType.UnstakeSpool:\n intention = UnstakeSpoolIntention.fromData(intentionData as UnstakeSpoolIntentionData);\n break;\n case TransactionSubType.ClaimIncentiveReward:\n intention = ClaimIncentiveRewardIntention.fromData(intentionData as ClaimIncentiveRewardIntentionData);\n break;\n case TransactionSubType.BorrowWithBoost:\n intention = BorrowWithBoostIntention.fromData(intentionData as BorrowWithBoostIntentionData);\n break;\n case TransactionSubType.StakeSca:\n intention = StakeScaIntention.fromData(intentionData as StakeScaIntentionData);\n break;\n case TransactionSubType.ExtendStakePeriod:\n intention = ExtendStakePeriodIntention.fromData(intentionData as ExtendStakePeriodIntentionData);\n break;\n case TransactionSubType.ExtendPeriodAndStakeMore:\n intention = ExtendPeriodAndStakeMoreIntention.fromData(intentionData as ExtendPeriodAndStakeMoreIntentionData);\n break;\n case TransactionSubType.RenewExpStakePeriod:\n intention = RenewExpStakePeriodIntention.fromData(intentionData as RenewExpStakePeriodIntentionData);\n break;\n case TransactionSubType.WithdrawStakedSca:\n intention = WithdrawStakedScaIntention.fromData(intentionData as WithdrawStakedScaIntentionData);\n break;\n case TransactionSubType.SupplyAndStakeLending:\n intention = SupplyAndStakeLendingIntention.fromData(intentionData as SupplyAndStakeLendingIntentionData);\n break;\n case TransactionSubType.WithdrawAndUnstakeLending:\n intention = WithdrawAndUnstakeLendingIntention.fromData(\n intentionData as WithdrawAndUnstakeLendingIntentionData,\n );\n break;\n case TransactionSubType.RedeemSca:\n intention = RedeemScaIntention.fromData(intentionData as RedeemScaIntentionData);\n break;\n case TransactionSubType.MigrateAndClaim:\n intention = MigrateAndClaimIntention.fromData(intentionData as MigrateAndClaimIntentionData);\n break;\n case TransactionSubType.BorrowWithReferral:\n intention = BorrowWithReferralIntention.fromData(intentionData as BorrowWithReferralIntentionData);\n break;\n case TransactionSubType.CreateReferralLink:\n intention = CreateReferralLinkIntention.fromData(intentionData as CreateReferralLinkIntentionData);\n break;\n case TransactionSubType.ClaimRevenueReferral:\n intention = ClaimRevenueReferralIntention.fromData(intentionData as ClaimRevenueReferralIntentionData);\n break;\n case TransactionSubType.BindReferral:\n intention = BindReferralIntention.fromData(intentionData as BindReferralIntentionData);\n break;\n case TransactionSubType.MigrateScoin:\n intention = MigrateScoinIntention.fromData(intentionData as MigrateScoinIntentionData);\n break;\n case TransactionSubType.RepayWithBoost:\n intention = RepayWithBoostIntention.fromData(intentionData as RepayWithBoostIntentionData);\n break;\n case TransactionSubType.MigrateWusdcToUsdc:\n intention = MigrateWusdcToUsdcIntention.fromData(intentionData as MigrateWusdcToUsdcIntentionData);\n break;\n default:\n throw new Error('not implemented');\n }\n return intention.build({ suiClient, account, network, scallop: this.scallop });\n }\n}\n","import { TransactionType } from '@msafe/sui3-utils';\nimport { MoveCallTransaction, SplitCoinsTransaction } from '@mysten/sui.js/dist/cjs/transactions';\n\nimport { Decoder } from './decoder';\nimport { OLD_BORROW_INCENTIVE_PROTOCOL_ID } from '../constants';\nimport { SupportBorrowIncentiveRewardCoins, SupportStakeMarketCoins } from '../types';\nimport { DecodeResult, TransactionSubType } from '../types/utils';\nimport { MoveCallHelper } from '../utils/moveCallHelper';\nimport { SplitCoinHelper } from '../utils/splitCoinHelper';\n\nexport class DecoderLending extends Decoder {\n decode() {\n if (this.isMoveAsset()) {\n return this.decodeMoveAsset();\n }\n if (this.isSupplyWithStakeSpoolTransaction()) {\n return this.decodeSupplyWithStakeSpool();\n }\n if (this.isUnstakeAndWithdrawTransaction()) {\n return this.decodeUnstakeAndWithdraw();\n }\n if (this.isStakeSpoolTransaction()) {\n return this.decodeStakeSpool();\n }\n if (this.isDepositCollateralTransaction()) {\n return this.decodeDepositCollateral();\n }\n if (this.isWithdrawCollateralTransaction()) {\n return this.decodeWithdrawCollateral();\n }\n if (this.isWithdrawLendingScoinTransaction()) {\n return this.decodeWithdrawLendingScoin();\n }\n if (this.isWithdrawLendingTransaction()) {\n return this.decodeWithdrawLending();\n }\n if (this.isSupplyLendingTransaction()) {\n return this.decodeSupplyLending();\n }\n if (this.isBorrowWithReferralTransaction()) {\n return this.decodeBorrowWithReferral();\n }\n if (this.isBorrowWithBoostTransaction()) {\n return this.decodeBorrowWithBoost();\n }\n if (this.isBorrowTransaction()) {\n return this.decodeBorrow();\n }\n if (this.isRepayWithBoostTransaction()) {\n return this.decodeRepayWithBoost();\n }\n if (this.isRepayTransaction()) {\n return this.decodeRepay();\n }\n if (this.isUnstakeSpoolTransaction()) {\n return this.decodeUnstakeSpool();\n }\n if (this.isClaimRewardTransaction()) {\n return this.decodeClaimReward();\n }\n if (this.isOpenObligationTransaction()) {\n return this.decodeOpenObligation();\n }\n if (this.isMigrateAndClaim()) {\n return this.decodeMigrateAndClaim();\n }\n if (this.isMigrateScoinTransaction()) {\n return this.decodeMigrateScoin();\n }\n return undefined;\n }\n\n private isMoveAsset() {\n return !!this.getMoveCallTransaction(\n '0x5857d185897aaff40ae37b2eecc895efc1a9dff1b210c4fb894eabbce4ac2603::slippage_check::check_slippage',\n );\n }\n\n private isMigrateScoinTransaction() {\n return !!this.getMoveCallTransaction(`${this.coreId.scoin}::s_coin_converter::mint_s_coin`);\n }\n\n private isSupplyLendingTransaction() {\n return !!this.getMoveCallTransaction(`${this.coreId.protocolPkg}::mint::mint`);\n }\n\n private isSupplyWithStakeSpoolTransaction() {\n const supplyMoveCall = this.getMoveCallTransaction(`${this.coreId.protocolPkg}::mint::mint`);\n const stakeMoveCall = this.getMoveCallTransaction(`${this.coreId.spoolPkg}::user::stake`);\n return !!supplyMoveCall && !!stakeMoveCall;\n }\n\n private isUnstakeAndWithdrawTransaction() {\n const unstakeMoveCall = this.getMoveCallTransaction(`${this.coreId.spoolPkg}::user::unstake`);\n const withdrawMoveCall = this.getMoveCallTransaction(`${this.coreId.protocolPkg}::redeem::redeem`);\n return !!unstakeMoveCall && !!withdrawMoveCall;\n }\n\n private isStakeSpoolTransaction() {\n return !!this.getMoveCallTransaction(`${this.coreId.spoolPkg}::user::stake`);\n }\n\n private isWithdrawLendingTransaction() {\n return !!this.getMoveCallTransaction(`${this.coreId.protocolPkg}::redeem::redeem`);\n }\n\n private isWithdrawLendingScoinTransaction() {\n const redeem = !!this.getMoveCallTransaction(`${this.coreId.protocolPkg}::redeem::redeem`);\n const burnScoin = !!this.getMoveCallTransaction(`${this.coreId.scoin}::s_coin_converter::burn_s_coin`);\n return !!redeem && !!burnScoin;\n }\n\n private isDepositCollateralTransaction() {\n return !!this.getMoveCallTransaction(`${this.coreId.protocolPkg}::deposit_collateral::deposit_collateral`);\n }\n\n private isWithdrawCollateralTransaction() {\n return !!this.getMoveCallTransaction(`${this.coreId.protocolPkg}::withdraw_collateral::withdraw_collateral`);\n }\n\n private isBorrowTransaction() {\n return !!this.getMoveCallTransaction(`${this.coreId.protocolPkg}::borrow::borrow`);\n }\n\n private isBorrowWithBoostTransaction() {\n const borrowMoveCall = this.getMoveCallTransaction(`${this.coreId.protocolPkg}::borrow::borrow`);\n const stakeMoveCall = this.getMoveCallTransaction(`${this.coreId.borrowIncentivePkg}::user::stake_with_ve_sca`);\n return !!borrowMoveCall && !!stakeMoveCall;\n }\n\n private isBorrowWithReferralTransaction() {\n const borrowWithReferral = this.getMoveCallTransaction(`${this.coreId.protocolPkg}::borrow::borrow_with_referral`);\n return !!borrowWithReferral;\n }\n\n private isRepayTransaction() {\n return !!this.getMoveCallTransaction(`${this.coreId.protocolPkg}::repay::repay`);\n }\n\n private isRepayWithBoostTransaction() {\n const repayMoveCall = !!this.getMoveCallTransaction(`${this.coreId.protocolPkg}::repay::repay`);\n const stakeMoveCall = this.getMoveCallTransaction(`${this.coreId.borrowIncentivePkg}::user::stake_with_ve_sca`);\n return !!repayMoveCall && !!stakeMoveCall;\n }\n\n private isUnstakeSpoolTransaction() {\n return !!this.getMoveCallTransaction(`${this.coreId.spoolPkg}::user::unstake`);\n }\n\n private isCreateStakeAccountTransaction() {\n return !!this.getMoveCallTransaction(`${this.coreId.spoolPkg}::user::new_spool_account`);\n }\n\n private isClaimRewardTransaction() {\n const lendingIncentive = this.getMoveCallTransaction(`${this.coreId.spoolPkg}::user::redeem_rewards`);\n const borrowIncentiveV2 = this.getMoveCallTransaction(`${this.coreId.borrowIncentivePkg}::user::redeem_rewards`);\n return !!lendingIncentive || !!borrowIncentiveV2;\n }\n\n private isOpenObligationTransaction() {\n return !!this.getMoveCallTransaction(`${this.coreId.protocolPkg}::open_obligation::open_obligation`);\n }\n\n private isMigrateAndClaim() {\n const oldBorrowIncentive = this.getMoveCallTransaction(`${OLD_BORROW_INCENTIVE_PROTOCOL_ID}::user::redeem_rewards`);\n const stakeWithVeSca = this.getMoveCallTransaction(`${this.coreId.borrowIncentivePkg}::user::stake_with_ve_sca`);\n const stakeWithoutVesca = this.getMoveCallTransaction(`${this.coreId.borrowIncentivePkg}::user::stake`);\n return !!oldBorrowIncentive && (!!stakeWithVeSca || !!stakeWithoutVesca);\n }\n\n private get helperClaimLendingReward() {\n const moveCalls = this.transactions\n .filter(\n (trans) =>\n trans.kind === 'MoveCall' && trans.target.startsWith(`${this.coreId.spoolPkg}::user::redeem_rewards`),\n )\n .map((trans) => new MoveCallHelper(trans as MoveCallTransaction, this.txb));\n return moveCalls;\n }\n\n private get helperClaimBorrowV2Reward() {\n const moveCalls = this.transactions\n .filter(\n (trans) =>\n trans.kind === 'MoveCall' &&\n trans.target.startsWith(`${this.coreId.borrowIncentivePkg}::user::redeem_rewards`),\n )\n .map((trans) => new MoveCallHelper(trans as MoveCallTransaction, this.txb));\n return moveCalls;\n }\n\n private get helperStakeObligationWithVeSca() {\n const moveCall = this.transactions.find(\n (trans) =>\n trans.kind === 'MoveCall' &&\n trans.target.startsWith(`${this.coreId.borrowIncentivePkg}::user::stake_with_ve_sca`),\n ) as MoveCallTransaction;\n return new MoveCallHelper(moveCall, this.txb);\n }\n\n private get helperClaimBorrowReward() {\n const moveCalls = this.transactions\n .filter(\n (trans) =>\n trans.kind === 'MoveCall' &&\n trans.target.startsWith(`${OLD_BORROW_INCENTIVE_PROTOCOL_ID}::user::redeem_rewards`),\n )\n .map((trans) => new MoveCallHelper(trans as MoveCallTransaction, this.txb));\n return moveCalls;\n }\n\n private get helperMint() {\n const moveCall = this.transactions.find(\n (trans) => trans.kind === 'MoveCall' && trans.target.startsWith(`${this.coreId.protocolPkg}::mint::mint`),\n ) as MoveCallTransaction;\n return new MoveCallHelper(moveCall, this.txb);\n }\n\n private get helperUnstakes() {\n const moveCalls = this.transactions\n .filter((trans) => trans.kind === 'MoveCall' && trans.target.startsWith(`${this.coreId.spoolPkg}::user::unstake`))\n .map((trans) => new MoveCallHelper(trans as MoveCallTransaction, this.txb));\n return moveCalls;\n }\n\n private get helperRedeems() {\n const moveCalls = this.transactions\n .filter(\n (trans) => trans.kind === 'MoveCall' && trans.target.startsWith(`${this.coreId.protocolPkg}::redeem::redeem`),\n )\n .map((trans) => new MoveCallHelper(trans as MoveCallTransaction, this.txb));\n return moveCalls;\n }\n\n private get helperRedeem() {\n const moveCall = this.transactions.find(\n (trans) => trans.kind === 'MoveCall' && trans.target.startsWith(`${this.coreId.protocolPkg}::redeem::redeem`),\n ) as MoveCallTransaction;\n return new MoveCallHelper(moveCall, this.txb);\n }\n\n private get helperBurnScoin() {\n const moveCall = this.transactions.find(\n (trans) =>\n trans.kind === 'MoveCall' && trans.target.startsWith(`${this.coreId.scoin}::s_coin_converter::burn_s_coin`),\n ) as MoveCallTransaction;\n return new MoveCallHelper(moveCall, this.txb);\n }\n\n private get helperSlippage() {\n const moveCall = this.transactions.find(\n (trans) =>\n trans.kind === 'MoveCall' &&\n trans.target.startsWith(\n `0x5857d185897aaff40ae37b2eecc895efc1a9dff1b210c4fb894eabbce4ac2603::slippage_check::check_slippage`,\n ),\n ) as MoveCallTransaction;\n return new MoveCallHelper(moveCall, this.txb);\n }\n\n private get helperStake() {\n const moveCall = this.transactions.find(\n (trans) => trans.kind === 'MoveCall' && trans.target.startsWith(`${this.coreId.spoolPkg}::user::stake`),\n ) as MoveCallTransaction;\n return new MoveCallHelper(moveCall, this.txb);\n }\n\n private get helperUnstake() {\n const moveCall = this.transactions.find(\n (trans) => trans.kind === 'MoveCall' && trans.target.startsWith(`${this.coreId.spoolPkg}::user::unstake`),\n ) as MoveCallTransaction;\n return new MoveCallHelper(moveCall, this.txb);\n }\n\n private get helperDepositCollateral() {\n const moveCall = this.transactions.find(\n (trans) =>\n trans.kind === 'MoveCall' &&\n trans.target.startsWith(`${this.coreId.protocolPkg}::deposit_collateral::deposit_collateral`),\n ) as MoveCallTransaction;\n return new MoveCallHelper(moveCall, this.txb);\n }\n\n private get helperWithdrawCollateral() {\n const moveCall = this.transactions.find(\n (trans) =>\n trans.kind === 'MoveCall' &&\n trans.target.startsWith(`${this.coreId.protocolPkg}::withdraw_collateral::withdraw_collateral`),\n ) as MoveCallTransaction;\n return new MoveCallHelper(moveCall, this.txb);\n }\n\n private get helperBorrow() {\n const moveCall = this.transactions.find(\n (trans) => trans.kind === 'MoveCall' && trans.target.startsWith(`${this.coreId.protocolPkg}::borrow::borrow`),\n ) as MoveCallTransaction;\n return new MoveCallHelper(moveCall, this.txb);\n }\n\n private get helperBorrowWithReferral() {\n const moveCall = this.transactions.find(\n (trans) =>\n trans.kind === 'MoveCall' &&\n trans.target.startsWith(`${this.coreId.protocolPkg}::borrow::borrow_with_referral`),\n ) as MoveCallTransaction;\n return new MoveCallHelper(moveCall, this.txb);\n }\n\n private get helperRepay() {\n const moveCall = this.transactions.find(\n (trans) => trans.kind === 'MoveCall' && trans.target.startsWith(`${this.coreId.protocolPkg}::repay::repay`),\n ) as MoveCallTransaction;\n return new MoveCallHelper(moveCall, this.txb);\n }\n\n private decodeMigrateScoin(): DecodeResult {\n return {\n txType: TransactionType.Other,\n type: TransactionSubType.MigrateScoin,\n intentionData: {},\n };\n }\n\n private decodeMigrateAndClaim(): DecodeResult {\n let veScaKey;\n if (this.helperStakeObligationWithVeSca.moveCall) {\n veScaKey = this.helperStakeObligationWithVeSca.decodeOwnedObjectId(9);\n }\n const obligationKey = this.helperClaimBorrowReward[0].decodeOwnedObjectId(2);\n const obligationId = this.helperClaimBorrowReward[0].decodeSharedObjectId(3);\n const rewardCoinName = this.scallop.utils.parseCoinNameFromType(\n this.helperClaimBorrowReward[0].typeArg(0),\n ) as SupportBorrowIncentiveRewardCoins;\n return {\n txType: TransactionType.Other,\n type: TransactionSubType.MigrateAndClaim,\n intentionData: {\n obligationKey,\n obligationId,\n rewardCoinName,\n veScaKey,\n },\n };\n }\n\n private decodeOpenObligation(): DecodeResult {\n return {\n txType: TransactionType.Other,\n type: TransactionSubType.OpenObligation,\n intentionData: {},\n };\n }\n\n private decodeSupplyLending(): DecodeResult {\n const coinName = this.scallop.utils.parseCoinNameFromType(this.helperMint.typeArg(0));\n const amount = this.helperMint.getNestedInputParam<SplitCoinsTransaction>(2);\n const amountFromSplitCoin = new SplitCoinHelper(amount, this.txb).getAmountInput().reduce((a, b) => a + b, 0);\n return {\n txType: TransactionType.Other,\n type: TransactionSubType.SupplyLending,\n intentionData: {\n amount: amountFromSplitCoin,\n coinName,\n },\n };\n }\n\n private decodeWithdrawLending(): DecodeResult {\n const coinName = this.scallop.utils.parseCoinNameFromType(this.helperRedeem.typeArg(0));\n const amount = this.helperRedeem.getNestedInputParam<SplitCoinsTransaction>(2);\n const amountFromSplitCoin = new SplitCoinHelper(amount, this.txb).getAmountInput().reduce((a, b) => a + b, 0);\n return {\n txType: TransactionType.Other,\n type: TransactionSubType.WithdrawLending,\n intentionData: {\n amount: amountFromSplitCoin,\n coinName,\n },\n };\n }\n\n private decodeWithdrawLendingScoin(): DecodeResult {\n const coinName = this.scallop.utils.parseCoinNameFromType(this.helperRedeem.typeArg(0));\n const amount = this.helperBurnScoin.getNestedInputParam<SplitCoinsTransaction>(1);\n const amountFromSplitCoin = new SplitCoinHelper(amount, this.txb).getAmountInput().reduce((a, b) => a + b, 0);\n return {\n txType: TransactionType.Other,\n type: TransactionSubType.WithdrawLending,\n intentionData: {\n amount: amountFromSplitCoin,\n coinName,\n },\n };\n }\n\n private decodeDepositCollateral(): DecodeResult {\n const coinName = this.scallop.utils.parseCoinNameFromType(this.helperDepositCollateral.typeArg(0));\n const amount = this.helperDepositCollateral.getNestedInputParam<SplitCoinsTransaction>(3);\n const amountFromSplitCoin = new SplitCoinHelper(amount, this.txb).getAmountInput().reduce((a, b) => a + b, 0);\n const obligationId = this.helperDepositCollateral.decodeSharedObjectId(1);\n return {\n txType: TransactionType.Other,\n type: TransactionSubType.DepositCollateral,\n intentionData: {\n amount: amountFromSplitCoin,\n obligationId,\n collateralCoinName: coinName,\n },\n };\n }\n\n private decodeWithdrawCollateral(): DecodeResult {\n const coinName = this.scallop.utils.parseCoinNameFromType(this.helperWithdrawCollateral.typeArg(0));\n const amount = this.helperWithdrawCollateral.decodeInputU64(5);\n const obligationId = this.helperWithdrawCollateral.decodeSharedObjectId(1);\n const obligationKey = this.helperWithdrawCollateral.decodeOwnedObjectId(2);\n return {\n txType: TransactionType.Other,\n type: TransactionSubType.WithdrawCollateral,\n intentionData: {\n amount,\n collateralCoinName: coinName,\n obligationKey,\n obligationId,\n },\n };\n }\n\n private decodeBorrow(): DecodeResult {\n const coinName = this.scallop.utils.parseCoinNameFromType(this.helperBorrow.typeArg(0));\n const amount = this.helperBorrow.decodeInputU64(5);\n const obligationId = this.helperBorrow.decodeSharedObjectId(1);\n const obligationKey = this.helperBorrow.decodeOwnedObjectId(2);\n return {\n txType: TransactionType.Other,\n type: TransactionSubType.Borrow,\n intentionData: {\n amount,\n coinName,\n obligationKey,\n obligationId,\n },\n };\n }\n\n private decodeBorrowWithBoost(): DecodeResult {\n const coinName = this.scallop.utils.parseCoinNameFromType(this.helperBorrow.typeArg(0));\n const veScaKey = this.helperStakeObligationWithVeSca.decodeOwnedObjectId(9);\n const amount = this.helperBorrow.decodeInputU64(5);\n const obligationId = this.helperBorrow.decodeSharedObjectId(1);\n const obligationKey = this.helperBorrow.decodeOwnedObjectId(2);\n return {\n txType: TransactionType.Other,\n type: TransactionSubType.BorrowWithBoost,\n intentionData: {\n amount,\n coinName,\n obligationKey,\n obligationId,\n veScaKey,\n },\n };\n }\n\n private decodeBorrowWithReferral(): DecodeResult {\n const coinName = this.scallop.utils.parseCoinNameFromType(this.helperBorrowWithReferral.typeArg(0));\n let veScaKey;\n if (this.helperStakeObligationWithVeSca.moveCall) {\n veScaKey = this.helperStakeObligationWithVeSca.decodeOwnedObjectId(9);\n }\n const amount = this.helperBorrowWithReferral.decodeInputU64(6);\n const obligationId = this.helperBorrowWithReferral.decodeSharedObjectId(1);\n const obligationKey = this.helperBorrowWithReferral.decodeOwnedObjectId(2);\n return {\n txType: TransactionType.Other,\n type: TransactionSubType.BorrowWithReferral,\n intentionData: {\n amount,\n coinName,\n obligationKey,\n obligationId,\n veScaKey,\n },\n };\n }\n\n private decodeRepay(): DecodeResult {\n const coinName = this.scallop.utils.parseCoinNameFromType(this.helperRepay.typeArg(0));\n const amount = this.helperRepay.getNestedInputParam<SplitCoinsTransaction>(3);\n const amountFromSplitCoin = new SplitCoinHelper(amount, this.txb).getAmountInput().reduce((a, b) => a + b, 0);\n const obligationId = this.helperRepay.decodeSharedObjectId(1);\n return {\n txType: TransactionType.Other,\n type: TransactionSubType.Repay,\n intentionData: {\n amount: amountFromSplitCoin,\n obligationId,\n coinName,\n },\n };\n }\n\n private decodeRepayWithBoost(): DecodeResult {\n const coinName = this.scallop.utils.parseCoinNameFromType(this.helperRepay.typeArg(0));\n const veScaKey = this.helperStakeObligationWithVeSca.decodeOwnedObjectId(9);\n const amount = this.helperRepay.getNestedInputParam<SplitCoinsTransaction>(3);\n const amountFromSplitCoin = new SplitCoinHelper(amount, this.txb).getAmountInput().reduce((a, b) => a + b, 0);\n const obligationId = this.helperRepay.decodeSharedObjectId(1);\n return {\n txType: TransactionType.Other,\n type: TransactionSubType.RepayWithBoost,\n intentionData: {\n amount: amountFromSplitCoin,\n obligationId,\n coinName,\n veScaKey,\n },\n };\n }\n\n private decodeStakeSpool(): DecodeResult {\n let stakeSpoolAccount;\n if (!this.isCreateStakeAccountTransaction()) {\n stakeSpoolAccount = this.helperStake.decodeOwnedObjectId(1);\n }\n let amountFromSplitCoin = 0;\n if (this.helperBurnScoin.moveCall) {\n const amount = this.helperBurnScoin.getNestedInputParam<SplitCoinsTransaction>(1);\n amountFromSplitCoin = new SplitCoinHelper(amount, this.txb).getAmountInput().reduce((a, b) => a + b, 0);\n }\n if (this.helperStake.moveCall && amountFromSplitCoin === 0) {\n const amount = this.helperStake.getNestedInputParam<SplitCoinsTransaction>(2);\n amountFromSplitCoin = new SplitCoinHelper(amount, this.txb).getAmountInput().reduce((a, b) => a + b, 0);\n }\n const coinType = this.helperStake.typeArg(0);\n const coinName = this.scallop.utils.parseCoinNameFromType(coinType);\n return {\n txType: TransactionType.Other,\n type: TransactionSubType.StakeSpool,\n intentionData: {\n amount: amountFromSplitCoin,\n marketCoinName: coinName,\n stakeAccountId: stakeSpoolAccount,\n },\n };\n }\n\n private decodeUnstakeSpool(): DecodeResult {\n const stakeSpoolAccount = this.helperUnstake.decodeOwnedObjectId(1);\n const amount = this.helperUnstake.decodeInputU64(2);\n const coinType = this.helperUnstake.typeArg(0);\n const coinName = this.scallop.utils.parseCoinNameFromType(coinType);\n return {\n txType: TransactionType.Other,\n type: TransactionSubType.UnstakeSpool,\n intentionData: {\n amount,\n marketCoinName: coinName,\n stakeAccountId: stakeSpoolAccount,\n },\n };\n }\n\n private decodeSupplyWithStakeSpool(): DecodeResult {\n const coinName = this.scallop.utils.parseCoinNameFromType(this.helperMint.typeArg(0));\n const amount = this.helperMint.getNestedInputParam<SplitCoinsTransaction>(2);\n const amountFromSplitCoin = new SplitCoinHelper(amount, this.txb).getAmountInput().reduce((a, b) => a + b, 0);\n let stakeSpoolAccount;\n if (!this.isCreateStakeAccountTransaction()) {\n stakeSpoolAccount = this.helperStake.decodeOwnedObjectId(1);\n }\n return {\n txType: TransactionType.Other,\n type: TransactionSubType.SupplyAndStakeLending,\n intentionData: {\n amount: amountFromSplitCoin,\n coinName,\n stakeAccountId: stakeSpoolAccount,\n },\n };\n }\n\n private decodeUnstakeAndWithdraw(): DecodeResult {\n const stakeAccountWithAmount: { id: string; coin: number }[] = [];\n this.helperUnstakes.forEach((tx) => {\n const stakeAccountId = tx.decodeOwnedObjectId(1);\n const amount = tx.decodeInputU64(2);\n stakeAccountWithAmount.push({ id: stakeAccountId, coin: amount });\n });\n const coinName = this.scallop.utils.parseCoinNameFromType(this.helperRedeems[0].typeArg(0));\n let amountFromSplitCoin = 0;\n if (this.helperBurnScoin.moveCall) {\n const amount = this.helperBurnScoin.getNestedInputParam<SplitCoinsTransaction>(1);\n amountFromSplitCoin = new SplitCoinHelper(amount, this.txb).getAmountInput().reduce((a, b) => a + b, 0);\n }\n return {\n txType: TransactionType.Other,\n type: TransactionSubType.WithdrawAndUnstakeLending,\n intentionData: {\n amount: amountFromSplitCoin,\n coinName,\n stakeAccountId: stakeAccountWithAmount,\n },\n };\n }\n\n private decodeMoveAsset(): DecodeResult {\n const stakeAccountWithAmount: { id: string; coin: number }[] = [];\n this.helperUnstakes.forEach((tx) => {\n const stakeAccountId = tx.decodeOwnedObjectId(1);\n const amount = tx.decodeInputU64(2);\n stakeAccountWithAmount.push({ id: stakeAccountId, coin: amount });\n });\n const coinName = this.scallop.utils.parseCoinNameFromType(this.helperRedeems[0].typeArg(0));\n let amountFromSplitCoin = 0;\n if (this.helperBurnScoin.moveCall) {\n const amount = this.helperBurnScoin.getNestedInputParam<SplitCoinsTransaction>(1);\n amountFromSplitCoin = new SplitCoinHelper(amount, this.txb).getAmountInput().reduce((a, b) => a + b, 0);\n }\n const slippage = this.helperSlippage.decodePureArg(1, 'u64');\n const validSwapAmount = this.helperSlippage.decodePureArg(2, 'string');\n\n return {\n txType: TransactionType.Other,\n type: TransactionSubType.MigrateWusdcToUsdc,\n intentionData: {\n amount: amountFromSplitCoin,\n coinName,\n slippage,\n validSwapAmount,\n stakeAccountId: stakeAccountWithAmount,\n },\n };\n }\n\n private decodeClaimReward(): DecodeResult {\n const lendingReward: {\n stakeMarketCoinName: SupportStakeMarketCoins;\n stakeAccountId: string;\n }[] = [];\n const borrowRewardV2: {\n obligationId: string;\n obligationKey: string;\n rewardCoinName: SupportBorrowIncentiveRewardCoins;\n }[] = [];\n\n const borrowReward: {\n obligationId: string;\n obligationKey: string;\n rewardCoinName: SupportBorrowIncentiveRewardCoins;\n }[] = [];\n\n this.helperClaimLendingReward.forEach((tx) => {\n const stakeAccountId = tx.decodeOwnedObjectId(2);\n const stakeMarketCoinName = tx.typeArg(0);\n const coinName = this.scallop.utils.parseCoinNameFromType(stakeMarketCoinName);\n lendingReward.push({ stakeMarketCoinName: coinName as SupportStakeMarketCoins, stakeAccountId });\n });\n\n this.helperClaimBorrowV2Reward.forEach((tx) => {\n const obligationKey = tx.decodeSharedObjectId(3);\n const obligationId = tx.decodeOwnedObjectId(4);\n const rewardCoinName = this.scallop.utils.parseCoinNameFromType(\n tx.typeArg(0),\n ) as SupportBorrowIncentiveRewardCoins;\n borrowRewardV2.push({ obligationId, obligationKey, rewardCoinName });\n });\n\n this.helperClaimBorrowReward.forEach((tx) => {\n const obligationKey = tx.decodeSharedObjectId(2);\n const obligationId = tx.decodeOwnedObjectId(3);\n const rewardCoinName = this.scallop.utils.parseCoinNameFromType(\n tx.typeArg(0),\n ) as SupportBorrowIncentiveRewardCoins;\n borrowReward.push({ obligationId, obligationKey, rewardCoinName });\n });\n\n return {\n txType: TransactionType.Other,\n type: TransactionSubType.ClaimIncentiveReward,\n intentionData: {\n lendingIncentive: lendingReward,\n borrowIncentiveV2: borrowRewardV2,\n borrowIncentive: borrowReward,\n },\n };\n }\n}\n","import { TransactionBlock } from '@mysten/sui.js/dist/cjs/transactions';\n\nimport { Scallop } from '../models';\n\nexport class Decoder {\n protected scallop: Scallop;\n\n constructor(\n public readonly txb: TransactionBlock,\n scallop: Scallop,\n ) {\n this.scallop = scallop;\n }\n\n protected get coreId() {\n return {\n protocolPkg: this.scallop.address.get('core.packages.protocol.id'),\n market: this.scallop.address.get('core.market'),\n version: this.scallop.address.get('core.version'),\n coinDecimalsRegistry: this.scallop.address.get('core.coinDecimalsRegistry'),\n xOracle: this.scallop.address.get('core.oracles.xOracle'),\n spoolPkg: this.scallop.address.get('spool.id'),\n borrowIncentivePkg: this.scallop.address.get('borrowIncentive.id'),\n veScaPkgId: this.scallop.address.get('vesca.id'),\n scoin: this.scallop.address.get('scoin.id'),\n referral: this.scallop.address.get('referral.id'),\n };\n }\n\n protected get transactions() {\n return this.txb.blockData.transactions;\n }\n\n protected get inputTransaction() {\n return this.txb.blockData.inputs;\n }\n\n protected getMoveCallTransaction(target: string) {\n return this.transactions.find((trans) => trans.kind === 'MoveCall' && trans.target === target);\n }\n}\n","// export const API_BASE_URL = 'https://sui.api.scallop.io';\nexport const API_BASE_URL = 'https://sui.apis.scallop.io';\nexport const SDK_API_BASE_URL = 'https://sdk.api.scallop.io';\n\nexport const IS_VE_SCA_TEST = false;\nexport const USE_TEST_ADDRESS = false;\n\n// export const ADDRESSES_ID = '';\nexport const ADDRESSES_ID =\n IS_VE_SCA_TEST || USE_TEST_ADDRESS ? ('65fb07c39c845425d71d7b18' as const) : ('66f8e7ed9bb9e07fdfb86bbb' as const);\n// : ('6601955b8b0024600a917079' as const);\n// : ('6462a088a7ace142bb6d7e9b' as const);\n\nexport const PROTOCOL_OBJECT_ID = IS_VE_SCA_TEST\n ? ('0xc9f859f98ca352a11b97a038c4b4162bee437b8df8caa047990fe9cb03d4f778' as const)\n : ('0xefe8b36d5b2e43728cc323298626b83177803521d195cfb11e15b910e892fddf' as const);\n// export const PROTOCOL_OBJECT_ID =\n// '0x87ddec2984645dbbe2403a509cc6edf393a43acdba9b77d45da2bcbefcf733c1' as const;\n\nexport const BORROW_FEE_PROTOCOL_ID = IS_VE_SCA_TEST\n ? ('0xc9f859f98ca352a11b97a038c4b4162bee437b8df8caa047990fe9cb03d4f778' as const) // test environment\n : ('0xc38f849e81cfe46d4e4320f508ea7dda42934a329d5a6571bb4c3cb6ea63f5da' as const);\n// export const BORROW_FEE_PROTOCOL_ID =\n// '0x87ddec2984645dbbe2403a509cc6edf393a43acdba9b77d45da2bcbefcf733c1' as const;\n\nexport const SCA_COIN_TYPE = IS_VE_SCA_TEST\n ? (`0x6cd813061a3adf3602b76545f076205f0c8e7ec1d3b1eab9a1da7992c18c0524::sca::SCA` as const)\n : ('0x7016aae72cfc67f2fadf55769c0a7dd54291a583b63051a5ed71081cce836ac6::sca::SCA' as const);\n\nexport const OLD_BORROW_INCENTIVE_PROTOCOL_ID =\n '0xc63072e7f5f4983a2efaf5bdba1480d5e7d74d57948e1c7cc436f8e22cbeb410' as const;\n\nexport const SUPPORT_POOLS = [\n 'weth',\n 'wbtc',\n 'wusdc',\n 'wusdt',\n 'sui',\n 'wapt',\n 'wsol',\n 'cetus',\n 'afsui',\n 'hasui',\n 'vsui',\n 'sca',\n 'usdc',\n] as const;\n\nexport const SUPPORT_COLLATERALS = [\n 'weth',\n 'wbtc',\n 'wusdc',\n 'wusdt',\n 'sui',\n 'wapt',\n 'wsol',\n 'cetus',\n 'afsui',\n 'hasui',\n 'vsui',\n 'sca',\n 'usdc',\n] as const;\n\nexport const SUPPORT_SPOOLS = [\n 'sweth',\n 'ssui',\n 'swusdc',\n 'swusdt',\n 'scetus',\n 'safsui',\n 'shasui',\n 'svsui',\n 'susdc',\n] as const;\n\nexport const SUPPORT_SCOIN = [\n 'ssui',\n 'swusdc',\n 'swusdt',\n 'safsui',\n 'shasui',\n 'svsui',\n 'sweth',\n 'ssca',\n 'scetus',\n 'swbtc',\n 'swsol',\n 'susdc',\n] as const;\n\nexport const UNSUPPORT_SCOIN = ['btc', 'sol'] as const;\n\nexport const SUPPORT_SPOOLS_REWARDS = ['sui'] as const;\n\nexport const SUPPORT_BORROW_INCENTIVE_POOLS = [\n 'sui',\n 'wusdc',\n 'wusdt',\n 'afsui',\n 'hasui',\n 'vsui',\n 'weth',\n 'sca',\n 'wbtc',\n 'wsol',\n 'usdc',\n] as const;\n\nexport const SUPPORT_BORROW_INCENTIVE_REWARDS = ['sui', 'sca'] as const;\nexport const SUPPORT_ORACLES = ['supra', 'switchboard', 'pyth'] as const;\n\nexport const SUPPORT_PACKAGES = [\n 'coinDecimalsRegistry',\n 'math',\n 'whitelist',\n 'x',\n 'protocol',\n 'protocolWhitelist',\n 'query',\n 'supra',\n 'pyth',\n 'switchboard',\n 'xOracle',\n 'testCoin',\n] as const;\n","import type {\n SupportCoinDecimals,\n AssetCoins,\n MarketCoins,\n StakeMarketCoins,\n StakeRewardCoins,\n BorrowIncentiveRewardCoins,\n AssetCoinIds,\n WormholeCoinIds,\n VoloCoinIds,\n SCoinIds,\n} from '../types';\n\nexport const coinDecimals: SupportCoinDecimals = {\n weth: 8,\n wbtc: 8,\n wusdc: 6,\n usdc: 6,\n wusdt: 6,\n sui: 9,\n wapt: 8,\n wsol: 8,\n sca: 9,\n cetus: 9,\n afsui: 9,\n hasui: 9,\n vsui: 9,\n sweth: 8,\n swbtc: 8,\n susdc: 6,\n swusdt: 6,\n swusdc: 6,\n ssui: 9,\n swapt: 8,\n swsol: 8,\n scetus: 9,\n safsui: 9,\n shasui: 9,\n svsui: 9,\n ssca: 9,\n};\n\nexport const assetCoins: AssetCoins = {\n weth: 'weth',\n wbtc: 'wbtc',\n wusdc: 'wusdc',\n usdc: 'usdc',\n wusdt: 'wusdt',\n sui: 'sui',\n wapt: 'wapt',\n wsol: 'wsol',\n cetus: 'cetus',\n afsui: 'afsui',\n hasui: 'hasui',\n vsui: 'vsui',\n sca: 'sca',\n};\n\nexport const marketCoins: MarketCoins = {\n sweth: 'sweth',\n swbtc: 'swbtc',\n swusdc: 'swusdc',\n swusdt: 'swusdt',\n ssui: 'ssui',\n swapt: 'swapt',\n swsol: 'swsol',\n scetus: 'scetus',\n safsui: 'safsui',\n shasui: 'shasui',\n svsui: 'svsui',\n ssca: 'ssca',\n susdc: 'susdc',\n};\n\nexport const stakeMarketCoins: StakeMarketCoins = {\n sweth: 'sweth',\n ssui: 'ssui',\n susdc: 'susdc',\n swusdt: 'swusdt',\n swusdc: 'swusdc',\n scetus: 'scetus',\n safsui: 'safsui',\n shasui: 'shasui',\n svsui: 'svsui',\n};\n\nexport const spoolRewardCoins: StakeRewardCoins = {\n sweth: 'sui',\n ssui: 'sui',\n swusdc: 'sui',\n swusdt: 'sui',\n scetus: 'sui',\n safsui: 'sui',\n shasui: 'sui',\n svsui: 'sui',\n susdc: 'sui',\n};\n\nexport const borrowIncentiveRewardCoins: BorrowIncentiveRewardCoins = {\n sui: ['sui', 'sca'],\n wusdc: ['sui', 'sca'],\n wusdt: ['sui', 'sca'],\n afsui: ['sui', 'sca'],\n hasui: ['sui', 'sca'],\n vsui: ['sui', 'sca'],\n sca: ['sui', 'sca'],\n weth: ['sui', 'sca'],\n wbtc: ['sui', 'sca'],\n wsol: ['sui', 'sca'],\n usdc: ['sui', 'sca'],\n};\n\nexport const coinIds: AssetCoinIds = {\n sui: '0x0000000000000000000000000000000000000000000000000000000000000002',\n weth: '0xaf8cd5edc19c4512f4259f0bee101a40d41ebed738ade5874359610ef8eeced5',\n wbtc: '0x027792d9fed7f9844eb4839566001bb6f6cb4804f66aa2da6fe1ee242d896881',\n wusdc: '0x5d4b302506645c37ff133b98c4b50a5ae14841659738d6d733d59d0d217a93bf',\n wusdt: '0xc060006111016b8a020ad5b33834984a437aaa7d3c74c18e09a95d48aceab08c',\n wapt: '0x3a5143bb1196e3bcdfab6203d1683ae29edd26294fc8bfeafe4aaa9d2704df37',\n wsol: '0xb7844e289a8410e50fb3ca48d69eb9cf29e27d223ef90353fe1bd8e27ff8f3f8',\n cetus: '0x06864a6f921804860930db6ddbe2e16acdf8504495ea7481637a1c8b9a8fe54b',\n afsui: '0xf325ce1300e8dac124071d3152c5c5ee6174914f8bc2161e88329cf579246efc',\n hasui: '0xbde4ba4c2e274a60ce15c1cfff9e5c42e41654ac8b6d906a57efa4bd3c29f47d',\n vsui: '0x549e8b69270defbfafd4f94e17ec44cdbdd99820b33bda2278dea3b9a32d3f55',\n sca: '0x7016aae72cfc67f2fadf55769c0a7dd54291a583b63051a5ed71081cce836ac6',\n usdc: '0xdba34672e30cb065b1f93e3ab55318768fd6fef66c15942c9f7cb846e2f900e7',\n};\n\nexport const wormholeCoinIds: WormholeCoinIds = {\n weth: '0xaf8cd5edc19c4512f4259f0bee101a40d41ebed738ade5874359610ef8eeced5',\n wbtc: '0x027792d9fed7f9844eb4839566001bb6f6cb4804f66aa2da6fe1ee242d896881',\n wusdc: '0x5d4b302506645c37ff133b98c4b50a5ae14841659738d6d733d59d0d217a93bf',\n wusdt: '0xc060006111016b8a020ad5b33834984a437aaa7d3c74c18e09a95d48aceab08c',\n wapt: '0x3a5143bb1196e3bcdfab6203d1683ae29edd26294fc8bfeafe4aaa9d2704df37',\n wsol: '0xb7844e289a8410e50fb3ca48d69eb9cf29e27d223ef90353fe1bd8e27ff8f3f8',\n};\n\nexport const voloCoinIds: VoloCoinIds = {\n vsui: '0x549e8b69270defbfafd4f94e17ec44cdbdd99820b33bda2278dea3b9a32d3f55',\n};\n\n// PROD VERSION\nexport const sCoinIds: SCoinIds = {\n ssui: '0xaafc4f740de0dd0dde642a31148fb94517087052f19afb0f7bed1dc41a50c77b::scallop_sui::SCALLOP_SUI',\n scetus: '0xea346ce428f91ab007210443efcea5f5cdbbb3aae7e9affc0ca93f9203c31f0c::scallop_cetus::SCALLOP_CETUS',\n ssca: '0x5ca17430c1d046fae9edeaa8fd76c7b4193a00d764a0ecfa9418d733ad27bc1e::scallop_sca::SCALLOP_SCA',\n swusdc:\n '0xad4d71551d31092230db1fd482008ea42867dbf27b286e9c70a79d2a6191d58d::scallop_wormhole_usdc::SCALLOP_WORMHOLE_USDC',\n swusdt:\n '0xe6e5a012ec20a49a3d1d57bd2b67140b96cd4d3400b9d79e541f7bdbab661f95::scallop_wormhole_usdt::SCALLOP_WORMHOLE_USDT',\n sweth:\n '0x67540ceb850d418679e69f1fb6b2093d6df78a2a699ffc733f7646096d552e9b::scallop_wormhole_eth::SCALLOP_WORMHOLE_ETH',\n safsui: '0x00671b1fa2a124f5be8bdae8b91ee711462c5d9e31bda232e70fd9607b523c88::scallop_af_sui::SCALLOP_AF_SUI',\n shasui: '0x9a2376943f7d22f88087c259c5889925f332ca4347e669dc37d54c2bf651af3c::scallop_ha_sui::SCALLOP_HA_SUI',\n svsui: '0xe1a1cc6bcf0001a015eab84bcc6713393ce20535f55b8b6f35c142e057a25fbe::scallop_v_sui::SCALLOP_V_SUI',\n swbtc:\n '0x2cf76a9cf5d3337961d1154283234f94da2dcff18544dfe5cbdef65f319591b5::scallop_wormhole_btc::SCALLOP_WORMHOLE_BTC',\n swsol:\n '0x1392650f2eca9e3f6ffae3ff89e42a3590d7102b80e2b430f674730bc30d3259::scallop_wormhole_sol::SCALLOP_WORMHOLE_SOL',\n susdc: '0x854950aa624b1df59fe64e630b2ba7c550642e9342267a33061d59fb31582da5::scallop_usdc::SCALLOP_USDC',\n} as const;\n","import { bcs } from '@mysten/sui.js/bcs';\nimport { MoveCallTransaction, TransactionBlock, TransactionBlockInput } from '@mysten/sui.js/dist/cjs/transactions';\nimport { normalizeStructTag, normalizeSuiAddress } from '@mysten/sui.js/utils';\n\nexport class MoveCallHelper {\n constructor(\n public readonly moveCall: MoveCallTransaction,\n public readonly txb: TransactionBlock,\n ) {}\n\n decodeSharedObjectId(argIndex: number) {\n const input = this.getInputParam(argIndex);\n return MoveCallHelper.getSharedObjectId(input);\n }\n\n decodeOwnedObjectId(argIndex: number) {\n const input = this.getInputParam(argIndex);\n return MoveCallHelper.getOwnedObjectId(input);\n }\n\n decodeInputU64(argIndex: number) {\n const strVal = this.decodePureArg<string>(argIndex, 'u64');\n return Number(strVal);\n }\n\n decodeInputU8(argIndex: number) {\n const strVal = this.decodePureArg<string>(argIndex, 'u8');\n return Number(strVal);\n }\n\n decodeInputAddress(argIndex: number) {\n const input = this.decodePureArg<string>(argIndex, 'address');\n return normalizeSuiAddress(input);\n }\n\n decodeInputString(argIndex: number) {\n return this.decodePureArg<string>(argIndex, 'string');\n }\n\n decodeInputBool(argIndex: number) {\n return this.decodePureArg<boolean>(argIndex, 'bool');\n }\n\n decodePureArg<T>(argIndex: number, bcsType: string) {\n const input = this.getInputParam(argIndex);\n return MoveCallHelper.getPureInputValue<T>(input, bcsType);\n }\n\n getInputParam(argIndex: number) {\n const arg = this.moveCall.arguments[argIndex];\n if (arg.kind !== 'Input') {\n throw new Error('not input type');\n }\n return this.txb.blockData.inputs[arg.index];\n }\n\n getNestedInputParam<T>(argIndex: number) {\n const arg = this.moveCall.arguments[argIndex];\n if (arg.kind !== 'NestedResult') {\n throw new Error('not input type');\n }\n return this.txb.blockData.transactions[arg.index] as T;\n }\n\n isHaveNestedInput(argIndex: number) {\n const arg = this.moveCall.arguments[argIndex];\n return arg.kind === 'NestedResult';\n }\n\n static getPureInputValue<T>(input: TransactionBlockInput, bcsType: string) {\n if (input.type !== 'pure') {\n throw new Error('not pure argument');\n }\n if (typeof input.value === 'object' && 'Pure' in input.value) {\n const bcsNums = input.value.Pure;\n return bcs.de(bcsType, new Uint8Array(bcsNums)) as T;\n }\n return input.value as T;\n }\n\n static getOwnedObjectId(input: TransactionBlockInput) {\n if (input.type !== 'object') {\n throw new Error(`not object argument: ${JSON.stringify(input)}`);\n }\n if (typeof input.value === 'object') {\n if (!('Object' in input.value) || !('ImmOrOwned' in input.value.Object)) {\n throw new Error('not ImmOrOwned');\n }\n return normalizeSuiAddress(input.value.Object.ImmOrOwned.objectId as string);\n }\n return normalizeSuiAddress(input.value as string);\n }\n\n static getSharedObjectId(input: TransactionBlockInput) {\n if (input.type !== 'object') {\n throw new Error(`not object argument: ${JSON.stringify(input)}`);\n }\n if (typeof input.value !== 'object') {\n return normalizeSuiAddress(input.value as string);\n }\n if (!('Object' in input.value) || !('Shared' in input.value.Object)) {\n throw new Error('not Shared');\n }\n return normalizeSuiAddress(input.value.Object.Shared.objectId as string);\n }\n\n static getPureInput<T>(input: TransactionBlockInput, bcsType: string) {\n if (input.type !== 'pure') {\n throw new Error('not pure argument');\n }\n if (typeof input.value !== 'object') {\n return input.value as T;\n }\n if (!('Pure' in input.value)) {\n throw new Error('Pure not in value');\n }\n const bcsVal = input.value.Pure;\n return bcs.de(bcsType, new Uint8Array(bcsVal)) as T;\n }\n\n typeArg(index: number) {\n return normalizeStructTag(this.moveCall.typeArguments[index]);\n }\n\n txArg(index: number) {\n return this.moveCall.arguments[index];\n }\n}\n","import { bcs } from '@mysten/sui.js/bcs';\nimport { SplitCoinsTransaction, TransactionBlock, TransactionBlockInput } from '@mysten/sui.js/dist/cjs/transactions';\n\nimport { MoveCallHelper } from './moveCallHelper';\n\nexport class SplitCoinHelper {\n constructor(\n public readonly splitCoin: SplitCoinsTransaction,\n public readonly txb: TransactionBlock,\n ) {}\n\n getAmountInput() {\n return this.splitCoin.amounts\n .map((input) => {\n if (input.kind === 'Input') {\n return Number(MoveCallHelper.getPureInputValue<number>(input, 'u64'));\n }\n return undefined;\n })\n .filter((input) => input !== undefined);\n }\n\n static getPureInputValue<T>(input: TransactionBlockInput, bcsType: string) {\n if (input.type !== 'pure') {\n throw new Error('not pure argument');\n }\n if (typeof input.value === 'object' && 'Pure' in input.value) {\n const bcsNums = input.value.Pure;\n return bcs.de(bcsType, new Uint8Array(bcsNums)) as T;\n }\n return input.value as T;\n }\n}\n","import { TransactionType } from '@msafe/sui3-utils';\nimport { MoveCallTransaction } from '@mysten/sui.js/dist/cjs/transactions';\n\nimport { Decoder } from './decoder';\nimport { DecodeResult } from '../types';\nimport { TransactionSubType } from '../types/utils';\nimport { MoveCallHelper } from '../utils/moveCallHelper';\n\nexport class DecoderReferral extends Decoder {\n decode() {\n if (this.isCreateReferralLink()) {\n return this.decodeCreateReferralLink();\n }\n if (this.isClaimRevenueReferral()) {\n return this.decodeClaimRevenueReferral();\n }\n if (this.isBindReferral()) {\n return this.decodeBindReferral();\n }\n return undefined;\n }\n\n private isClaimRevenueReferral() {\n return !!this.getMoveCallTransaction(\n `${this.coreId.referral}::referral_revenue_pool::claim_revenue_with_ve_sca_key`,\n );\n }\n\n private isCreateReferralLink() {\n return !!this.getMoveCallTransaction(`${this.coreId.veScaPkgId}::ve_sca::mint_ve_sca_placeholder_key`);\n }\n\n private isBindReferral() {\n return !!this.getMoveCallTransaction(`${this.coreId.referral}::referral_bindings::bind_ve_sca_referrer`);\n }\n\n private get helperClaimRevenueReferral() {\n const moveCalls = this.transactions\n .filter(\n (trans) =>\n trans.kind === 'MoveCall' &&\n trans.target.startsWith(`${this.coreId.referral}::referral_revenue_pool::claim_revenue_with_ve_sca_key`),\n )\n .map((trans) => new MoveCallHelper(trans as MoveCallTransaction, this.txb));\n return moveCalls;\n }\n\n private get helperBindReferral() {\n const moveCall = this.transactions.find(\n (trans) =>\n trans.kind === 'MoveCall' &&\n trans.target.startsWith(`${this.coreId.referral}::referral_bindings::bind_ve_sca_referrer`),\n ) as MoveCallTransaction;\n return new MoveCallHelper(moveCall, this.txb);\n }\n\n private decodeCreateReferralLink(): DecodeResult {\n return {\n txType: TransactionType.Other,\n type: TransactionSubType.CreateReferralLink,\n intentionData: {},\n };\n }\n\n private decodeClaimRevenueReferral(): DecodeResult {\n const veScaKey = this.helperClaimRevenueReferral[0].decodeOwnedObjectId(2);\n const coins = this.helperClaimRevenueReferral.map((helper) => helper.typeArg(0));\n return {\n txType: TransactionType.Other,\n type: TransactionSubType.ClaimRevenueReferral,\n intentionData: {\n veScaKey,\n coins,\n },\n };\n }\n\n private decodeBindReferral(): DecodeResult {\n const veScaKey = this.helperBindReferral.decodePureArg(1, 'address');\n return {\n txType: TransactionType.Other,\n type: TransactionSubType.BindReferral,\n intentionData: {\n veScaKey,\n },\n };\n }\n}\n","import { TransactionType } from '@msafe/sui3-utils';\nimport { MoveCallTransaction, SplitCoinsTransaction } from '@mysten/sui.js/dist/cjs/transactions';\n\nimport { Decoder } from './decoder';\nimport { OLD_BORROW_INCENTIVE_PROTOCOL_ID } from '../constants';\nimport { DecodeResult } from '../types';\nimport { TransactionSubType } from '../types/utils';\nimport { MoveCallHelper } from '../utils/moveCallHelper';\nimport { SplitCoinHelper } from '../utils/splitCoinHelper';\n\nexport class DecoderVesca extends Decoder {\n decode() {\n if (this.isExtendPeriodAndStakeMoreSca()) {\n return this.decodePeriodAndStakeMoreSca();\n }\n if (this.isStakeScaFirsTime() || this.isStakeMoreSca()) {\n return this.decodeStakeSca();\n }\n if (this.isRenewExpiredVeSca()) {\n return this.decodeRenewExpiredVeSca();\n }\n if (this.isExtendPeriod()) {\n return this.decodeExtendStakePeriod();\n }\n if (this.isRedeemSca()) {\n return this.decodeRedeemSca();\n }\n return undefined;\n }\n\n private isStakeScaFirsTime() {\n return !!this.getMoveCallTransaction(`${this.coreId.veScaPkgId}::ve_sca::mint_ve_sca_key`);\n }\n\n private isExtendPeriodAndStakeMoreSca() {\n const extendPeriod = this.getMoveCallTransaction(`${this.coreId.veScaPkgId}::ve_sca::extend_lock_period`);\n const stakeMoreSca = this.getMoveCallTransaction(`${this.coreId.veScaPkgId}::ve_sca::lock_more_sca`);\n return !!extendPeriod && !!stakeMoreSca;\n }\n\n private isRedeemSca() {\n return !!this.getMoveCallTransaction(`${this.coreId.veScaPkgId}::ve_sca::redeem`);\n }\n\n private isStakeMoreSca() {\n return !!this.getMoveCallTransaction(`${this.coreId.veScaPkgId}::ve_sca::lock_more_sca`);\n }\n\n private isExtendPeriod() {\n return !!this.getMoveCallTransaction(`${this.coreId.veScaPkgId}::ve_sca::extend_lock_period`);\n }\n\n private isRenewExpiredVeSca() {\n return !!this.getMoveCallTransaction(`${this.coreId.veScaPkgId}::ve_sca::renew_expired_ve_sca`);\n }\n\n private get helperStakeMoreSca() {\n const moveCall = this.transactions.find(\n (trans) =>\n trans.kind === 'MoveCall' && trans.target.startsWith(`${this.coreId.veScaPkgId}::ve_sca::lock_more_sca`),\n ) as MoveCallTransaction;\n return new MoveCallHelper(moveCall, this.txb);\n }\n\n private get helperStakeSca() {\n const moveCall = this.transactions.find(\n (trans) =>\n trans.kind === 'MoveCall' && trans.target.startsWith(`${this.coreId.veScaPkgId}::ve_sca::mint_ve_sca_key`),\n ) as MoveCallTransaction;\n return new MoveCallHelper(moveCall, this.txb);\n }\n\n private get helperExtendStakePeriod() {\n const moveCall = this.transactions.find(\n (trans) =>\n trans.kind === 'MoveCall' && trans.target.startsWith(`${this.coreId.veScaPkgId}::ve_sca::extend_lock_period`),\n ) as MoveCallTransaction;\n return new MoveCallHelper(moveCall, this.txb);\n }\n\n private get helperRedeemSca() {\n const moveCall = this.transactions.find(\n (trans) => trans.kind === 'MoveCall' && trans.target.startsWith(`${this.coreId.veScaPkgId}::ve_sca::redeem`),\n ) as MoveCallTransaction;\n return new MoveCallHelper(moveCall, this.txb);\n }\n\n private get helperRenewExpired() {\n const moveCall = this.transactions.find(\n (trans) =>\n trans.kind === 'MoveCall' && trans.target.startsWith(`${this.coreId.veScaPkgId}::ve_sca::renew_expired_ve_sca`),\n ) as MoveCallTransaction;\n return new MoveCallHelper(moveCall, this.txb);\n }\n\n private get helperOldUnstakeObligation() {\n const moveCall = this.transactions.find(\n (trans) =>\n trans.kind === 'MoveCall' && trans.target.startsWith(`${OLD_BORROW_INCENTIVE_PROTOCOL_ID}::user::unstake`),\n ) as MoveCallTransaction;\n return new MoveCallHelper(moveCall, this.txb);\n }\n\n private get helperUnstakeObligation() {\n const moveCall = this.transactions.find(\n (trans) =>\n trans.kind === 'MoveCall' && trans.target.startsWith(`${this.coreId.borrowIncentivePkg}::user::unstake`),\n ) as MoveCallTransaction;\n return new MoveCallHelper(moveCall, this.txb);\n }\n\n private get helperStakeObligationWithVeSca() {\n const moveCall = this.transactions.find(\n (trans) =>\n trans.kind === 'MoveCall' &&\n trans.target.startsWith(`${this.coreId.borrowIncentivePkg}::user::stake_with_ve_sca`),\n ) as MoveCallTransaction;\n return new MoveCallHelper(moveCall, this.txb);\n }\n\n private decodeRedeemSca(): DecodeResult {\n const veScaKey = this.helperRedeemSca.decodeOwnedObjectId(1);\n return {\n txType: TransactionType.Other,\n type: TransactionSubType.RedeemSca,\n intentionData: {\n veScaKey,\n },\n };\n }\n\n private decodeRenewExpiredVeSca(): DecodeResult {\n const lockSca = this.helperRenewExpired.getNestedInputParam<SplitCoinsTransaction>(4);\n const unlockTime = this.helperRenewExpired.decodeInputU64(5);\n const amountFromSplitCoin = new SplitCoinHelper(lockSca, this.txb).getAmountInput().reduce((a, b) => a + b, 0);\n const veScaKey = this.helperRenewExpired.decodeOwnedObjectId(1);\n const isHaveRedeem = !!this.helperRedeemSca.moveCall;\n let oldUnstakeObligation: string[] = [];\n let unstakeObligation: string[] = [];\n let stakeObligation: string[] = [];\n if (this.helperOldUnstakeObligation.moveCall) {\n oldUnstakeObligation = [\n this.helperOldUnstakeObligation.decodeSharedObjectId(2), // Obligation key\n this.helperOldUnstakeObligation.decodeSharedObjectId(3), // Obligation Id\n ];\n }\n if (this.helperUnstakeObligation.moveCall) {\n unstakeObligation = [\n this.helperUnstakeObligation.decodeSharedObjectId(3), // Obligation key\n this.helperUnstakeObligation.decodeSharedObjectId(4), // Obligation Id\n ];\n }\n if (this.helperStakeObligationWithVeSca.moveCall) {\n stakeObligation = [\n this.helperStakeObligationWithVeSca.decodeSharedObjectId(3), // Obligation key\n this.helperStakeObligationWithVeSca.decodeSharedObjectId(4), // Obligation Id\n ];\n }\n let isObligationLocked = false;\n let isOldBorrowIncentive = false;\n let obligationId;\n let obligationKey;\n\n const operations = [\n { condition: oldUnstakeObligation, isOld: true },\n { condition: unstakeObligation, isOld: false },\n { condition: stakeObligation, isOld: false },\n ];\n\n for (let i = 0; i < operations.length; i++) {\n if (operations[i].condition.length > 1) {\n [obligationKey, obligationId] = operations[i].condition;\n isObligationLocked = true;\n isOldBorrowIncentive = operations[i].isOld;\n }\n }\n return {\n txType: TransactionType.Other,\n type: TransactionSubType.RenewExpStakePeriod,\n intentionData: {\n amount: amountFromSplitCoin,\n lockPeriodInDays: unlockTime,\n obligationId,\n obligationKey,\n veScaKey,\n isHaveRedeem,\n isObligationLocked,\n isOldBorrowIncentive,\n },\n };\n }\n\n private decodeExtendStakePeriod(): DecodeResult {\n const unlockTime = this.helperExtendStakePeriod.decodeInputU64(4);\n const veScaKey = this.helperExtendStakePeriod.decodeOwnedObjectId(1);\n let oldUnstakeObligation: string[] = [];\n let unstakeObligation: string[] = [];\n let stakeObligation: string[] = [];\n if (this.helperOldUnstakeObligation.moveCall) {\n oldUnstakeObligation = [\n this.helperOldUnstakeObligation.decodeSharedObjectId(2), // Obligation key\n this.helperOldUnstakeObligation.decodeSharedObjectId(3), // Obligation Id\n ];\n }\n if (this.helperUnstakeObligation.moveCall) {\n unstakeObligation = [\n this.helperUnstakeObligation.decodeSharedObjectId(3), // Obligation key\n this.helperUnstakeObligation.decodeSharedObjectId(4), // Obligation Id\n ];\n }\n if (this.helperStakeObligationWithVeSca.moveCall) {\n stakeObligation = [\n this.helperStakeObligationWithVeSca.decodeSharedObjectId(3), // Obligation key\n this.helperStakeObligationWithVeSca.decodeSharedObjectId(4), // Obligation Id\n ];\n }\n let isObligationLocked = false;\n let isOldBorrowIncentive = false;\n let obligationId;\n let obligationKey;\n\n const operations = [\n { condition: oldUnstakeObligation, isOld: true },\n { condition: unstakeObligation, isOld: false },\n { condition: stakeObligation, isOld: false },\n ];\n\n for (let i = 0; i < operations.length; i++) {\n if (operations[i].condition.length > 1) {\n [obligationKey, obligationId] = operations[i].condition;\n isObligationLocked = true;\n isOldBorrowIncentive = operations[i].isOld;\n }\n }\n return {\n txType: TransactionType.Other,\n type: TransactionSubType.ExtendStakePeriod,\n intentionData: {\n lockPeriodInDays: unlockTime,\n obligationId,\n obligationKey,\n veScaKey,\n isObligationLocked,\n isOldBorrowIncentive,\n },\n };\n }\n\n private decodePeriodAndStakeMoreSca(): DecodeResult {\n const lockSca = this.helperStakeMoreSca.getNestedInputParam<SplitCoinsTransaction>(4);\n const unlockTime = this.helperExtendStakePeriod.decodeInputU64(4);\n const amountFromSplitCoin = new SplitCoinHelper(lockSca, this.txb).getAmountInput().reduce((a, b) => a + b, 0);\n let oldUnstakeObligation: string[] = [];\n let unstakeObligation: string[] = [];\n let veScaKey;\n let stakeObligation: string[] = [];\n if (this.helperOldUnstakeObligation.moveCall) {\n oldUnstakeObligation = [\n this.helperOldUnstakeObligation.decodeSharedObjectId(2), // Obligation key\n this.helperOldUnstakeObligation.decodeSharedObjectId(3), // Obligation Id\n ];\n }\n if (this.helperUnstakeObligation.moveCall) {\n unstakeObligation = [\n this.helperUnstakeObligation.decodeSharedObjectId(3), // Obligation key\n this.helperUnstakeObligation.decodeSharedObjectId(4), // Obligation Id\n ];\n }\n if (this.helperStakeMoreSca.moveCall) {\n veScaKey = this.helperStakeMoreSca.decodeOwnedObjectId(1);\n }\n if (this.helperStakeObligationWithVeSca.moveCall) {\n stakeObligation = [\n this.helperStakeObligationWithVeSca.decodeSharedObjectId(3), // Obligation key\n this.helperStakeObligationWithVeSca.decodeSharedObjectId(4), // Obligation Id\n ];\n }\n let isObligationLocked = false;\n let isOldBorrowIncentive = false;\n let obligationId;\n let obligationKey;\n\n const operations = [\n { condition: oldUnstakeObligation, isOld: true },\n { condition: unstakeObligation, isOld: false },\n { condition: stakeObligation, isOld: false },\n ];\n\n for (let i = 0; i < operations.length; i++) {\n if (operations[i].condition.length > 1) {\n [obligationKey, obligationId] = operations[i].condition;\n isObligationLocked = true;\n isOldBorrowIncentive = operations[i].isOld;\n }\n }\n return {\n txType: TransactionType.Other,\n type: TransactionSubType.ExtendPeriodAndStakeMore,\n intentionData: {\n amount: amountFromSplitCoin,\n veScaKey,\n lockPeriodInDays: unlockTime,\n obligationId,\n obligationKey,\n isOldBorrowIncentive,\n isObligationLocked,\n },\n };\n }\n\n private decodeStakeSca(): DecodeResult {\n let lockSca;\n let unlockTime;\n if (this.helperStakeSca.moveCall && this.helperStakeMoreSca.moveCall === undefined) {\n lockSca = this.helperStakeSca.getNestedInputParam<SplitCoinsTransaction>(3);\n unlockTime = this.helperStakeSca.decodeInputU64(4);\n } else {\n lockSca = this.helperStakeMoreSca.getNestedInputParam<SplitCoinsTransaction>(4);\n }\n const amountFromSplitCoin = new SplitCoinHelper(lockSca, this.txb).getAmountInput().reduce((a, b) => a + b, 0);\n let oldUnstakeObligation: string[] = [];\n let unstakeObligation: string[] = [];\n let veScaKey;\n let stakeObligation: string[] = [];\n if (this.helperOldUnstakeObligation.moveCall) {\n oldUnstakeObligation = [\n this.helperOldUnstakeObligation.decodeSharedObjectId(2), // Obligation key\n this.helperOldUnstakeObligation.decodeSharedObjectId(3), // Obligation Id\n ];\n }\n if (this.helperUnstakeObligation.moveCall) {\n unstakeObligation = [\n this.helperUnstakeObligation.decodeSharedObjectId(3), // Obligation key\n this.helperUnstakeObligation.decodeSharedObjectId(4), // Obligation Id\n ];\n }\n if (this.helperStakeMoreSca.moveCall) {\n veScaKey = this.helperStakeMoreSca.decodeOwnedObjectId(1);\n }\n if (this.helperStakeObligationWithVeSca.moveCall) {\n stakeObligation = [\n this.helperStakeObligationWithVeSca.decodeSharedObjectId(3), // Obligation key\n this.helperStakeObligationWithVeSca.decodeSharedObjectId(4), // Obligation Id\n ];\n }\n let isObligationLocked = false;\n let isOldBorrowIncentive = false;\n let obligationId;\n let obligationKey;\n\n const operations = [\n { condition: oldUnstakeObligation, isOld: true },\n { condition: unstakeObligation, isOld: false },\n { condition: stakeObligation, isOld: false },\n ];\n\n for (let i = 0; i < operations.length; i++) {\n if (operations[i].condition.length > 1) {\n [obligationKey, obligationId] = operations[i].condition;\n isObligationLocked = true;\n isOldBorrowIncentive = operations[i].isOld;\n }\n }\n return {\n txType: TransactionType.Other,\n type: TransactionSubType.StakeSca,\n intentionData: {\n amount: amountFromSplitCoin,\n lockPeriodInDays: unlockTime,\n obligationId,\n obligationKey,\n veScaKey,\n isObligationLocked,\n isOldBorrowIncentive,\n },\n };\n }\n}\n","import { TransactionType } from '@msafe/sui3-utils';\nimport { SuiClient } from '@mysten/sui.js/client';\nimport { TransactionBlock } from '@mysten/sui.js/transactions';\nimport { WalletAccount } from '@mysten/wallet-standard';\nimport sortKeys from 'sort-keys-recursive';\n\nimport { BaseIntentionLegacy } from '@/apps/interface/sui-js';\nimport { SuiNetworks } from '@/types';\n\nimport { Scallop } from '../models';\n\nexport abstract class ScallopCoreBaseIntention<D> implements BaseIntentionLegacy<D> {\n abstract txType: TransactionType;\n\n abstract txSubType: string;\n\n protected constructor(public readonly data: D) {}\n\n get application() {\n return 'msafe-core';\n }\n\n serialize() {\n return JSON.stringify(sortKeys(this.data));\n }\n\n abstract build(input: {\n suiClient: SuiClient;\n account: WalletAccount;\n network: SuiNetworks;\n scallop: Scallop;\n }): Promise<TransactionBlock>;\n}\n","import { TransactionType } from '@msafe/sui3-utils';\nimport { SuiClient } from '@mysten/sui.js/client';\nimport { TransactionBlock } from '@mysten/sui.js/transactions';\nimport { WalletAccount } from '@mysten/wallet-standard';\n\nimport { SuiNetworks } from '@/types';\n\nimport { Scallop } from '../../models';\nimport { SupportPoolCoins } from '../../types';\nimport { TransactionSubType } from '../../types/utils';\nimport { ScallopCoreBaseIntention } from '../scallopCoreBaseIntention';\n\nexport interface BorrowIntentionData {\n coinName: SupportPoolCoins;\n amount: number | string;\n obligationId: string;\n obligationKey: string;\n}\n\nexport class BorrowIntention extends ScallopCoreBaseIntention<BorrowIntentionData> {\n txType: TransactionType.Other;\n\n txSubType: TransactionSubType.Borrow;\n\n constructor(public readonly data: BorrowIntentionData) {\n super(data);\n }\n\n async build(input: {\n suiClient: SuiClient;\n account: WalletAccount;\n network: SuiNetworks;\n scallop: Scallop;\n }): Promise<TransactionBlock> {\n return input.scallop.client.borrow(\n this.data.coinName,\n Number(this.data.amount),\n this.data.obligationId,\n this.data.obligationKey,\n input.account.address,\n );\n }\n\n static fromData(data: BorrowIntentionData): BorrowIntention {\n return new BorrowIntention(data);\n }\n}\n","import { TransactionType } from '@msafe/sui3-utils';\nimport { SuiClient } from '@mysten/sui.js/client';\nimport { TransactionBlock } from '@mysten/sui.js/transactions';\nimport { WalletAccount } from '@mysten/wallet-standard';\n\nimport { SuiNetworks } from '@/types';\n\nimport { Scallop } from '../../models';\nimport { SupportPoolCoins } from '../../types';\nimport { TransactionSubType } from '../../types/utils';\nimport { ScallopCoreBaseIntention } from '../scallopCoreBaseIntention';\n\nexport interface BorrowWithBoostIntentionData {\n coinName: SupportPoolCoins;\n amount: number | string;\n obligationId: string;\n obligationKey: string;\n veScaKey: string;\n}\n\nexport class BorrowWithBoostIntention extends ScallopCoreBaseIntention<BorrowWithBoostIntentionData> {\n txType: TransactionType.Other;\n\n txSubType: TransactionSubType.Borrow;\n\n constructor(public readonly data: BorrowWithBoostIntentionData) {\n super(data);\n }\n\n async build(input: {\n suiClient: SuiClient;\n account: WalletAccount;\n network: SuiNetworks;\n scallop: Scallop;\n }): Promise<TransactionBlock> {\n return input.scallop.client.borrowWithBoost(\n this.data.coinName,\n Number(this.data.amount),\n this.data.obligationId,\n this.data.obligationKey,\n this.data.veScaKey,\n input.account.address,\n );\n }\n\n static fromData(data: BorrowWithBoostIntentionData): BorrowWithBoostIntention {\n return new BorrowWithBoostIntention(data);\n }\n}\n","import { TransactionType } from '@msafe/sui3-utils';\nimport { SuiClient } from '@mysten/sui.js/client';\nimport { TransactionBlock } from '@mysten/sui.js/transactions';\nimport { WalletAccount } from '@mysten/wallet-standard';\n\nimport { SuiNetworks } from '@/types';\n\nimport { Scallop } from '../../models';\nimport { SupportPoolCoins } from '../../types';\nimport { TransactionSubType } from '../../types/utils';\nimport { ScallopCoreBaseIntention } from '../scallopCoreBaseIntention';\n\nexport interface BorrowWithReferralIntentionData {\n coinName: SupportPoolCoins;\n amount: number | string;\n obligationId: string;\n obligationKey: string;\n veScaKey: string | undefined;\n}\n\nexport class BorrowWithReferralIntention extends ScallopCoreBaseIntention<BorrowWithReferralIntentionData> {\n txType: TransactionType.Other;\n\n txSubType: TransactionSubType.BorrowWithReferral;\n\n constructor(public readonly data: BorrowWithReferralIntentionData) {\n super(data);\n }\n\n async build(input: {\n suiClient: SuiClient;\n account: WalletAccount;\n network: SuiNetworks;\n scallop: Scallop;\n }): Promise<TransactionBlock> {\n return input.scallop.client.borrowWithReferral(\n this.data.coinName,\n Number(this.data.amount),\n this.data.obligationId,\n this.data.obligationKey,\n this.data.veScaKey,\n input.account.address,\n );\n }\n\n static fromData(data: BorrowWithReferralIntentionData): BorrowWithReferralIntention {\n return new BorrowWithReferralIntention(data);\n }\n}\n","import { TransactionType } from '@msafe/sui3-utils';\nimport { SuiClient } from '@mysten/sui.js/client';\nimport { TransactionBlock } from '@mysten/sui.js/transactions';\nimport { WalletAccount } from '@mysten/wallet-standard';\n\nimport { SuiNetworks } from '@/types';\n\nimport { Scallop } from '../../models';\nimport { BorrowIncentiveParams, SpoolIncentiveParams } from '../../types';\nimport { TransactionSubType } from '../../types/utils';\nimport { ScallopCoreBaseIntention } from '../scallopCoreBaseIntention';\n\nexport interface ClaimIncentiveRewardIntentionData {\n lendingIncentive: SpoolIncentiveParams[];\n borrowIncentiveV2: BorrowIncentiveParams[];\n borrowIncentive: BorrowIncentiveParams[];\n}\n\nexport class ClaimIncentiveRewardIntention extends ScallopCoreBaseIntention<ClaimIncentiveRewardIntentionData> {\n txType: TransactionType.Other;\n\n txSubType: TransactionSubType.ClaimIncentiveReward;\n\n constructor(public readonly data: ClaimIncentiveRewardIntentionData) {\n super(data);\n }\n\n async build(input: {\n suiClient: SuiClient;\n account: WalletAccount;\n network: SuiNetworks;\n scallop: Scallop;\n }): Promise<TransactionBlock> {\n return input.scallop.client.claim(\n this.data.lendingIncentive,\n this.data.borrowIncentiveV2,\n this.data.borrowIncentive,\n input.account.address,\n );\n }\n\n static fromData(data: ClaimIncentiveRewardIntentionData): ClaimIncentiveRewardIntention {\n return new ClaimIncentiveRewardIntention(data);\n }\n}\n","import { TransactionType } from '@msafe/sui3-utils';\nimport { SuiClient } from '@mysten/sui.js/client';\nimport { TransactionBlock } from '@mysten/sui.js/transactions';\nimport { WalletAccount } from '@mysten/wallet-standard';\n\nimport { SuiNetworks } from '@/types';\n\nimport { Scallop } from '../../models';\nimport { SupportCollateralCoins } from '../../types';\nimport { TransactionSubType } from '../../types/utils';\nimport { ScallopCoreBaseIntention } from '../scallopCoreBaseIntention';\n\nexport interface DepositCollateralIntentionData {\n collateralCoinName: SupportCollateralCoins;\n amount: number | string;\n obligationId: string;\n}\n\nexport class DepositCollateralIntention extends ScallopCoreBaseIntention<DepositCollateralIntentionData> {\n txType: TransactionType.Other;\n\n txSubType: TransactionSubType.DepositCollateral;\n\n constructor(public readonly data: DepositCollateralIntentionData) {\n super(data);\n }\n\n async build(input: {\n suiClient: SuiClient;\n account: WalletAccount;\n network: SuiNetworks;\n scallop: Scallop;\n }): Promise<TransactionBlock> {\n return input.scallop.client.depositCollateral(\n this.data.collateralCoinName,\n Number(this.data.amount),\n this.data.obligationId,\n input.account.address,\n );\n }\n\n static fromData(data: DepositCollateralIntentionData): DepositCollateralIntention {\n return new DepositCollateralIntention(data);\n }\n}\n","import { TransactionType } from '@msafe/sui3-utils';\nimport { SuiClient } from '@mysten/sui.js/client';\nimport { TransactionBlock } from '@mysten/sui.js/transactions';\nimport { WalletAccount } from '@mysten/wallet-standard';\n\nimport { SuiNetworks } from '@/types';\n\nimport { Scallop } from '../../models';\nimport { SupportBorrowIncentiveRewardCoins, TransactionSubType } from '../../types';\nimport { ScallopCoreBaseIntention } from '../scallopCoreBaseIntention';\n\nexport interface MigrateAndClaimIntentionData {\n obligationKey: string;\n obligationId: string;\n rewardCoinName: SupportBorrowIncentiveRewardCoins;\n veScaKey?: string;\n}\n\nexport class MigrateAndClaimIntention extends ScallopCoreBaseIntention<MigrateAndClaimIntentionData> {\n txType: TransactionType.Other;\n\n txSubType: TransactionSubType.MigrateAndClaim;\n\n constructor(public readonly data: MigrateAndClaimIntentionData) {\n super(data);\n }\n\n async build(input: {\n suiClient: SuiClient;\n account: WalletAccount;\n network: SuiNetworks;\n scallop: Scallop;\n }): Promise<TransactionBlock> {\n return input.scallop.client.migrateAndClaim(\n this.data.obligationKey,\n this.data.obligationId,\n this.data.rewardCoinName,\n this.data.veScaKey,\n );\n }\n\n static fromData(data: MigrateAndClaimIntentionData): MigrateAndClaimIntention {\n return new MigrateAndClaimIntention(data);\n }\n}\n","import { TransactionType } from '@msafe/sui3-utils';\nimport { SuiClient } from '@mysten/sui.js/client';\nimport { TransactionBlock } from '@mysten/sui.js/transactions';\nimport { WalletAccount } from '@mysten/wallet-standard';\n\nimport { SuiNetworks } from '@/types';\n\nimport { Scallop } from '../../models';\nimport { TransactionSubType } from '../../types';\nimport { ScallopCoreBaseIntention } from '../scallopCoreBaseIntention';\n\n// eslint-disable-next-line @typescript-eslint/no-empty-interface\nexport interface MigrateScoinIntentionData {}\n\nexport class MigrateScoinIntention extends ScallopCoreBaseIntention<MigrateScoinIntentionData> {\n txType: TransactionType.Other;\n\n txSubType: TransactionSubType.MigrateScoin;\n\n constructor(public readonly data: MigrateScoinIntentionData) {\n super(data);\n }\n\n async build(input: {\n suiClient: SuiClient;\n account: WalletAccount;\n network: SuiNetworks;\n scallop: Scallop;\n }): Promise<TransactionBlock> {\n return input.scallop.client.migrateAllMarketCoin();\n }\n\n static fromData(data: MigrateScoinIntentionData): MigrateScoinIntention {\n return new MigrateScoinIntention(data);\n }\n}\n","/* eslint-disable import/no-extraneous-dependencies */\nimport { TransactionType } from '@msafe/sui3-utils';\nimport { SuiClient } from '@mysten/sui.js/client';\nimport { TransactionBlock } from '@mysten/sui.js/transactions';\nimport { WalletAccount } from '@mysten/wallet-standard';\n\nimport { SuiNetworks } from '@/types';\n\nimport { Scallop } from '../../models';\nimport { SupportAssetCoins, TransactionSubType } from '../../types';\nimport { ScallopCoreBaseIntention } from '../scallopCoreBaseIntention';\n\nexport interface MigrateWusdcToUsdcIntentionData {\n amount: number | undefined;\n coinName: SupportAssetCoins;\n slippage: number;\n validSwapAmount: string;\n stakeAccountId: { id: string; coin: number }[];\n}\n\nexport class MigrateWusdcToUsdcIntention extends ScallopCoreBaseIntention<MigrateWusdcToUsdcIntentionData> {\n txType: TransactionType.Other;\n\n txSubType: TransactionSubType.MigrateWusdcToUsdc;\n\n constructor(public readonly data: MigrateWusdcToUsdcIntentionData) {\n super(data);\n }\n\n async build(input: {\n suiClient: SuiClient;\n account: WalletAccount;\n network: SuiNetworks;\n scallop: Scallop;\n }): Promise<TransactionBlock> {\n return input.scallop.client.migrateLendingWusdcToUsdcNative(\n this.data.coinName,\n Number(this.data.amount),\n this.data.slippage,\n this.data.validSwapAmount,\n this.data.stakeAccountId,\n );\n }\n\n static fromData(data: MigrateWusdcToUsdcIntentionData): MigrateWusdcToUsdcIntention {\n return new MigrateWusdcToUsdcIntention(data);\n }\n}\n","import { TransactionType } from '@msafe/sui3-utils';\nimport { SuiClient } from '@mysten/sui.js/client';\nimport { TransactionBlock } from '@mysten/sui.js/transactions';\nimport { WalletAccount } from '@mysten/wallet-standard';\n\nimport { SuiNetworks } from '@/types';\n\nimport { Scallop } from '../../models';\nimport { TransactionSubType } from '../../types/utils';\nimport { ScallopCoreBaseIntention } from '../scallopCoreBaseIntention';\n\n// eslint-disable-next-line @typescript-eslint/no-empty-interface\nexport interface OpenObligationIntentionData {}\n\nexport class OpenObligationIntention extends ScallopCoreBaseIntention<OpenObligationIntentionData> {\n txType: TransactionType.Other;\n\n txSubType: TransactionSubType.OpenObligation;\n\n constructor(public readonly data: OpenObligationIntentionData) {\n super(data);\n }\n\n async build(input: {\n suiClient: SuiClient;\n account: WalletAccount;\n network: SuiNetworks;\n scallop: Scallop;\n }): Promise<TransactionBlock> {\n return input.scallop.client.openObligation();\n }\n\n static fromData(data: OpenObligationIntentionData): OpenObligationIntention {\n return new OpenObligationIntention(data);\n }\n}\n","import { TransactionType } from '@msafe/sui3-utils';\nimport { SuiClient } from '@mysten/sui.js/client';\nimport { TransactionBlock } from '@mysten/sui.js/transactions';\nimport { WalletAccount } from '@mysten/wallet-standard';\n\nimport { SuiNetworks } from '@/types';\n\nimport { Scallop } from '../../models';\nimport { SupportPoolCoins } from '../../types';\nimport { TransactionSubType } from '../../types/utils';\nimport { ScallopCoreBaseIntention } from '../scallopCoreBaseIntention';\n\nexport interface RepayIntentionData {\n coinName: SupportPoolCoins;\n amount: number | string;\n obligationId: string;\n obligationKey: string;\n}\n\nexport class RepayIntention extends ScallopCoreBaseIntention<RepayIntentionData> {\n txType: TransactionType.Other;\n\n txSubType: TransactionSubType.Repay;\n\n constructor(public readonly data: RepayIntentionData) {\n super(data);\n }\n\n async build(input: {\n suiClient: SuiClient;\n account: WalletAccount;\n network: SuiNetworks;\n scallop: Scallop;\n }): Promise<TransactionBlock> {\n return input.scallop.client.repay(\n this.data.coinName,\n Number(this.data.amount),\n this.data.obligationId,\n this.data.obligationKey,\n input.account.address,\n );\n }\n\n static fromData(data: RepayIntentionData): RepayIntention {\n return new RepayIntention(data);\n }\n}\n","import { TransactionType } from '@msafe/sui3-utils';\nimport { SuiClient } from '@mysten/sui.js/client';\nimport { TransactionBlock } from '@mysten/sui.js/transactions';\nimport { WalletAccount } from '@mysten/wallet-standard';\n\nimport { SuiNetworks } from '@/types';\n\nimport { Scallop } from '../../models';\nimport { SupportPoolCoins } from '../../types';\nimport { TransactionSubType } from '../../types/utils';\nimport { ScallopCoreBaseIntention } from '../scallopCoreBaseIntention';\n\nexport interface RepayWithBoostIntentionData {\n coinName: SupportPoolCoins;\n amount: number | string;\n obligationId: string;\n veScaKey: string;\n}\n\nexport class RepayWithBoostIntention extends ScallopCoreBaseIntention<RepayWithBoostIntentionData> {\n txType: TransactionType.Other;\n\n txSubType: TransactionSubType.RepayWithBoost;\n\n constructor(public readonly data: RepayWithBoostIntentionData) {\n super(data);\n }\n\n async build(input: {\n suiClient: SuiClient;\n account: WalletAccount;\n network: SuiNetworks;\n scallop: Scallop;\n }): Promise<TransactionBlock> {\n return input.scallop.client.repayWithBoost(\n this.data.coinName,\n Number(this.data.amount),\n this.data.obligationId,\n this.data.veScaKey,\n input.account.address,\n );\n }\n\n static fromData(data: RepayWithBoostIntentionData): RepayWithBoostIntention {\n return new RepayWithBoostIntention(data);\n }\n}\n","import { TransactionType } from '@msafe/sui3-utils';\nimport { SuiClient } from '@mysten/sui.js/client';\nimport { TransactionBlock } from '@mysten/sui.js/transactions';\nimport { WalletAccount } from '@mysten/wallet-standard';\n\nimport { SuiNetworks } from '@/types';\n\nimport { Scallop } from '../../models';\nimport { SupportStakeMarketCoins } from '../../types';\nimport { TransactionSubType } from '../../types/utils';\nimport { ScallopCoreBaseIntention } from '../scallopCoreBaseIntention';\n\nexport interface StakeSpoolIntentionData {\n amount: number | string;\n marketCoinName: SupportStakeMarketCoins;\n stakeAccountId?: string | null;\n}\n\nexport class StakeSpoolIntention extends ScallopCoreBaseIntention<StakeSpoolIntentionData> {\n txType: TransactionType.Other;\n\n txSubType: TransactionSubType.StakeSpool;\n\n constructor(public readonly data: StakeSpoolIntentionData) {\n super(data);\n }\n\n async build(input: {\n suiClient: SuiClient;\n account: WalletAccount;\n network: SuiNetworks;\n scallop: Scallop;\n }): Promise<TransactionBlock> {\n return input.scallop.client.stake(\n this.data.marketCoinName,\n Number(this.data.amount),\n undefined,\n input.account.address,\n );\n }\n\n static fromData(data: StakeSpoolIntentionData): StakeSpoolIntention {\n return new StakeSpoolIntention(data);\n }\n}\n","/* eslint-disable import/no-extraneous-dependencies */\nimport { TransactionType } from '@msafe/sui3-utils';\nimport { SuiClient } from '@mysten/sui.js/client';\nimport { TransactionBlock } from '@mysten/sui.js/transactions';\nimport { WalletAccount } from '@mysten/wallet-standard';\n\nimport { SuiNetworks } from '@/types';\n\nimport { Scallop } from '../../models';\nimport { SupportAssetCoins, TransactionSubType } from '../../types';\nimport { ScallopCoreBaseIntention } from '../scallopCoreBaseIntention';\n\nexport interface SupplyLendingIntentionData {\n amount: number | string;\n coinName: SupportAssetCoins;\n}\n\nexport class SupplyLendingIntention extends ScallopCoreBaseIntention<SupplyLendingIntentionData> {\n txType: TransactionType.Other;\n\n txSubType: TransactionSubType.SupplyLending;\n\n constructor(public readonly data: SupplyLendingIntentionData) {\n super(data);\n }\n\n async build(input: {\n suiClient: SuiClient;\n account: WalletAccount;\n network: SuiNetworks;\n scallop: Scallop;\n }): Promise<TransactionBlock> {\n return input.scallop.client.deposit(this.data.coinName, Number(this.data.amount), input.account.address);\n }\n\n static fromData(data: SupplyLendingIntentionData): SupplyLendingIntention {\n return new SupplyLendingIntention(data);\n }\n}\n","import { TransactionType } from '@msafe/sui3-utils';\nimport { SuiClient } from '@mysten/sui.js/client';\nimport { TransactionBlock } from '@mysten/sui.js/transactions';\nimport { WalletAccount } from '@mysten/wallet-standard';\n\nimport { SuiNetworks } from '@/types';\n\nimport { Scallop } from '../../models';\nimport { SupportStakeMarketCoins } from '../../types';\nimport { TransactionSubType } from '../../types/utils';\nimport { ScallopCoreBaseIntention } from '../scallopCoreBaseIntention';\n\nexport interface UnstakeSpoolIntentionData {\n amount: number | string;\n marketCoinName: SupportStakeMarketCoins;\n stakeAccountId: string | null;\n}\n\nexport class UnstakeSpoolIntention extends ScallopCoreBaseIntention<UnstakeSpoolIntentionData> {\n txType: TransactionType.Other;\n\n txSubType: TransactionSubType.UnstakeSpool;\n\n constructor(public readonly data: UnstakeSpoolIntentionData) {\n super(data);\n }\n\n async build(input: {\n suiClient: SuiClient;\n account: WalletAccount;\n network: SuiNetworks;\n scallop: Scallop;\n }): Promise<TransactionBlock> {\n return input.scallop.client.unstake(\n this.data.marketCoinName,\n Number(this.data.amount),\n undefined,\n input.account.address,\n );\n }\n\n static fromData(data: UnstakeSpoolIntentionData): UnstakeSpoolIntention {\n return new UnstakeSpoolIntention(data);\n }\n}\n","/* eslint-disable import/no-extraneous-dependencies */\nimport { TransactionType } from '@msafe/sui3-utils';\nimport { SuiClient } from '@mysten/sui.js/client';\nimport { TransactionBlock } from '@mysten/sui.js/transactions';\nimport { WalletAccount } from '@mysten/wallet-standard';\n\nimport { SuiNetworks } from '@/types';\n\nimport { Scallop } from '../../models';\nimport { SupportAssetCoins, TransactionSubType } from '../../types';\nimport { ScallopCoreBaseIntention } from '../scallopCoreBaseIntention';\n\nexport interface WithdrawAndUnstakeLendingIntentionData {\n amount: number | undefined;\n coinName: SupportAssetCoins;\n stakeAccountId: { id: string; coin: number }[];\n}\n\nexport class WithdrawAndUnstakeLendingIntention extends ScallopCoreBaseIntention<WithdrawAndUnstakeLendingIntentionData> {\n txType: TransactionType.Other;\n\n txSubType: TransactionSubType.WithdrawAndUnstakeLending;\n\n constructor(public readonly data: WithdrawAndUnstakeLendingIntentionData) {\n super(data);\n }\n\n async build(input: {\n suiClient: SuiClient;\n account: WalletAccount;\n network: SuiNetworks;\n scallop: Scallop;\n }): Promise<TransactionBlock> {\n return input.scallop.client.unstakeAndWithdraw(\n this.data.coinName,\n Number(this.data.amount),\n this.data.stakeAccountId,\n );\n }\n\n static fromData(data: WithdrawAndUnstakeLendingIntentionData): WithdrawAndUnstakeLendingIntention {\n return new WithdrawAndUnstakeLendingIntention(data);\n }\n}\n","import { TransactionType } from '@msafe/sui3-utils';\nimport { SuiClient } from '@mysten/sui.js/client';\nimport { TransactionBlock } from '@mysten/sui.js/transactions';\nimport { WalletAccount } from '@mysten/wallet-standard';\n\nimport { SuiNetworks } from '@/types';\n\nimport { Scallop } from '../../models';\nimport { SupportCollateralCoins } from '../../types';\nimport { TransactionSubType } from '../../types/utils';\nimport { ScallopCoreBaseIntention } from '../scallopCoreBaseIntention';\n\nexport interface WithdrawCollateralIntentionData {\n collateralCoinName: SupportCollateralCoins;\n amount: number | string;\n obligationId: string;\n obligationKey: string;\n}\n\nexport class WithdrawCollateralIntention extends ScallopCoreBaseIntention<WithdrawCollateralIntentionData> {\n txType: TransactionType.Other;\n\n txSubType: TransactionSubType.WithdrawCollateral;\n\n constructor(public readonly data: WithdrawCollateralIntentionData) {\n super(data);\n }\n\n async build(input: {\n suiClient: SuiClient;\n account: WalletAccount;\n network: SuiNetworks;\n scallop: Scallop;\n }): Promise<TransactionBlock> {\n return input.scallop.client.withdrawCollateral(\n this.data.collateralCoinName,\n Number(this.data.amount),\n this.data.obligationId,\n this.data.obligationKey,\n input.account.address,\n );\n }\n\n static fromData(data: WithdrawCollateralIntentionData): WithdrawCollateralIntention {\n return new WithdrawCollateralIntention(data);\n }\n}\n","import { TransactionType } from '@msafe/sui3-utils';\nimport { SuiClient } from '@mysten/sui.js/client';\nimport { TransactionBlock } from '@mysten/sui.js/transactions';\nimport { WalletAccount } from '@mysten/wallet-standard';\n\nimport { Scallop } from '../../models';\nimport { SupportAssetCoins } from '../../types';\nimport { SuiNetworks, TransactionSubType } from '../../types/utils';\nimport { ScallopCoreBaseIntention } from '../scallopCoreBaseIntention';\n\nexport interface WithdrawLendingIntentionData {\n amount: string | number;\n coinName: SupportAssetCoins;\n}\n\nexport class WithdrawLendingIntention extends ScallopCoreBaseIntention<WithdrawLendingIntentionData> {\n txType: TransactionType.Other;\n\n txSubType: TransactionSubType.WithdrawLending;\n\n constructor(public readonly data: WithdrawLendingIntentionData) {\n super(data);\n }\n\n async build(input: {\n suiClient: SuiClient;\n account: WalletAccount;\n network: SuiNetworks;\n scallop: Scallop;\n }): Promise<TransactionBlock> {\n return input.scallop.client.withdraw(this.data.coinName, Number(this.data.amount), input.account.address);\n }\n\n static fromData(data: WithdrawLendingIntentionData): WithdrawLendingIntention {\n return new WithdrawLendingIntention(data);\n }\n}\n","import { TransactionType } from '@msafe/sui3-utils';\nimport { SuiClient } from '@mysten/sui.js/client';\nimport { TransactionBlock } from '@mysten/sui.js/transactions';\nimport { WalletAccount } from '@mysten/wallet-standard';\n\nimport { SuiNetworks } from '@/types';\n\nimport { Scallop } from '../../models';\nimport { TransactionSubType } from '../../types/utils';\nimport { ScallopCoreBaseIntention } from '../scallopCoreBaseIntention';\n\nexport interface BindReferralIntentionData {\n veScaKey: string;\n}\n\nexport class BindReferralIntention extends ScallopCoreBaseIntention<BindReferralIntentionData> {\n txType: TransactionType.Other;\n\n txSubType: TransactionSubType.BindReferral;\n\n constructor(public readonly data: BindReferralIntentionData) {\n super(data);\n }\n\n async build(input: {\n suiClient: SuiClient;\n account: WalletAccount;\n network: SuiNetworks;\n scallop: Scallop;\n }): Promise<TransactionBlock> {\n return input.scallop.client.bindReferral(this.data.veScaKey);\n }\n\n static fromData(data: BindReferralIntentionData): BindReferralIntention {\n return new BindReferralIntention(data);\n }\n}\n","import { TransactionType } from '@msafe/sui3-utils';\nimport { SuiClient } from '@mysten/sui.js/client';\nimport { TransactionBlock } from '@mysten/sui.js/transactions';\nimport { WalletAccount } from '@mysten/wallet-standard';\n\nimport { SuiNetworks } from '@/types';\n\nimport { Scallop } from '../../models';\nimport { TransactionSubType } from '../../types/utils';\nimport { ScallopCoreBaseIntention } from '../scallopCoreBaseIntention';\n\nexport interface ClaimRevenueReferralIntentionData {\n veScaKey: string;\n coins: string[];\n}\n\nexport class ClaimRevenueReferralIntention extends ScallopCoreBaseIntention<ClaimRevenueReferralIntentionData> {\n txType: TransactionType.Other;\n\n txSubType: TransactionSubType.ClaimRevenueReferral;\n\n constructor(public readonly data: ClaimRevenueReferralIntentionData) {\n super(data);\n }\n\n async build(input: {\n suiClient: SuiClient;\n account: WalletAccount;\n network: SuiNetworks;\n scallop: Scallop;\n }): Promise<TransactionBlock> {\n return input.scallop.client.claimRevenuReferral(this.data.veScaKey, this.data.coins);\n }\n\n static fromData(data: ClaimRevenueReferralIntentionData): ClaimRevenueReferralIntention {\n return new ClaimRevenueReferralIntention(data);\n }\n}\n","import { TransactionType } from '@msafe/sui3-utils';\nimport { SuiClient } from '@mysten/sui.js/client';\nimport { TransactionBlock } from '@mysten/sui.js/transactions';\nimport { WalletAccount } from '@mysten/wallet-standard';\n\nimport { SuiNetworks } from '@/types';\n\nimport { Scallop } from '../../models';\nimport { TransactionSubType } from '../../types/utils';\nimport { ScallopCoreBaseIntention } from '../scallopCoreBaseIntention';\n\n// eslint-disable-next-line @typescript-eslint/no-empty-interface\nexport interface CreateReferralLinkIntentionData {}\n\nexport class CreateReferralLinkIntention extends ScallopCoreBaseIntention<CreateReferralLinkIntentionData> {\n txType: TransactionType.Other;\n\n txSubType: TransactionSubType.CreateReferralLink;\n\n constructor(public readonly data: CreateReferralLinkIntentionData) {\n super(data);\n }\n\n async build(input: {\n suiClient: SuiClient;\n account: WalletAccount;\n network: SuiNetworks;\n scallop: Scallop;\n }): Promise<TransactionBlock> {\n return input.scallop.client.createReferralLink();\n }\n\n static fromData(data: CreateReferralLinkIntentionData): CreateReferralLinkIntention {\n return new CreateReferralLinkIntention(data);\n }\n}\n","import { TransactionType } from '@msafe/sui3-utils';\nimport { SuiClient } from '@mysten/sui.js/client';\nimport { TransactionBlock } from '@mysten/sui.js/transactions';\nimport { WalletAccount } from '@mysten/wallet-standard';\n\nimport { SuiNetworks } from '@/types';\n\nimport { Scallop } from '../../models';\nimport { TransactionSubType } from '../../types/utils';\nimport { ScallopCoreBaseIntention } from '../scallopCoreBaseIntention';\n\nexport interface ExtendPeriodAndStakeMoreIntentionData {\n amount: number;\n veScaKey: string;\n lockPeriodInDays: number;\n obligationId: string | undefined;\n obligationKey: string | undefined;\n isOldBorrowIncentive: boolean;\n isObligationLocked: boolean;\n}\n\nexport class ExtendPeriodAndStakeMoreIntention extends ScallopCoreBaseIntention<ExtendPeriodAndStakeMoreIntentionData> {\n txType: TransactionType.Other;\n\n txSubType: TransactionSubType.ExtendPeriodAndStakeMore;\n\n constructor(public readonly data: ExtendPeriodAndStakeMoreIntentionData) {\n super(data);\n }\n\n async build(input: {\n suiClient: SuiClient;\n account: WalletAccount;\n network: SuiNetworks;\n scallop: Scallop;\n }): Promise<TransactionBlock> {\n return input.scallop.client.extendPeriodAndStakeMoreSca(\n this.data.amount,\n this.data.veScaKey,\n this.data.lockPeriodInDays,\n this.data.obligationId,\n this.data.obligationKey,\n this.data.isObligationLocked,\n this.data.isOldBorrowIncentive,\n input.account.address,\n );\n }\n\n static fromData(data: ExtendPeriodAndStakeMoreIntentionData): ExtendPeriodAndStakeMoreIntention {\n return new ExtendPeriodAndStakeMoreIntention(data);\n }\n}\n","import { TransactionType } from '@msafe/sui3-utils';\nimport { SuiClient } from '@mysten/sui.js/client';\nimport { TransactionBlock } from '@mysten/sui.js/transactions';\nimport { WalletAccount } from '@mysten/wallet-standard';\n\nimport { SuiNetworks } from '@/types';\n\nimport { Scallop } from '../../models';\nimport { TransactionSubType } from '../../types/utils';\nimport { ScallopCoreBaseIntention } from '../scallopCoreBaseIntention';\n\nexport interface ExtendStakePeriodIntentionData {\n isObligationLocked: boolean;\n isOldBorrowIncentive: boolean;\n obligationId: string | undefined;\n obligationKey: string | undefined;\n lockPeriodInDays: number | undefined;\n veScaKey: string | undefined;\n}\n\nexport class ExtendStakePeriodIntention extends ScallopCoreBaseIntention<ExtendStakePeriodIntentionData> {\n txType: TransactionType.Other;\n\n txSubType: TransactionSubType.ExtendStakePeriod;\n\n constructor(public readonly data: ExtendStakePeriodIntentionData) {\n super(data);\n }\n\n async build(input: {\n suiClient: SuiClient;\n account: WalletAccount;\n network: SuiNetworks;\n scallop: Scallop;\n }): Promise<TransactionBlock> {\n return input.scallop.client.extendStakeScaLockPeriod(\n this.data.lockPeriodInDays,\n this.data.veScaKey,\n this.data.obligationId,\n this.data.obligationKey,\n this.data.isObligationLocked,\n this.data.isOldBorrowIncentive,\n input.account.address,\n );\n }\n\n static fromData(data: ExtendStakePeriodIntentionData): ExtendStakePeriodIntention {\n return new ExtendStakePeriodIntention(data);\n }\n}\n","import { TransactionType } from '@msafe/sui3-utils';\nimport { SuiClient } from '@mysten/sui.js/client';\nimport { TransactionBlock } from '@mysten/sui.js/transactions';\nimport { WalletAccount } from '@mysten/wallet-standard';\n\nimport { SuiNetworks } from '@/types';\n\nimport { Scallop } from '../../models';\nimport { TransactionSubType } from '../../types';\nimport { ScallopCoreBaseIntention } from '../scallopCoreBaseIntention';\n\nexport interface RedeemScaIntentionData {\n veScaKey: string;\n}\n\nexport class RedeemScaIntention extends ScallopCoreBaseIntention<RedeemScaIntentionData> {\n txType: TransactionType.Other;\n\n txSubType: TransactionSubType.RedeemSca;\n\n constructor(public readonly data: RedeemScaIntentionData) {\n super(data);\n }\n\n async build(input: {\n suiClient: SuiClient;\n account: WalletAccount;\n network: SuiNetworks;\n scallop: Scallop;\n }): Promise<TransactionBlock> {\n return input.scallop.client.redeemSca(this.data.veScaKey);\n }\n\n static fromData(data: RedeemScaIntentionData): RedeemScaIntention {\n return new RedeemScaIntention(data);\n }\n}\n","import { TransactionType } from '@msafe/sui3-utils';\nimport { SuiClient } from '@mysten/sui.js/client';\nimport { TransactionBlock } from '@mysten/sui.js/transactions';\nimport { WalletAccount } from '@mysten/wallet-standard';\n\nimport { SuiNetworks } from '@/types';\n\nimport { Scallop } from '../../models';\nimport { TransactionSubType } from '../../types/utils';\nimport { ScallopCoreBaseIntention } from '../scallopCoreBaseIntention';\n\nexport interface RenewExpStakePeriodIntentionData {\n amount: number;\n lockPeriodInDays: number;\n vescaKey: string;\n isHaveRedeem: boolean;\n obligation?: string;\n obligationKey?: string;\n isObligationLocked: boolean;\n isOldBorrowIncentive: boolean;\n}\n\nexport class RenewExpStakePeriodIntention extends ScallopCoreBaseIntention<RenewExpStakePeriodIntentionData> {\n txType: TransactionType.Other;\n\n txSubType: TransactionSubType.RenewExpStakePeriod;\n\n constructor(public readonly data: RenewExpStakePeriodIntentionData) {\n super(data);\n }\n\n async build(input: {\n suiClient: SuiClient;\n account: WalletAccount;\n network: SuiNetworks;\n scallop: Scallop;\n }): Promise<TransactionBlock> {\n return input.scallop.client.renewExpiredStakeSca(\n this.data.amount,\n this.data.lockPeriodInDays,\n this.data.vescaKey,\n this.data.isHaveRedeem,\n this.data.obligation,\n this.data.obligationKey,\n this.data.isObligationLocked,\n this.data.isOldBorrowIncentive,\n input.account.address,\n );\n }\n\n static fromData(data: RenewExpStakePeriodIntentionData): RenewExpStakePeriodIntention {\n return new RenewExpStakePeriodIntention(data);\n }\n}\n","import { TransactionType } from '@msafe/sui3-utils';\nimport { SuiClient } from '@mysten/sui.js/client';\nimport { TransactionBlock } from '@mysten/sui.js/transactions';\nimport { WalletAccount } from '@mysten/wallet-standard';\n\nimport { SuiNetworks } from '@/types';\n\nimport { Scallop } from '../../models';\nimport { TransactionSubType } from '../../types/utils';\nimport { ScallopCoreBaseIntention } from '../scallopCoreBaseIntention';\n\nexport interface StakeScaIntentionData {\n amount: number;\n isObligationLocked: boolean;\n isOldBorrowIncentive: boolean;\n obligationId: string | undefined;\n obligationKey: string | undefined;\n lockPeriodInDays: number | undefined;\n veScaKey: string | undefined;\n}\n\nexport class StakeScaIntention extends ScallopCoreBaseIntention<StakeScaIntentionData> {\n txType: TransactionType.Other;\n\n txSubType: TransactionSubType.StakeSca;\n\n constructor(public readonly data: StakeScaIntentionData) {\n super(data);\n }\n\n async build(input: {\n suiClient: SuiClient;\n account: WalletAccount;\n network: SuiNetworks;\n scallop: Scallop;\n }): Promise<TransactionBlock> {\n return input.scallop.client.stakeSca(\n this.data.amount,\n this.data.isObligationLocked,\n this.data.isOldBorrowIncentive,\n this.data.obligationId,\n this.data.obligationKey,\n this.data.lockPeriodInDays,\n this.data.veScaKey,\n input.account.address,\n );\n }\n\n static fromData(data: StakeScaIntentionData): StakeScaIntention {\n return new StakeScaIntention(data);\n }\n}\n","/* eslint-disable import/no-extraneous-dependencies */\nimport { TransactionType } from '@msafe/sui3-utils';\nimport { SuiClient } from '@mysten/sui.js/client';\nimport { TransactionBlock } from '@mysten/sui.js/transactions';\nimport { WalletAccount } from '@mysten/wallet-standard';\n\nimport { SuiNetworks } from '@/types';\n\nimport { Scallop } from '../../models';\nimport { SupportAssetCoins, TransactionSubType } from '../../types';\nimport { ScallopCoreBaseIntention } from '../scallopCoreBaseIntention';\n\nexport interface SupplyAndStakeLendingIntentionData {\n amount: number | string;\n coinName: SupportAssetCoins;\n stakeAccountId?: string | null;\n}\n\nexport class SupplyAndStakeLendingIntention extends ScallopCoreBaseIntention<SupplyAndStakeLendingIntentionData> {\n txType: TransactionType.Other;\n\n txSubType: TransactionSubType.SupplyAndStakeLending;\n\n constructor(public readonly data: SupplyAndStakeLendingIntentionData) {\n super(data);\n }\n\n async build(input: {\n suiClient: SuiClient;\n account: WalletAccount;\n network: SuiNetworks;\n scallop: Scallop;\n }): Promise<TransactionBlock> {\n return input.scallop.client.supplyAndStake(\n this.data.coinName,\n Number(this.data.amount),\n this.data.stakeAccountId,\n input.account.address,\n );\n }\n\n static fromData(data: SupplyAndStakeLendingIntentionData): SupplyAndStakeLendingIntention {\n return new SupplyAndStakeLendingIntention(data);\n }\n}\n","import { TransactionType } from '@msafe/sui3-utils';\nimport { SuiClient } from '@mysten/sui.js/client';\nimport { TransactionBlock } from '@mysten/sui.js/transactions';\nimport { WalletAccount } from '@mysten/wallet-standard';\n\nimport { SuiNetworks } from '@/types';\n\nimport { Scallop } from '../../models';\nimport { TransactionSubType } from '../../types/utils';\nimport { ScallopCoreBaseIntention } from '../scallopCoreBaseIntention';\n\nexport interface WithdrawStakedScaIntentionData {\n vescaKey?: string;\n}\n\nexport class WithdrawStakedScaIntention extends ScallopCoreBaseIntention<WithdrawStakedScaIntentionData> {\n txType: TransactionType.Other;\n\n txSubType: TransactionSubType.WithdrawStakedSca;\n\n constructor(public readonly data: WithdrawStakedScaIntentionData) {\n super(data);\n }\n\n async build(input: {\n suiClient: SuiClient;\n account: WalletAccount;\n network: SuiNetworks;\n scallop: Scallop;\n }): Promise<TransactionBlock> {\n return input.scallop.client.withdrawUnlockedSca(this.data.vescaKey, input.account.address);\n }\n\n static fromData(data: WithdrawStakedScaIntentionData): WithdrawStakedScaIntention {\n return new WithdrawStakedScaIntention(data);\n }\n}\n","import { API_BASE_URL } from '../constants';\nimport type { ScallopAddressParams, AddressesInterface, AddressStringPath } from '../types';\n\n/**\n * @description\n * It provides methods for managing addresses.\n *\n * @example\n * ```typescript\n * const scallopAddress = new ScallopAddress(<parameters>);\n * scallopAddress.<address functions>();\n * await scallopAddress.<address async functions>();\n * ```\n */\nexport class ScallopAddress {\n private id: string;\n\n private addresses: AddressesInterface;\n\n public constructor(params: ScallopAddressParams) {\n const { id } = params;\n this.id = id;\n }\n\n /**\n * Get addresses API id.\n *\n * @return The addresses API id.\n */\n public getId() {\n return this.id;\n }\n\n /**\n * Get the addresses, If `network` is not provided, returns the current\n * addresses or the default network addresses in the addresses map.\n *\n * @param network - Specifies which network's addresses you want to get.\n */\n public getAddresses() {\n return this.addresses;\n }\n\n /**\n * Get the address at the provided path.\n *\n * @param path - The path of the address to get.\n * @return The address at the provided path.\n */\n public get(path: AddressStringPath): string {\n if (!this.addresses) {\n throw new Error(`Failed to fetch address ${this.id}`);\n }\n const value = path\n .split('.')\n .reduce(\n (nestedAddressObj: any, key: string) =>\n typeof nestedAddressObj === 'object' ? nestedAddressObj[key] : nestedAddressObj,\n this.addresses,\n );\n return value;\n }\n\n public async read() {\n const options = {\n method: 'GET',\n headers: new Headers({ 'Content-Type': 'application/json' }),\n } as const;\n\n const response = await fetch(`${API_BASE_URL}/addresses/${this.id}`, options);\n if (response.status === 200) {\n const responseData = await response.json();\n\n if ('mainnet' in responseData) {\n this.addresses = responseData.mainnet;\n return;\n }\n throw new Error('Mainnet key is not in address!');\n }\n throw new Error(`Failed to fetch address with id ${this.id}`);\n }\n}\n","import type { SuiClient } from '@mysten/sui.js/client';\nimport { TransactionBlock, TransactionObjectArgument, TransactionResult } from '@mysten/sui.js/transactions';\nimport BigNumber from 'bignumber.js';\n\nimport { ScallopAddress } from './scallopAddress';\nimport { ScallopBuilder } from './scallopBuilder';\nimport { ScallopQuery } from './scallopQuery';\nimport { ScallopUtils } from './scallopUtils';\nimport { generateBorrowIncentiveQuickMethod } from '../builders/borrowIncentiveBuilder';\nimport { generateCoreQuickMethod } from '../builders/coreBuilder';\nimport { generateReferralNormalMethod, generateReferralQuickMethod } from '../builders/referralBuilder';\nimport { generateSCoinNormalMethod } from '../builders/sCoinBuilder';\nimport { SlippageTxBuilder } from '../builders/slipPageBuilder';\nimport { generateSpoolQuickMethod } from '../builders/spoolBuilder';\nimport { generateQuickVeScaMethod } from '../builders/vescaBuilder';\nimport { SCA_COIN_TYPE, SUPPORT_BORROW_INCENTIVE_POOLS, SUPPORT_SCOIN, SUPPORT_SPOOLS } from '../constants';\n// eslint-disable-next-line import/no-cycle\nimport { DeepBookSwap } from '../swap/deepbook/swap';\nimport type {\n ScallopClientParams,\n SupportPoolCoins,\n SupportCollateralCoins,\n SupportStakeMarketCoins,\n BorrowIncentiveParams,\n SpoolIncentiveParams,\n SupportBorrowIncentiveRewardCoins,\n SupportSCoin,\n SuiObjectArg,\n} from '../types';\n\n/**\n * @description\n * It provides contract interaction operations for general users.\n *\n * @example\n * ```typescript\n * const scallopClient = new ScallopClient(<parameters>);\n * await scallopClient.init();\n * scallopClient.<client functions>();\n * await scallopClient.<client async functions>();\n * ```\n */\nexport class ScallopClient {\n public readonly params: ScallopClientParams;\n\n public client: SuiClient;\n\n private address: ScallopAddress;\n\n public builder: ScallopBuilder;\n\n public query: ScallopQuery;\n\n public utils: ScallopUtils;\n\n public walletAddress: string;\n\n public deepbookSwap: DeepBookSwap;\n\n public constructor(params: ScallopClientParams, address: ScallopAddress) {\n this.params = params;\n this.client = params.client;\n\n this.address = address;\n this.utils = new ScallopUtils(params, this.address);\n\n this.query = new ScallopQuery(params, {\n address: this.address,\n utils: this.utils,\n });\n this.builder = new ScallopBuilder(params, {\n address: this.address,\n query: this.query,\n utils: this.utils,\n });\n\n this.deepbookSwap = new DeepBookSwap({\n client: this.client,\n currentAddress: this.params.walletAddress,\n scallopUtils: this.utils,\n });\n }\n\n /* ==================== Query Method ==================== */\n\n /**\n * Get obligations data.\n *\n * @description\n * This method might be @deprecated in the future, please use the {@link ScallopQuery} query instance instead.\n *\n * @param ownerAddress - The owner address.\n * @return Obligations data.\n */\n public async getObligations(ownerAddress?: string) {\n const owner = ownerAddress || this.params.walletAddress;\n return this.query.getObligations(owner);\n }\n\n /**\n * Query all stake accounts data.\n *\n * @description\n * This method might be @deprecated in the future, please use the {@link ScallopQuery} query instance instead.\n *\n * @param ownerAddress - The owner address.\n * @return All stake accounts data.\n */\n async getAllStakeAccounts(ownerAddress?: string) {\n const owner = ownerAddress || this.params.walletAddress;\n return this.query.getAllStakeAccounts(owner);\n }\n\n /**\n * Query stake account data.\n *\n * @description\n * This method might be @deprecated in the future, please use the {@link ScallopQuery} query instance instead.\n *\n * @param stakeMarketCoinName - Support stake market coin.\n * @param ownerAddress - The owner address.\n * @return Stake accounts data.\n */\n async getStakeAccounts(stakeMarketCoinName: SupportStakeMarketCoins, ownerAddress?: string) {\n const owner = ownerAddress || this.params.walletAddress;\n return this.query.getStakeAccounts(stakeMarketCoinName, owner);\n }\n\n /**\n * Query stake pool data.\n *\n * @description\n * This method might be @deprecated in the future, please use the {@link ScallopQuery} query instance instead.\n *\n * @param stakeMarketCoinName - Support stake market coin.\n * @return Stake pool data.\n */\n async getStakePool(stakeMarketCoinName: SupportStakeMarketCoins) {\n return this.query.getStakePool(stakeMarketCoinName);\n }\n\n /**\n * Query reward pool data.\n *\n * @description\n * This method might be @deprecated in the future, please use the {@link ScallopQuery} query instance instead.\n *\n * @param stakeMarketCoinName - Support stake market coin.\n * @return Reward pool data.\n */\n async getStakeRewardPool(stakeMarketCoinName: SupportStakeMarketCoins) {\n return this.query.getStakeRewardPool(stakeMarketCoinName);\n }\n\n /* ==================== Core Method ==================== */\n\n /**\n * Open obligation.\n *\n * @param sign - Decide to directly sign the transaction or return the transaction block.\n * @return Transaction block response or transaction block.\n */\n public async openObligation(walletAddress?: string): Promise<TransactionBlock> {\n const txBlock = new TransactionBlock();\n const coreQuickMethod = await generateCoreQuickMethod({ builder: this.builder, txBlock });\n const borrowIncentiveMethod = await generateBorrowIncentiveQuickMethod({ builder: this.builder, txBlock });\n const sender = walletAddress || this.params.walletAddress;\n txBlock.setSender(sender);\n const [obligationId, obligationKey, hotPotato] = coreQuickMethod.normalMethod.openObligation();\n borrowIncentiveMethod.normalMethod.stakeObligation(obligationId, obligationKey);\n coreQuickMethod.normalMethod.returnObligation(obligationId, hotPotato);\n txBlock.transferObjects([obligationKey], sender);\n return txBlock;\n }\n\n /**\n * Deposit collateral into the specific pool.\n *\n * @param collateralCoinName - Types of collateral coin.\n * @param amount - The amount of coins would deposit.\n * @param sign - Decide to directly sign the transaction or return the transaction block.\n * @param obligationId - The obligation object.\n * @param walletAddress - The wallet address of the owner.\n * @return Transaction block response or transaction block.\n */\n public async depositCollateral(\n collateralCoinName: SupportCollateralCoins,\n amount: number,\n obligationId?: string,\n walletAddress?: string,\n ): Promise<TransactionBlock> {\n const txBlock = new TransactionBlock();\n const sender = walletAddress || this.params.walletAddress;\n txBlock.setSender(sender);\n const quickMethod = await generateCoreQuickMethod({ builder: this.builder, txBlock });\n\n const obligations = await this.query.getObligations(sender);\n const specificObligationId = obligationId || obligations?.[0]?.id;\n if (specificObligationId) {\n await quickMethod.addCollateralQuick(amount, collateralCoinName, specificObligationId);\n } else {\n const [obligation, obligationKey, hotPotato] = quickMethod.normalMethod.openObligation();\n await quickMethod.addCollateralQuick(amount, collateralCoinName, obligation);\n quickMethod.normalMethod.returnObligation(obligation, hotPotato);\n txBlock.transferObjects([obligationKey], sender);\n }\n return txBlock;\n }\n\n /**\n * Withdraw collateral from the specific pool.\n *\n * @param collateralCoinName - Types of collateral coin.\n * @param amount - The amount of coins would deposit.\n * @param sign - Decide to directly sign the transaction or return the transaction block.\n * @param obligationId - The obligation object.\n * @param obligationKey - The obligation key object to verifying obligation authority.\n * @param walletAddress - The wallet address of the owner.\n * @return Transaction block response or transaction block.\n */\n public async withdrawCollateral(\n collateralCoinName: SupportCollateralCoins,\n amount: number,\n obligationId: string,\n obligationKey: string,\n walletAddress?: string,\n ): Promise<TransactionBlock> {\n const txBlock = new TransactionBlock();\n const quickMethod = await generateCoreQuickMethod({ builder: this.builder, txBlock });\n const sender = walletAddress || this.params.walletAddress;\n txBlock.setSender(sender);\n\n const collateralCoin = await quickMethod.takeCollateralQuick(\n amount,\n collateralCoinName,\n obligationId,\n obligationKey,\n );\n txBlock.transferObjects([collateralCoin], sender);\n return txBlock;\n }\n\n /**\n * Deposit asset into the specific pool.\n *\n * @param poolCoinName - Types of pool coin.\n * @param amount - The amount of coins would deposit.\n * @param sign - Decide to directly sign the transaction or return the transaction block.\n * @param walletAddress - The wallet address of the owner.\n * @return Transaction block response or transaction block.\n */\n public async deposit(\n poolCoinName: SupportPoolCoins,\n amount: number,\n walletAddress?: string,\n ): Promise<TransactionBlock> {\n const txBlock = new TransactionBlock();\n const quickMethod = await generateCoreQuickMethod({\n builder: this.builder,\n txBlock,\n });\n const scoinMethod = await generateSCoinNormalMethod({ builder: this.builder, txBlock });\n const sender = walletAddress || this.params.walletAddress;\n txBlock.setSender(sender);\n\n const marketCoin = await quickMethod.depositQuick(amount, poolCoinName, walletAddress);\n const parseScoin = this.utils.parseMarketCoinName(poolCoinName);\n if (!SUPPORT_SCOIN.includes(parseScoin as SupportSCoin)) {\n txBlock.transferObjects([marketCoin], sender);\n } else {\n const scoin = scoinMethod.mintSCoin(parseScoin as SupportSCoin, marketCoin);\n txBlock.transferObjects([scoin], sender);\n }\n return txBlock;\n }\n\n /**\n * Withdraw asset from the specific pool, must return market coin.\n *\n * @param poolCoinName - Specific support pool coin name.\n * @param amount - The amount of coins would withdraw.\n * @param sign - Decide to directly sign the transaction or return the transaction block.\n * @param walletAddress - The wallet address of the owner.\n * @return Transaction block response or transaction block.\n */\n public async withdraw(\n poolCoinName: SupportPoolCoins,\n amount: number,\n walletAddress?: string,\n ): Promise<TransactionBlock> {\n const txBlock = new TransactionBlock();\n const sender = walletAddress || this.params.walletAddress;\n const quickMethod = await generateCoreQuickMethod({\n builder: this.builder,\n txBlock,\n });\n txBlock.setSender(sender);\n\n const coin = await quickMethod.withdrawQuick(amount, poolCoinName);\n txBlock.transferObjects([coin], sender);\n return txBlock;\n }\n\n /**\n * Borrow asset from the specific pool.\n *\n * @param poolCoinName - Specific support pool coin name.\n * @param amount - The amount of coins would borrow.\n * @param sign - Decide to directly sign the transaction or return the transaction block.\n * @param obligationId - The obligation object.\n * @param obligationKey - The obligation key object to verifying obligation authority.\n * @param walletAddress - The wallet address of the owner.\n * @return Transaction block response or transaction block.\n */\n public async borrow(\n poolCoinName: SupportPoolCoins,\n amount: number,\n obligationId: string,\n obligationKey: string,\n walletAddress?: string,\n ): Promise<TransactionBlock> {\n const txBlock = new TransactionBlock();\n const quickMethod = await generateCoreQuickMethod({ builder: this.builder, txBlock });\n const borrowIncentiveQuickMethod = await generateBorrowIncentiveQuickMethod({\n builder: this.builder,\n txBlock,\n });\n const sender = walletAddress || this.params.walletAddress;\n txBlock.setSender(sender);\n\n const availableStake = (SUPPORT_BORROW_INCENTIVE_POOLS as readonly SupportPoolCoins[]).includes(poolCoinName);\n if (availableStake) {\n await borrowIncentiveQuickMethod.unstakeObligationQuick(obligationId, obligationKey);\n }\n const coin = await quickMethod.borrowQuick(amount, poolCoinName, obligationId, obligationKey);\n txBlock.transferObjects([coin], sender);\n if (availableStake) {\n await borrowIncentiveQuickMethod.stakeObligationQuick(obligationId, obligationKey);\n }\n return txBlock;\n }\n\n /**\n * Borrow asset from the specific pool with boost from SCA stake.\n *\n * @param poolCoinName - Specific support pool coin name.\n * @param amount - The amount of coins would borrow.\n * @param sign - Decide to directly sign the transaction or return the transaction block.\n * @param obligationId - The obligation object.\n * @param obligationKey - The obligation key object to verifying obligation authority.\n * @param veScaKey - The vesca key object to verifying sca staker.\n * @param walletAddress - The wallet address of the owner.\n * @return Transaction block response or transaction block.\n */\n public async borrowWithBoost(\n poolCoinName: SupportPoolCoins,\n amount: number,\n obligationId: string,\n obligationKey: string,\n veScaKey: string,\n walletAddress?: string,\n ): Promise<TransactionBlock> {\n const txBlock = new TransactionBlock();\n const quickMethod = await generateCoreQuickMethod({ builder: this.builder, txBlock });\n const borrowIncentiveQuickMethod = await generateBorrowIncentiveQuickMethod({\n builder: this.builder,\n txBlock,\n });\n const sender = walletAddress || this.params.walletAddress;\n txBlock.setSender(sender);\n\n const availableStake = (SUPPORT_BORROW_INCENTIVE_POOLS as readonly SupportPoolCoins[]).includes(poolCoinName);\n if (availableStake) {\n await borrowIncentiveQuickMethod.unstakeObligationQuick(obligationId, obligationKey);\n }\n const coin = await quickMethod.borrowQuick(amount, poolCoinName, obligationId, obligationKey);\n txBlock.transferObjects([coin], sender);\n if (availableStake) {\n await borrowIncentiveQuickMethod.stakeObligationWithVeScaQuick(obligationId, obligationKey, veScaKey);\n }\n return txBlock;\n }\n\n /**\n * Borrow asset from the specific pool with boost from SCA stake.\n *\n * @param poolCoinName - Specific support pool coin name.\n * @param amount - The amount of coins would borrow.\n * @param sign - Decide to directly sign the transaction or return the transaction block.\n * @param obligationId - The obligation object.\n * @param obligationKey - The obligation key object to verifying obligation authority.\n * @param veScaKey - The vesca key object to verifying sca staker.\n * @param walletAddress - The wallet address of the owner.\n * @return Transaction block response or transaction block.\n */\n public async borrowWithReferral(\n poolCoinName: SupportPoolCoins,\n amount: number,\n obligationId: string,\n obligationKey: string,\n veScaKey: string | undefined,\n walletAddress?: string,\n ): Promise<TransactionBlock> {\n const txBlock = new TransactionBlock();\n const quickMethod = await generateCoreQuickMethod({ builder: this.builder, txBlock });\n const borrowIncentiveQuickMethod = await generateBorrowIncentiveQuickMethod({\n builder: this.builder,\n txBlock,\n });\n const referralMethod = await generateReferralNormalMethod({ builder: this.builder, txBlock });\n const sender = walletAddress || this.params.walletAddress;\n txBlock.setSender(sender);\n\n const availableStake = (SUPPORT_BORROW_INCENTIVE_POOLS as readonly SupportPoolCoins[]).includes(poolCoinName);\n if (availableStake) {\n await borrowIncentiveQuickMethod.unstakeObligationQuick(obligationId, obligationKey);\n }\n const borrowReferral = referralMethod.claimReferralTicket(poolCoinName);\n const coin = await quickMethod.borrowWithReferralQuick(\n amount,\n poolCoinName,\n borrowReferral,\n obligationId,\n obligationKey,\n );\n referralMethod.burnReferralTicket(borrowReferral, poolCoinName);\n txBlock.transferObjects([coin], sender);\n if (availableStake && veScaKey) {\n await borrowIncentiveQuickMethod.stakeObligationWithVeScaQuick(obligationId, obligationKey, veScaKey);\n } else {\n await borrowIncentiveQuickMethod.stakeObligationQuick(obligationId, obligationKey);\n }\n return txBlock;\n }\n\n /**\n * Repay asset into the specific pool.\n *\n * @param poolCoinName - Specific support pool coin name.\n * @param amount - The amount of coins would repay.\n * @param sign - Decide to directly sign the transaction or return the transaction block.\n * @param obligationId - The obligation object.\n * @param walletAddress - The wallet address of the owner.\n * @return Transaction block response or transaction block.\n */\n public async repay(\n poolCoinName: SupportPoolCoins,\n amount: number,\n obligationId: string,\n obligationKey: string,\n walletAddress?: string,\n ): Promise<TransactionBlock> {\n const txBlock = new TransactionBlock();\n const quickMethod = await generateCoreQuickMethod({ builder: this.builder, txBlock });\n const borrowIncentiveQuickMethod = await generateBorrowIncentiveQuickMethod({\n builder: this.builder,\n txBlock,\n });\n const sender = walletAddress || this.params.walletAddress;\n txBlock.setSender(sender);\n\n const availableStake = (SUPPORT_BORROW_INCENTIVE_POOLS as readonly SupportPoolCoins[]).includes(poolCoinName);\n if (availableStake) {\n await borrowIncentiveQuickMethod.unstakeObligationQuick(obligationId, obligationKey);\n }\n await quickMethod.repayQuick(amount, poolCoinName, obligationId, sender);\n if (availableStake) {\n await borrowIncentiveQuickMethod.stakeObligationQuick(obligationId, obligationKey);\n }\n return txBlock;\n }\n\n /**\n * Repay asset into the specific pool.\n *\n * @param poolCoinName - Specific support pool coin name.\n * @param amount - The amount of coins would repay.\n * @param sign - Decide to directly sign the transaction or return the transaction block.\n * @param obligationId - The obligation object.\n * @param walletAddress - The wallet address of the owner.\n * @return Transaction block response or transaction block.\n */\n public async repayWithBoost(\n poolCoinName: SupportPoolCoins,\n amount: number,\n obligationId: string,\n veScaKey: string,\n walletAddress?: string,\n ): Promise<TransactionBlock> {\n const txBlock = new TransactionBlock();\n const quickMethod = await generateCoreQuickMethod({ builder: this.builder, txBlock });\n const borrowIncentiveQuickMethod = await generateBorrowIncentiveQuickMethod({\n builder: this.builder,\n txBlock,\n });\n const sender = walletAddress || this.params.walletAddress;\n txBlock.setSender(sender);\n\n const availableStake = (SUPPORT_BORROW_INCENTIVE_POOLS as readonly SupportPoolCoins[]).includes(poolCoinName);\n if (availableStake) {\n await borrowIncentiveQuickMethod.unstakeObligationQuick(obligationId, undefined);\n }\n await quickMethod.repayQuick(amount, poolCoinName, obligationId, sender);\n if (availableStake) {\n await borrowIncentiveQuickMethod.stakeObligationWithVeScaQuick(obligationId, undefined, veScaKey);\n }\n return txBlock;\n }\n\n /* ==================== Spool Method ==================== */\n\n /**\n * Create stake account.\n *\n * @param sign - Decide to directly sign the transaction or return the transaction block.\n * @param walletAddress - The wallet address of the owner.\n * @return Transaction block response or transaction block.\n */\n public async createStakeAccount(\n marketCoinName: SupportStakeMarketCoins,\n walletAddress?: string,\n ): Promise<TransactionBlock> {\n const txBlock = new TransactionBlock();\n const spoolQuickMethod = await generateSpoolQuickMethod({ builder: this.builder, txBlock });\n const sender = walletAddress || this.params.walletAddress;\n txBlock.setSender(sender);\n\n const stakeAccount = spoolQuickMethod.normalMethod.createStakeAccount(marketCoinName);\n txBlock.transferObjects([stakeAccount], sender);\n return txBlock;\n }\n\n public async supplyAndStake(\n poolCoinName: SupportPoolCoins,\n amount: number,\n stakeAccountId: string,\n walletAddress?: string,\n ): Promise<TransactionBlock> {\n const txBlock = new TransactionBlock();\n const quickMethod = await generateCoreQuickMethod({\n builder: this.builder,\n txBlock,\n });\n const spoolQuickMethod = await generateSpoolQuickMethod({ builder: this.builder, txBlock });\n const sender = walletAddress || this.params.walletAddress;\n txBlock.setSender(sender);\n\n const marketCoin = await quickMethod.depositQuick(amount, poolCoinName, walletAddress);\n const stakeMarketCoinName = this.utils.parseMarketCoinName(poolCoinName);\n if (!SUPPORT_SPOOLS.find((coin) => coin === stakeMarketCoinName)) {\n return txBlock;\n }\n const stakeAccounts = await this.query.getStakeAccounts(stakeMarketCoinName as SupportStakeMarketCoins, sender);\n const targetStakeAccount = stakeAccountId || (stakeAccounts.length > 0 ? stakeAccounts[0].id : undefined);\n if (targetStakeAccount) {\n await spoolQuickMethod.stakeQuick(marketCoin, stakeMarketCoinName as SupportStakeMarketCoins, targetStakeAccount);\n } else {\n const account = spoolQuickMethod.normalMethod.createStakeAccount(stakeMarketCoinName as SupportStakeMarketCoins);\n await spoolQuickMethod.stakeQuick(marketCoin, stakeMarketCoinName as SupportStakeMarketCoins, account);\n txBlock.transferObjects([account], sender);\n }\n return txBlock;\n }\n\n public async unstakeAndWithdraw(\n poolCoinName: SupportPoolCoins,\n amount: number,\n unstakeAccount: { id: string; coin: number }[],\n ) {\n const txBlock = new TransactionBlock();\n const quickMethod = await generateCoreQuickMethod({\n builder: this.builder,\n txBlock,\n });\n const spoolQuickMethod = await generateSpoolQuickMethod({ builder: this.builder, txBlock });\n const sender = this.params.walletAddress;\n const withdrawCoins = [];\n txBlock.setSender(sender);\n const stakeMarketCoinName = this.utils.parseMarketCoinName(poolCoinName) as SupportStakeMarketCoins;\n for (let i = 0; i < unstakeAccount.length; i++) {\n const account = unstakeAccount[i];\n const [marketCoin] = await spoolQuickMethod.unstakeQuick(account.coin, stakeMarketCoinName, account.id);\n if (marketCoin) {\n const wdScoin = quickMethod.normalMethod.withdraw(marketCoin, poolCoinName);\n withdrawCoins.push(wdScoin);\n }\n }\n if (amount > 0) {\n const wdCoin = await quickMethod.withdrawQuick(amount, poolCoinName);\n withdrawCoins.push(wdCoin);\n }\n if (withdrawCoins.length > 1) {\n txBlock.mergeCoins(withdrawCoins[0], withdrawCoins.slice(1));\n }\n txBlock.transferObjects(withdrawCoins, sender);\n return txBlock;\n }\n\n /**\n * Stake market coin into the specific spool.\n *\n * @param marketCoinName - Types of market coin.\n * @param amount - The amount of coins would deposit.\n * @param sign - Decide to directly sign the transaction or return the transaction block.\n * @param stakeAccountId - The stake account object.\n * @param walletAddress - The wallet address of the owner.\n * @return Transaction block response or transaction block.\n */\n public async stake(\n stakeMarketCoinName: SupportStakeMarketCoins,\n amount: number,\n stakeAccountId?: string,\n walletAddress?: string,\n ): Promise<TransactionBlock> {\n const txBlock = new TransactionBlock();\n const spoolQuickMethod = await generateSpoolQuickMethod({ builder: this.builder, txBlock });\n const sender = walletAddress || this.params.walletAddress;\n txBlock.setSender(sender);\n\n const stakeAccounts = await this.query.getStakeAccounts(stakeMarketCoinName, sender);\n const targetStakeAccount = stakeAccountId || (stakeAccounts.length > 0 ? stakeAccounts[0].id : undefined);\n if (targetStakeAccount) {\n await spoolQuickMethod.stakeQuick(amount, stakeMarketCoinName, targetStakeAccount);\n } else {\n const account = spoolQuickMethod.normalMethod.createStakeAccount(stakeMarketCoinName);\n await spoolQuickMethod.stakeQuick(amount, stakeMarketCoinName, account);\n txBlock.transferObjects([account], sender);\n }\n return txBlock;\n }\n\n /**\n * Unstake market coin from the specific spool.\n *\n * @param stakeMarketCoinName - Types of mak coin.\n * @param amount - The amount of coins would deposit.\n * @param sign - Decide to directly sign the transaction or return the transaction block.\n * @param accountId - The stake account object.\n * @param walletAddress - The wallet address of the owner.\n * @return Transaction block response or transaction block.\n */\n public async unstake(\n stakeMarketCoinName: SupportStakeMarketCoins,\n amount: number,\n stakeAccountId?: string,\n walletAddress?: string,\n ): Promise<TransactionBlock> {\n const txBlock = new TransactionBlock();\n const spoolQuickMethod = await generateSpoolQuickMethod({ builder: this.builder, txBlock });\n const sender = walletAddress || this.params.walletAddress;\n txBlock.setSender(sender);\n const returnScoin = SUPPORT_SCOIN.includes(stakeMarketCoinName);\n const marketCoins = await spoolQuickMethod.unstakeQuick(amount, stakeMarketCoinName, stakeAccountId, returnScoin);\n txBlock.transferObjects([marketCoins], txBlock.pure(sender));\n return txBlock;\n }\n\n /**\n * Claim reward coin from the specific spool.\n *\n * @param stakeMarketCoinName - Types of mak coin.\n * @param amount - The amount of coins would deposit.\n * @param sign - Decide to directly sign the transaction or return the transaction block.\n * @param accountId - The stake account object.\n * @param walletAddress - The wallet address of the owner.\n * @return Transaction block response or transaction block.\n */\n public async claim(\n lendingIncentive: SpoolIncentiveParams[],\n borrowIncentiveV2: BorrowIncentiveParams[],\n borrowIncentive: BorrowIncentiveParams[],\n walletAddress?: string,\n ): Promise<TransactionBlock> {\n const txBlock = new TransactionBlock();\n const spoolQuickMethod = await generateSpoolQuickMethod({ builder: this.builder, txBlock });\n const borrowIncentiveRewarad = await generateBorrowIncentiveQuickMethod({ builder: this.builder, txBlock });\n const sender = walletAddress || this.params.walletAddress;\n txBlock.setSender(sender);\n\n const rewardCoins: { sui: TransactionResult[]; sca: TransactionResult[] } = {\n sui: [],\n sca: [],\n };\n\n for (let i = 0; i < lendingIncentive.length; i++) {\n const { stakeMarketCoinName, stakeAccountId } = lendingIncentive[i];\n const rewardCoin = spoolQuickMethod.normalMethod.claim(stakeAccountId, stakeMarketCoinName);\n rewardCoins.sui.push(rewardCoin);\n }\n\n for (let i = 0; i < borrowIncentiveV2.length; i++) {\n const { obligationId, obligationKey, rewardCoinName } = borrowIncentiveV2[i];\n const rewardCoin = borrowIncentiveRewarad.normalMethod.claimBorrowIncentive(\n obligationId,\n obligationKey,\n rewardCoinName,\n );\n rewardCoins[rewardCoinName].push(rewardCoin);\n }\n\n for (let i = 0; i < borrowIncentive.length; i++) {\n const { obligationId, obligationKey, rewardCoinName } = borrowIncentive[i];\n const rewardCoin = borrowIncentiveRewarad.normalMethod.oldClaimBorrowIncentive(\n obligationId,\n obligationKey,\n rewardCoinName,\n );\n rewardCoins[rewardCoinName].push(rewardCoin);\n }\n\n if (rewardCoins.sui.length > 0) {\n if (rewardCoins.sui.length > 1) {\n txBlock.mergeCoins(rewardCoins.sui[0], rewardCoins.sui.slice(1));\n }\n txBlock.transferObjects([rewardCoins.sui[0]], txBlock.pure(sender));\n }\n\n if (rewardCoins.sca.length > 0) {\n if (rewardCoins.sca.length > 1) {\n txBlock.mergeCoins(rewardCoins.sca[0], rewardCoins.sca.slice(1));\n }\n txBlock.transferObjects([rewardCoins.sca[0]], txBlock.pure(sender));\n }\n return txBlock;\n }\n\n /* ==================== Borrow Incentive Method ==================== */\n\n /**\n * stake obligaion.\n *\n * @param obligationId - The obligation account object.\n * @param obligationKeyId - The obligation key account object.\n * @param sign - Decide to directly sign the transaction or return the transaction block.\n * @param walletAddress - The wallet address of the owner.\n * @return Transaction block response or transaction block\n */\n public async stakeObligation(\n obligationId: string,\n obligationKeyId: string,\n walletAddress?: string,\n ): Promise<TransactionBlock> {\n const txBlock = this.builder.createTxBlock();\n const borrowIncentiveQuickMethod = await generateBorrowIncentiveQuickMethod({ builder: this.builder, txBlock });\n const sender = walletAddress || this.params.walletAddress;\n txBlock.setSender(sender);\n\n await borrowIncentiveQuickMethod.stakeObligationQuick(obligationId, obligationKeyId);\n return txBlock;\n }\n\n /**\n * unstake obligaion.\n *\n * @param obligationId - The obligation account object.\n * @param obligationKeyId - The obligation key account object.\n * @param sign - Decide to directly sign the transaction or return the transaction block.\n * @param walletAddress - The wallet address of the owner.\n * @return Transaction block response or transaction block\n */\n public async unstakeObligation(\n obligationId: string,\n obligationKeyId: string,\n walletAddress?: string,\n ): Promise<TransactionBlock> {\n const txBlock = this.builder.createTxBlock();\n const borrowIncentiveQuickMethod = await generateBorrowIncentiveQuickMethod({ builder: this.builder, txBlock });\n const sender = walletAddress || this.params.walletAddress;\n txBlock.setSender(sender);\n\n await borrowIncentiveQuickMethod.unstakeObligationQuick(obligationId, obligationKeyId);\n return txBlock;\n }\n\n /**\n * Stake SCA.\n *\n * @param amount - Types of mak coin.\n * @param lockPeriod - The amount of coins would deposit.\n * @param walletAddress - The wallet address of the owner.\n * @return Transaction block response or transaction block.\n */\n public async stakeSca(\n amount: number,\n isObligationLocked = false,\n isOldBorrowIncentive = false,\n obligationId?: string,\n obligationKey?: string,\n lockPeriod?: number,\n vescaKey?: string,\n walletAddress?: string,\n ): Promise<TransactionBlock> {\n const txBlock = new TransactionBlock();\n const vescaQuickMethod = await generateQuickVeScaMethod({ builder: this.builder, txBlock });\n const borrowIncentive = await generateBorrowIncentiveQuickMethod({ builder: this.builder, txBlock });\n const sender = walletAddress || this.params.walletAddress;\n txBlock.setSender(sender);\n\n // Get all SCA and merge them into one.\n const coins = await this.builder.utils.selectCoinIds(amount, SCA_COIN_TYPE, sender);\n const [takeCoin, leftCoin] = this.builder.utils.takeAmountFromCoins(txBlock, coins, amount);\n\n let newVescaKey;\n if (!vescaKey) {\n newVescaKey = vescaQuickMethod.normalMethod.lockSca(takeCoin, lockPeriod);\n } else {\n vescaQuickMethod.normalMethod.extendLockAmount(vescaKey, takeCoin);\n }\n\n if (obligationId && obligationKey) {\n if (isObligationLocked) {\n if (isOldBorrowIncentive) {\n borrowIncentive.normalMethod.oldUnstakeObligation(obligationId, obligationKey);\n } else {\n borrowIncentive.normalMethod.unstakeObligation(obligationId, obligationKey);\n }\n }\n borrowIncentive.normalMethod.stakeObligationWithVesca(obligationId, obligationKey, vescaKey || newVescaKey);\n }\n\n if (!vescaKey) {\n txBlock.transferObjects([newVescaKey, leftCoin], sender);\n }\n\n return txBlock;\n }\n\n /**\n * Stake more SCA.\n *\n * @param amount - Types of mak coin.\n * @param vescaKey - The vesca key object.\n * @param walletAddress - The wallet address of the owner.\n * @return Transaction block response or transaction block.\n */\n public async stakeMoreSca(amount: number, vescaKey?: string, walletAddress?: string): Promise<TransactionBlock> {\n const txBlock = new TransactionBlock();\n // const vescaQuickMethod = await generateQuickVeScaMethod({ builder: this.builder, txBlock });\n const sender = walletAddress || this.params.walletAddress;\n txBlock.setSender(sender);\n\n // await vescaQuickMethod.extendLockAmountQuick(amount, vescaKey);\n return txBlock;\n }\n\n /**\n * Extend stake lock period.\n *\n * @param lockPeriodInDays\n * @param vescaKey\n * @param walletAddress\n * @returns Transaction block response or transaction block.\n */\n public async extendStakeScaLockPeriod(\n lockPeriodInDays: number,\n vescaKey: string,\n obligationId?: string,\n obligationKey?: string,\n isObligationLocked = false,\n isOldBorrowIncentive = false,\n walletAddress?: string,\n ): Promise<TransactionBlock> {\n const txBlock = new TransactionBlock();\n const vescaQuickMethod = await generateQuickVeScaMethod({ builder: this.builder, txBlock });\n const borrowIncentive = await generateBorrowIncentiveQuickMethod({ builder: this.builder, txBlock });\n const sender = walletAddress || this.params.walletAddress;\n txBlock.setSender(sender);\n\n vescaQuickMethod.normalMethod.extendLockPeriod(vescaKey, lockPeriodInDays);\n if (obligationId && obligationKey) {\n if (isObligationLocked) {\n if (isOldBorrowIncentive) {\n borrowIncentive.normalMethod.oldUnstakeObligation(obligationId, obligationKey);\n } else {\n borrowIncentive.normalMethod.unstakeObligation(obligationId, obligationKey);\n }\n }\n borrowIncentive.normalMethod.stakeObligationWithVesca(obligationId, obligationKey, vescaKey);\n }\n return txBlock;\n }\n\n public async extendPeriodAndStakeMoreSca(\n amount: number,\n vescaKey: string,\n lockPeriodInDays: number,\n obligation?: string,\n obligationKey?: string,\n isObligationLocked = false,\n isOldBorrowIncentive = false,\n walletAddress?: string,\n ): Promise<TransactionBlock> {\n const txBlock = new TransactionBlock();\n const vescaQuickMethod = await generateQuickVeScaMethod({ builder: this.builder, txBlock });\n const borrowIncentive = await generateBorrowIncentiveQuickMethod({ builder: this.builder, txBlock });\n const sender = walletAddress || this.params.walletAddress;\n txBlock.setSender(sender);\n\n // Get all SCA and merge them into one.\n const coins = await this.builder.utils.selectCoinIds(amount, SCA_COIN_TYPE, sender);\n const [takeCoin, leftCoin] = this.builder.utils.takeAmountFromCoins(txBlock, coins, amount);\n vescaQuickMethod.normalMethod.extendLockPeriod(vescaKey, lockPeriodInDays);\n vescaQuickMethod.normalMethod.extendLockAmount(vescaKey, takeCoin);\n txBlock.transferObjects([leftCoin], sender);\n if (!obligation || !obligationKey) {\n return txBlock;\n }\n if (isObligationLocked) {\n if (isOldBorrowIncentive) {\n borrowIncentive.normalMethod.oldUnstakeObligation(obligation, obligationKey);\n } else {\n borrowIncentive.normalMethod.unstakeObligation(obligation, obligationKey);\n }\n }\n borrowIncentive.normalMethod.stakeObligationWithVesca(obligation, obligationKey, vescaKey);\n return txBlock;\n }\n\n /**\n * Renew expired stake SCA.\n *\n * @param amount\n * @param lockPeriodInDays\n * @param vescaKey\n * @param walletAddress\n * @returns Transaction block response or transaction block.\n */\n public async renewExpiredStakeSca(\n amount: number,\n lockPeriodInDays: number,\n vescaKey: string,\n isHaveRedeem = false,\n obligation?: string,\n obligationKey?: string,\n isObligationLocked = false,\n isOldBorrowIncentive = false,\n walletAddress?: string,\n ): Promise<TransactionBlock> {\n const txBlock = new TransactionBlock();\n const vescaQuickMethod = await generateQuickVeScaMethod({ builder: this.builder, txBlock });\n const borrowIncentive = await generateBorrowIncentiveQuickMethod({ builder: this.builder, txBlock });\n const sender = walletAddress || this.params.walletAddress;\n txBlock.setSender(sender);\n\n if (isHaveRedeem) {\n const redeem = vescaQuickMethod.normalMethod.redeemSca(vescaKey);\n txBlock.transferObjects([redeem], sender);\n }\n\n // Get all SCA and merge them into one.\n const coins = await this.builder.utils.selectCoinIds(amount, SCA_COIN_TYPE, sender);\n const [takeCoin, leftCoin] = this.builder.utils.takeAmountFromCoins(txBlock, coins, amount);\n txBlock.transferObjects([leftCoin], sender);\n // renew veSCA\n vescaQuickMethod.normalMethod.renewExpiredVeSca(vescaKey, takeCoin, lockPeriodInDays);\n if (!obligation || !obligationKey) {\n return txBlock;\n }\n if (isObligationLocked) {\n if (isOldBorrowIncentive) {\n borrowIncentive.normalMethod.oldUnstakeObligation(obligation, obligationKey);\n } else {\n borrowIncentive.normalMethod.unstakeObligation(obligation, obligationKey);\n }\n }\n borrowIncentive.normalMethod.stakeObligationWithVesca(obligation, obligationKey, vescaKey);\n return txBlock;\n }\n\n public async redeemSca(veScaKey: string): Promise<TransactionBlock> {\n const txBlock = new TransactionBlock();\n const vescaQuickMethod = await generateQuickVeScaMethod({ builder: this.builder, txBlock });\n const sender = this.params.walletAddress;\n txBlock.setSender(sender);\n\n await vescaQuickMethod.redeemScaQuick(veScaKey);\n return txBlock;\n }\n\n public async migrateAndClaim(\n obligationKey: string,\n obligationId: string,\n rewardCoinName: SupportBorrowIncentiveRewardCoins,\n veScaKey?: string,\n ) {\n const txBlock = new TransactionBlock();\n const borrowIncentive = await generateBorrowIncentiveQuickMethod({ builder: this.builder, txBlock });\n const sender = this.params.walletAddress;\n txBlock.setSender(sender);\n\n const rewardCoin = borrowIncentive.normalMethod.oldClaimBorrowIncentive(\n obligationId,\n obligationKey,\n rewardCoinName,\n );\n txBlock.transferObjects([rewardCoin], sender);\n await borrowIncentive.unstakeObligationQuick(obligationId, obligationKey);\n if (veScaKey) {\n await borrowIncentive.stakeObligationWithVeScaQuick(obligationId, obligationKey, veScaKey);\n } else {\n await borrowIncentive.stakeObligationQuick(obligationId, obligationKey);\n }\n return txBlock;\n }\n\n /**\n * Withdraw unlocked SCA.\n *\n * @param vescaKey\n * @param walletAddress\n * @returns Transaction block response or transaction block.\n */\n public async withdrawUnlockedSca(vescaKey?: string, walletAddress?: string): Promise<TransactionBlock> {\n const txBlock = new TransactionBlock();\n const vescaQuickMethod = await generateQuickVeScaMethod({ builder: this.builder, txBlock });\n const sender = walletAddress || this.params.walletAddress;\n txBlock.setSender(sender);\n\n await vescaQuickMethod.redeemScaQuick(vescaKey);\n return txBlock;\n }\n\n private calculateAvailableClaimCoin(accountPoint: any, poolPoint: any): BigNumber {\n const borrowAmount = new BigNumber(accountPoint.weightedAmount);\n const baseIndexRate = 1e9;\n const increasePointRate = poolPoint.currentPointIndex\n ? BigNumber(poolPoint.currentPointIndex - accountPoint.index).dividedBy(baseIndexRate)\n : 1;\n return borrowAmount\n .multipliedBy(increasePointRate)\n .plus(accountPoint.points)\n .shiftedBy(-1 * poolPoint.coinDecimal);\n }\n\n /**\n * Create Referral Link\n *\n * @returns Transaction block response or transaction block.\n */\n public async createReferralLink(): Promise<TransactionBlock> {\n const txBlock = new TransactionBlock();\n const vescaMethod = await generateQuickVeScaMethod({ builder: this.builder, txBlock });\n const sender = this.params.walletAddress;\n txBlock.setSender(sender);\n\n const referralTicket = vescaMethod.normalMethod.mintEmptyVeSca();\n txBlock.transferObjects([referralTicket], sender);\n return txBlock;\n }\n\n /**\n * Claim Referral Revenue\n * @param veScaKey - The vesca key object.\n * @param coins - The coins would claim.\n *\n * @returns Transaction block response or transaction block.\n */\n public async claimRevenuReferral(veScaKey: string, coins: string[]): Promise<TransactionBlock> {\n const txBlock = new TransactionBlock();\n const referral = await generateReferralQuickMethod({ builder: this.builder, txBlock });\n const sender = this.params.walletAddress;\n txBlock.setSender(sender);\n const coinsName = coins.map((coin) => this.utils.parseCoinNameFromType(coin) as SupportPoolCoins);\n\n await referral.claimReferralRevenueQuick(veScaKey, sender, coinsName);\n return txBlock;\n }\n\n /**\n * Bind Referral\n * @param veScaKey - The vesca key object.\n *\n *\n * @returns Transaction block response or transaction block.\n */\n public async bindReferral(veScaKey: string): Promise<TransactionBlock> {\n const txBlock = new TransactionBlock();\n const referral = await generateReferralNormalMethod({ builder: this.builder, txBlock });\n const sender = this.params.walletAddress;\n txBlock.setSender(sender);\n referral.bindToReferral(veScaKey);\n return txBlock;\n }\n\n /* ==================== Migrate market coin to sCoin method ==================== */\n /**\n * Function to migrate all market coin in user wallet into sCoin\n * @returns Transaction response\n */\n public async migrateAllMarketCoin(): Promise<TransactionBlock> {\n const txBlock = new TransactionBlock();\n const scoinNormalMethod = await generateSCoinNormalMethod({ builder: this.builder, txBlock });\n const spoolQuickMethod = await generateSpoolQuickMethod({ builder: this.builder, txBlock });\n txBlock.setSender(this.params.walletAddress);\n\n const toTransfer: SuiObjectArg[] = [];\n await Promise.all(\n SUPPORT_SCOIN.map(async (sCoinName) => {\n /**\n * First check marketCoin inside mini wallet\n * Then check stakedMarketCoin inside spool\n */\n const sCoins: SuiObjectArg[] = [];\n let toDestroyMarketCoin: SuiObjectArg | undefined;\n\n // check market coin in mini wallet\n try {\n const marketCoins = await this.utils.selectCoinIds(\n Number.MAX_SAFE_INTEGER,\n this.utils.parseMarketCoinType(sCoinName as SupportSCoin),\n this.params.walletAddress,\n ); // throw error no coins found\n\n const mergedMarketCoin = marketCoins[0];\n if (marketCoins.length > 1) {\n txBlock.mergeCoins(mergedMarketCoin, marketCoins.slice(1));\n }\n\n toDestroyMarketCoin = mergedMarketCoin;\n } catch (e: any) {\n // Ignore\n const errMsg = e.toString() as string;\n if (!errMsg.includes('No valid coins found for the transaction')) {\n throw e;\n }\n }\n\n // if market coin found, mint sCoin\n if (toDestroyMarketCoin) {\n // mint new sCoin\n const sCoin = scoinNormalMethod.mintSCoin(sCoinName as SupportSCoin, toDestroyMarketCoin);\n\n // check if current sCoin exist\n try {\n const existSCoins = await this.utils.selectCoinIds(\n Number.MAX_SAFE_INTEGER,\n this.utils.parseSCoinType(sCoinName as SupportSCoin),\n this.params.walletAddress,\n ); // throw error on no coins found\n txBlock.mergeCoins(sCoin, existSCoins);\n } catch (e: any) {\n console.log(e);\n }\n sCoins.push(sCoin);\n }\n\n // check for staked market coin in spool\n if (SUPPORT_SPOOLS.includes(sCoinName as SupportStakeMarketCoins)) {\n try {\n const sCoin = await spoolQuickMethod.unstakeQuick(\n Number.MAX_SAFE_INTEGER,\n sCoinName as SupportStakeMarketCoins,\n );\n if (sCoin) {\n sCoins.push(sCoin);\n }\n } catch (e: any) {\n console.log(e);\n }\n }\n\n if (sCoins.length > 0) {\n const mergedSCoin = sCoins[0];\n if (sCoins.length > 1) {\n txBlock.mergeCoins(\n mergedSCoin as TransactionObjectArgument,\n sCoins.slice(1) as TransactionObjectArgument[],\n );\n }\n\n toTransfer.push(mergedSCoin);\n }\n }),\n );\n\n if (toTransfer.length > 0) {\n txBlock.transferObjects(toTransfer as TransactionObjectArgument[], this.params.walletAddress);\n }\n\n return txBlock;\n }\n\n public async migrateLendingWusdcToUsdcNative(\n poolCoinName: SupportPoolCoins,\n amount: number,\n slippage: number,\n validSwapAmount: string,\n unstakeAccount: { id: string; coin: number }[],\n ): Promise<TransactionBlock> {\n const txBlock = new TransactionBlock();\n const quickMethod = await generateCoreQuickMethod({\n builder: this.builder,\n txBlock,\n });\n const spoolQuickMethod = await generateSpoolQuickMethod({ builder: this.builder, txBlock });\n const sender = this.params.walletAddress;\n const withdrawCoins = [];\n\n const stakeMarketCoinName = this.utils.parseMarketCoinName(poolCoinName) as SupportStakeMarketCoins;\n const marketCoinType = this.utils.parseMarketCoinType(stakeMarketCoinName);\n const coins = await this.utils.selectCoinsMarketCoin(marketCoinType, sender);\n const coinIds = coins.map((value) => value.objectId);\n\n txBlock.setSender(sender);\n for (let i = 0; i < unstakeAccount.length; i++) {\n const account = unstakeAccount[i];\n const [marketCoin] = await spoolQuickMethod.unstakeQuick(account.coin, stakeMarketCoinName, account.id);\n if (marketCoin) {\n // If user has market coin object merge it\n if (coinIds.length > 0) {\n txBlock.mergeCoins(marketCoin, coinIds);\n }\n const wdCoin = quickMethod.normalMethod.withdraw(marketCoin, poolCoinName);\n withdrawCoins.push(wdCoin);\n }\n }\n\n // burn scoin then withdraw wusdc\n if (amount > 0) {\n const wdCoin = await quickMethod.withdrawQuick(amount, poolCoinName);\n withdrawCoins.push(wdCoin);\n }\n\n // Merge withdraw coins to one object\n if (withdrawCoins.length > 1) {\n txBlock.mergeCoins(withdrawCoins[0], withdrawCoins.slice(1));\n }\n const [coinSwap] = txBlock.splitCoins(withdrawCoins[0], [txBlock.pure(validSwapAmount)]);\n txBlock.transferObjects([withdrawCoins[0]], sender);\n\n const { swapResult: coinB, accountCap } = await this.deepbookSwap.swapToken({\n baseCoinName: 'wusdc',\n quoteCoinName: 'usdc',\n tokenObjectIn: coinSwap,\n tx: txBlock,\n });\n if (typeof accountCap === 'string') {\n txBlock.transferObjects([accountCap], sender);\n }\n\n SlippageTxBuilder.check_slippage(txBlock, coinB, slippage, validSwapAmount, this.query.utils.parseCoinType('usdc'));\n\n const mintedMarketCoin = quickMethod.normalMethod.deposit(coinB, 'usdc');\n await spoolQuickMethod.stakeQuick(mintedMarketCoin, 'susdc');\n return txBlock;\n }\n}\n","import type { SuiClient } from '@mysten/sui.js/client';\nimport { TransactionBlock } from '@mysten/sui.js/transactions';\n\nimport { ScallopAddress } from './scallopAddress';\nimport { ScallopQuery } from './scallopQuery';\nimport { ScallopUtils } from './scallopUtils';\nimport type {\n ScallopInstanceParams,\n ScallopBuilderParams,\n ScallopTxBlock,\n SupportMarketCoins,\n SupportAssetCoins,\n SupportSCoin,\n} from '../types';\n\n/**\n * @description\n * It provides methods for operating the transaction block, making it more convenient to organize transaction combinations.\n *\n * @example\n * ```typescript\n * const scallopBuilder = new ScallopBuilder(<parameters>);\n * await scallopBuilder.init();\n * const txBlock = scallopBuilder.<builder functions>();\n * ```\n */\nexport class ScallopBuilder {\n public readonly params: ScallopBuilderParams;\n\n public readonly isTestnet: boolean;\n\n public address: ScallopAddress;\n\n public query: ScallopQuery;\n\n public utils: ScallopUtils;\n\n public client: SuiClient;\n\n public constructor(params: ScallopBuilderParams, instance: Omit<ScallopInstanceParams, 'builder'>) {\n this.params = params;\n this.client = params.client;\n\n const { address, query, utils } = instance;\n this.address = address;\n this.query = query;\n this.utils = utils;\n this.isTestnet = params.networkType ? params.networkType === 'testnet' : false;\n }\n\n /**\n * Create a scallop txBlock instance that enhances transaction block.\n *\n * @param txBlock - Scallop txBlock, txBlock created by SuiKit, or original transaction block.\n * @return Scallop txBlock.\n */\n public createTxBlock(txBlock?: ScallopTxBlock | TransactionBlock) {\n return new TransactionBlock(txBlock);\n }\n\n /**\n * Specifying the sender's amount of coins to get coins args from transaction result.\n *\n * @param txBlock - Scallop txBlock or txBlock created by SuiKit .\n * @param assetCoinName - Specific support asset coin name.\n * @param amount - Amount of coins to be selected.\n * @param sender - Sender address.\n * @return Take coin and left coin.\n */\n public async selectCoin(\n txBlock: ScallopTxBlock,\n assetCoinName: SupportAssetCoins,\n amount: number,\n sender: string = this.params.walletAddress,\n ) {\n const coinType = this.utils.parseCoinType(assetCoinName);\n const coins = await this.utils.selectCoinIds(amount, coinType, sender);\n const [takeCoin, leftCoin] = this.utils.takeAmountFromCoins(txBlock, coins, amount);\n return { takeCoin, leftCoin };\n }\n\n /**\n * Specifying the sender's amount of market coins to get coins args from transaction result.\n *\n * @param txBlock - Scallop txBlock or txBlock created by SuiKit .\n * @param marketCoinName - Specific support market coin name.\n * @param amount - Amount of coins to be selected.\n * @param sender - Sender address.\n * @return Take coin and left coin.\n */\n public async selectMarketCoin(\n txBlock: TransactionBlock,\n marketCoinName: SupportMarketCoins,\n amount: number,\n sender: string = this.params.walletAddress,\n ) {\n const marketCoinType = this.utils.parseMarketCoinType(marketCoinName);\n const coins = await this.utils.selectCoins(amount, marketCoinType, sender);\n const totalAmount = coins.reduce((prev, coin) => {\n // eslint-disable-next-line no-param-reassign\n prev += Number(coin.balance);\n return prev;\n }, 0);\n const coinIds = coins.map((value) => value.objectId);\n const [takeCoin, leftCoin] = this.utils.takeAmountFromCoins(txBlock, coinIds, Math.min(amount, totalAmount));\n return { takeCoin, leftCoin, totalAmount };\n }\n\n /**\n * Specifying the sender's amount of sCoins to get coins args from transaction result.\n *\n * @param txBlock - Scallop txBlock or txBlock created by SuiKit .\n * @param marketCoinName - Specific support sCoin name.\n * @param amount - Amount of coins to be selected.\n * @param sender - Sender address.\n * @return Take coin and left coin.\n */\n public async selectSCoin(\n txBlock: TransactionBlock,\n sCoinName: SupportSCoin,\n amount: number,\n sender: string = this.params.walletAddress,\n ) {\n const sCoinType = this.utils.parseSCoinType(sCoinName);\n const coins = await this.utils.selectCoins(amount, sCoinType, sender);\n const coinIds = coins.map((coin) => coin.objectId);\n const totalAmount = coins.reduce((prev, coin) => prev + Number(coin.balance), 0);\n const [takeCoin, leftCoin] = this.utils.takeAmountFromCoins(txBlock, coinIds, Math.min(totalAmount, amount));\n return {\n takeCoin,\n leftCoin,\n totalAmount,\n };\n }\n}\n","import type { SuiObjectResponse, SuiObjectData } from '@mysten/sui.js/client';\nimport { TransactionBlock } from '@mysten/sui.js/transactions';\nimport BigNumber from 'bignumber.js';\n\nimport { SUPPORT_POOLS, PROTOCOL_OBJECT_ID } from '../constants';\nimport type { ScallopQuery } from '../models';\nimport {\n SupportAssetCoins,\n SupportPoolCoins,\n Obligation,\n CoinAmounts,\n MarketCoinAmounts,\n SupportMarketCoins,\n SuiAddressArg,\n ObligationQueryInterface,\n} from '../types';\n\n/**\n * Query all owned obligations.\n *\n * @param query - The Scallop query instance.\n * @param ownerAddress - The owner address.\n * @return Owned obligations.\n */\nexport const getObligations = async (query: ScallopQuery, ownerAddress: string) => {\n const owner = ownerAddress;\n const protocolObjectId = query.address.get('core.object') || PROTOCOL_OBJECT_ID;\n const keyObjectsResponse: SuiObjectResponse[] = [];\n let hasNextPage = false;\n let nextCursor: string | null = null;\n do {\n const paginatedKeyObjectsResponse = await query.client.getOwnedObjects({\n owner,\n filter: {\n StructType: `${protocolObjectId}::obligation::ObligationKey`,\n },\n cursor: nextCursor,\n });\n keyObjectsResponse.push(...paginatedKeyObjectsResponse.data);\n if (paginatedKeyObjectsResponse.hasNextPage && paginatedKeyObjectsResponse.nextCursor) {\n hasNextPage = true;\n nextCursor = paginatedKeyObjectsResponse.nextCursor;\n } else {\n hasNextPage = false;\n }\n } while (hasNextPage);\n\n const keyObjectIds: string[] = keyObjectsResponse\n .map((ref: any) => ref?.data?.objectId)\n .filter((id: any) => id !== undefined);\n const keyObjects = await query.client.multiGetObjects({\n ids: keyObjectIds,\n options: { showContent: true, showType: true },\n });\n const obligations: Obligation[] = [];\n for (let i = 0; i < keyObjects.length; i++) {\n const keyId = keyObjects[i].data.objectId;\n const { content } = keyObjects[i].data;\n if (content && 'fields' in content) {\n const fields = content.fields as any;\n const obligationId = String(fields.ownership.fields.of);\n const locked = await getObligationLocked(query, obligationId);\n obligations.push({ id: obligationId, keyId, locked });\n }\n }\n return obligations;\n};\n\n/**\n * Query obligation locked status.\n *\n * @param query - The Scallop query instance.\n * @param obligationId - The obligation id.\n * @return Obligation locked status.\n */\nexport const getObligationLocked = async (query: ScallopQuery, obligationId: string) => {\n const obligationObjectResponse = await query.client.getObject({\n id: obligationId,\n options: {\n showContent: true,\n },\n });\n let obligationLocked = false;\n if (\n obligationObjectResponse.data &&\n obligationObjectResponse?.data?.content?.dataType === 'moveObject' &&\n 'lock_key' in obligationObjectResponse.data.content.fields\n ) {\n obligationLocked = Boolean(obligationObjectResponse.data.content.fields.lock_key);\n }\n\n return obligationLocked;\n};\n\n/**\n * Query all owned coin amount.\n *\n * @param query - The Scallop query instance.\n * @param assetCoinNames - Specific an array of support asset coin name.\n * @param ownerAddress - The owner address.\n * @return All owned coin amounts.\n */\nexport const getCoinAmounts = async (\n query: ScallopQuery,\n ownerAddress: string,\n assetCoinNames?: SupportAssetCoins[],\n) => {\n const updatedAssetCoinNames = assetCoinNames || [...SUPPORT_POOLS];\n const owner = ownerAddress;\n const coinObjectsResponse: SuiObjectResponse[] = [];\n let hasNextPage = false;\n let nextCursor: string | null = null;\n do {\n const paginatedCoinObjectsResponse = await query.client.getOwnedObjects({\n owner,\n filter: {\n MatchAny: updatedAssetCoinNames.map((assetCoinName) => {\n const coinType = query.utils.parseCoinType(assetCoinName);\n return { StructType: `0x2::coin::Coin<${coinType}>` };\n }),\n },\n options: {\n showType: true,\n showContent: true,\n },\n cursor: nextCursor,\n });\n\n coinObjectsResponse.push(...paginatedCoinObjectsResponse.data);\n if (paginatedCoinObjectsResponse.hasNextPage && paginatedCoinObjectsResponse.nextCursor) {\n hasNextPage = true;\n nextCursor = paginatedCoinObjectsResponse.nextCursor;\n } else {\n hasNextPage = false;\n }\n } while (hasNextPage);\n\n const coinAmounts: CoinAmounts = {};\n const coinObjects = coinObjectsResponse\n .map((response) => response.data)\n .filter((object: any) => object !== undefined && object !== null) as SuiObjectData[];\n coinObjects.forEach((coinObject) => {\n const type = coinObject.type as string;\n if (coinObject.content && 'fields' in coinObject.content) {\n const fields = coinObject.content.fields as any;\n const poolCoinName = query.utils.parseCoinNameFromType<SupportPoolCoins>(type);\n if (poolCoinName) {\n coinAmounts[poolCoinName as SupportPoolCoins] = BigNumber(coinAmounts[poolCoinName as SupportPoolCoins] ?? 0)\n .plus(fields.balance)\n .toNumber();\n }\n }\n });\n return coinAmounts;\n};\n\n/**\n * Query owned coin amount.\n *\n * @param query - The Scallop query instance.\n * @param assetCoinName - Specific support asset coin name.\n * @param ownerAddress - The owner address.\n * @return Owned coin amount.\n */\nexport const getCoinAmount = async (query: ScallopQuery, assetCoinName: SupportAssetCoins, ownerAddress: string) => {\n const owner = ownerAddress;\n const coinType = query.utils.parseCoinType(assetCoinName);\n const coinObjectsResponse: SuiObjectResponse[] = [];\n let hasNextPage = false;\n let nextCursor: string | null = null;\n do {\n const paginatedCoinObjectsResponse = await query.client.getOwnedObjects({\n owner,\n filter: { StructType: `0x2::coin::Coin<${coinType}>` },\n options: {\n showContent: true,\n },\n cursor: nextCursor,\n });\n\n coinObjectsResponse.push(...paginatedCoinObjectsResponse.data);\n if (paginatedCoinObjectsResponse.hasNextPage && paginatedCoinObjectsResponse.nextCursor) {\n hasNextPage = true;\n nextCursor = paginatedCoinObjectsResponse.nextCursor;\n } else {\n hasNextPage = false;\n }\n } while (hasNextPage);\n\n let coinAmount = 0;\n const coinObjects = coinObjectsResponse\n .map((response) => response.data)\n .filter((object: any) => object !== undefined && object !== null) as SuiObjectData[];\n coinObjects.forEach((coinObject) => {\n if (coinObject.content && 'fields' in coinObject.content) {\n const fields = coinObject.content.fields as any;\n coinAmount = BigNumber(coinAmount).plus(fields.balance).toNumber();\n }\n });\n return coinAmount;\n};\n\n/**\n * Query all owned market coins (sCoin) amount.\n *\n * @param query - The Scallop query instance.\n * @param marketCoinNames - Specific an array of support market coin name.\n * @param ownerAddress - The owner address.\n * @return All owned market coins amount.\n */\nexport const getMarketCoinAmounts = async (\n query: ScallopQuery,\n ownerAddress: string,\n marketCoinNames?: SupportMarketCoins[],\n) => {\n const updatedMarketCoinNames =\n marketCoinNames || [...SUPPORT_POOLS].map((poolCoinName) => query.utils.parseMarketCoinName(poolCoinName));\n const owner = ownerAddress;\n const marketCoinObjectsResponse: SuiObjectResponse[] = [];\n let hasNextPage = false;\n let nextCursor: string | null = null;\n do {\n const paginatedMarketCoinObjectsResponse = await query.client.getOwnedObjects({\n owner,\n filter: {\n MatchAny: updatedMarketCoinNames.map((marketCoinName) => {\n const marketCoinType = query.utils.parseMarketCoinType(marketCoinName);\n return { StructType: `0x2::coin::Coin<${marketCoinType}>` };\n }),\n },\n options: {\n showType: true,\n showContent: true,\n },\n cursor: nextCursor,\n });\n\n marketCoinObjectsResponse.push(...paginatedMarketCoinObjectsResponse.data);\n if (paginatedMarketCoinObjectsResponse.hasNextPage && paginatedMarketCoinObjectsResponse.nextCursor) {\n hasNextPage = true;\n nextCursor = paginatedMarketCoinObjectsResponse.nextCursor;\n } else {\n hasNextPage = false;\n }\n } while (hasNextPage);\n\n const marketCoinAmounts: MarketCoinAmounts = {};\n const marketCoinObjects = marketCoinObjectsResponse\n .map((response) => response.data)\n .filter((object: any) => object !== undefined && object !== null) as SuiObjectData[];\n marketCoinObjects.forEach((marketCoinObject) => {\n const type = marketCoinObject.type as string;\n if (marketCoinObject.content && 'fields' in marketCoinObject.content) {\n const fields = marketCoinObject.content.fields as any;\n const marketCoinName = query.utils.parseCoinNameFromType<SupportMarketCoins>(type);\n if (marketCoinName) {\n marketCoinAmounts[marketCoinName as SupportMarketCoins] = BigNumber(\n marketCoinAmounts[marketCoinName as SupportMarketCoins] ?? 0,\n )\n .plus(fields.balance)\n .toNumber();\n }\n }\n });\n return marketCoinAmounts;\n};\n\n/**\n * Query owned market coin (sCoin) amount.\n *\n * @param query - The Scallop query instance.\n * @param marketCoinNames - Specific support market coin name.\n * @param ownerAddress - The owner address.\n * @return Owned market coin amount.\n */\nexport const getMarketCoinAmount = async (\n query: ScallopQuery,\n marketCoinName: SupportMarketCoins,\n ownerAddress: string,\n) => {\n const owner = ownerAddress;\n const marketCoinType = query.utils.parseMarketCoinType(marketCoinName);\n const marketCoinObjectsResponse: SuiObjectResponse[] = [];\n let hasNextPage = false;\n let nextCursor: string | null = null;\n do {\n const paginatedMarketCoinObjectsResponse = await query.client.getOwnedObjects({\n owner,\n filter: { StructType: `0x2::coin::Coin<${marketCoinType}>` },\n options: {\n showContent: true,\n },\n cursor: nextCursor,\n });\n\n marketCoinObjectsResponse.push(...paginatedMarketCoinObjectsResponse.data);\n if (paginatedMarketCoinObjectsResponse.hasNextPage && paginatedMarketCoinObjectsResponse.nextCursor) {\n hasNextPage = true;\n nextCursor = paginatedMarketCoinObjectsResponse.nextCursor;\n } else {\n hasNextPage = false;\n }\n } while (hasNextPage);\n\n let marketCoinAmount = 0;\n const marketCoinObjects = marketCoinObjectsResponse\n .map((response) => response.data)\n .filter((object: any) => object !== undefined && object !== null) as SuiObjectData[];\n marketCoinObjects.forEach((marketCoinObject) => {\n if (marketCoinObject.content && 'fields' in marketCoinObject.content) {\n const fields = marketCoinObject.content.fields as any;\n marketCoinAmount = BigNumber(marketCoinAmount).plus(fields.balance).toNumber();\n }\n });\n return marketCoinAmount;\n};\n\n/**\n * Query obligation data.\n *\n * @description\n * Use inspectTxn call to obtain the data provided in the scallop contract query module.\n *\n * @param query - The Scallop query instance.\n * @param obligationId - The obligation id.\n * @return Obligation data.\n */\nexport const queryObligation = async (query: ScallopQuery, obligationId: SuiAddressArg) => {\n const packageId = query.address.get('core.packages.query.id');\n const queryTarget = `${packageId}::obligation_query::obligation_data` as `${string}::${string}::${string}`;\n const txBlock = new TransactionBlock();\n txBlock.moveCall({\n target: queryTarget,\n arguments: [txBlock.object(obligationId as string)],\n });\n const queryResult = await query.client.devInspectTransactionBlock({\n transactionBlock: txBlock,\n sender: query.params.walletAddress,\n });\n return queryResult.events[0].parsedJson as ObligationQueryInterface;\n};\n","import type { SuiObjectResponse } from '@mysten/sui.js/client';\nimport { normalizeStructTag } from '@mysten/sui.js/utils';\n\nimport type { ScallopQuery } from '../models';\nimport type { StakePool, StakeRewardPool, StakeAccounts, SupportStakeMarketCoins, SupportStakeCoins } from '../types';\n\n/**\n * Get all stake accounts of the owner.\n *\n * @param query - The Scallop query instance.\n * @param ownerAddress - Owner address.\n * @return Stake accounts.\n */\nexport const getStakeAccounts = async (query: ScallopQuery, ownerAddress: string) => {\n const owner = ownerAddress;\n const spoolObjectId = query.address.get('spool.object');\n const stakeAccountType = `${spoolObjectId}::spool_account::SpoolAccount`;\n const stakeObjectsResponse: SuiObjectResponse[] = [];\n let hasNextPage = false;\n let nextCursor: string | null = null;\n do {\n const paginatedStakeObjectsResponse = await query.client.getOwnedObjects({\n owner,\n filter: { StructType: stakeAccountType },\n options: {\n showContent: true,\n showType: true,\n },\n cursor: nextCursor,\n });\n stakeObjectsResponse.push(...paginatedStakeObjectsResponse.data);\n if (paginatedStakeObjectsResponse.hasNextPage && paginatedStakeObjectsResponse.nextCursor) {\n hasNextPage = true;\n nextCursor = paginatedStakeObjectsResponse.nextCursor;\n } else {\n hasNextPage = false;\n }\n } while (hasNextPage);\n\n const stakeAccounts: StakeAccounts = {\n sweth: [],\n ssui: [],\n susdc: [],\n swusdc: [],\n swusdt: [],\n scetus: [],\n safsui: [],\n shasui: [],\n svsui: [],\n };\n\n const stakeMarketCoinTypes: Record<SupportStakeMarketCoins, string> = Object.keys(stakeAccounts).reduce(\n (types, stakeMarketCoinName) => {\n const stakeCoinName = query.utils.parseCoinName<SupportStakeCoins>(stakeMarketCoinName);\n const marketCoinType = query.utils.parseMarketCoinType(stakeCoinName);\n\n const updateTypes = { ...types };\n const newType = `${spoolObjectId}::spool_account::SpoolAccount<${marketCoinType}>`;\n updateTypes[stakeMarketCoinName as SupportStakeMarketCoins] = newType;\n return updateTypes;\n },\n {} as Record<SupportStakeMarketCoins, string>,\n );\n\n const stakeObjectIds: string[] = stakeObjectsResponse\n .map((ref: any) => ref?.data?.objectId)\n .filter((id: any) => id !== undefined);\n const stakeObjects = await query.client.multiGetObjects({\n ids: stakeObjectIds,\n options: { showContent: true, showType: true },\n });\n stakeObjects.forEach((stakeObject) => {\n const id = stakeObject.data.objectId;\n const type = stakeObject.data.type!;\n if (stakeObject.data.content && 'fields' in stakeObject.data.content) {\n const fields = stakeObject.data.content.fields as any;\n const stakePoolId = String(fields.spool_id);\n const stakeType = String(fields.stake_type.fields.name);\n const staked = Number(fields.stakes);\n const index = Number(fields.index);\n const points = Number(fields.points);\n const totalPoints = Number(fields.total_points);\n if (normalizeStructTag(type) === stakeMarketCoinTypes.sweth) {\n stakeAccounts.sweth.push({\n id,\n type: normalizeStructTag(type),\n stakePoolId,\n stakeType: normalizeStructTag(stakeType),\n staked,\n index,\n points,\n totalPoints,\n });\n } else if (normalizeStructTag(type) === stakeMarketCoinTypes.ssui) {\n stakeAccounts.ssui.push({\n id,\n type: normalizeStructTag(type),\n stakePoolId,\n stakeType: normalizeStructTag(stakeType),\n staked,\n index,\n points,\n totalPoints,\n });\n } else if (normalizeStructTag(type) === stakeMarketCoinTypes.swusdc) {\n stakeAccounts.swusdc.push({\n id,\n type: normalizeStructTag(type),\n stakePoolId,\n stakeType: normalizeStructTag(stakeType),\n staked,\n index,\n points,\n totalPoints,\n });\n } else if (normalizeStructTag(type) === stakeMarketCoinTypes.swusdt) {\n stakeAccounts.swusdt.push({\n id,\n type: normalizeStructTag(type),\n stakePoolId,\n stakeType: normalizeStructTag(stakeType),\n staked,\n index,\n points,\n totalPoints,\n });\n } else if (normalizeStructTag(type) === stakeMarketCoinTypes.scetus) {\n stakeAccounts.scetus.push({\n id,\n type: normalizeStructTag(type),\n stakePoolId,\n stakeType: normalizeStructTag(stakeType),\n staked,\n index,\n points,\n totalPoints,\n });\n } else if (normalizeStructTag(type) === stakeMarketCoinTypes.safsui) {\n stakeAccounts.safsui.push({\n id,\n type: normalizeStructTag(type),\n stakePoolId,\n stakeType: normalizeStructTag(stakeType),\n staked,\n index,\n points,\n totalPoints,\n });\n } else if (normalizeStructTag(type) === stakeMarketCoinTypes.shasui) {\n stakeAccounts.shasui.push({\n id,\n type: normalizeStructTag(type),\n stakePoolId,\n stakeType: normalizeStructTag(stakeType),\n staked,\n index,\n points,\n totalPoints,\n });\n } else if (normalizeStructTag(type) === stakeMarketCoinTypes.svsui) {\n stakeAccounts.svsui.push({\n id,\n type: normalizeStructTag(type),\n stakePoolId,\n stakeType: normalizeStructTag(stakeType),\n staked,\n index,\n points,\n totalPoints,\n });\n } else if (normalizeStructTag(type) === stakeMarketCoinTypes.susdc) {\n stakeAccounts.susdc.push({\n id,\n type: normalizeStructTag(type),\n stakePoolId,\n stakeType: normalizeStructTag(stakeType),\n staked,\n index,\n points,\n totalPoints,\n });\n }\n }\n });\n return stakeAccounts;\n};\n\n/**\n * Get stake pool data.\n *\n * @description\n * For backward compatible, it is recommended to use `getSpool` method\n * to get stake pool info in spool data.\n *\n * @param query - The Scallop query instance.\n * @param marketCoinName - Specific support stake market coin name.\n * @return Stake pool data.\n */\nexport const getStakePool = async (query: ScallopQuery, marketCoinName: SupportStakeMarketCoins) => {\n const poolId = query.address.get(`spool.pools.${marketCoinName}.id`);\n let stakePool: StakePool | undefined;\n const stakePoolObjectResponse = await query.client.getObject({\n id: poolId,\n options: {\n showContent: true,\n showType: true,\n },\n });\n if (stakePoolObjectResponse.data) {\n const stakePoolObject = stakePoolObjectResponse.data;\n const id = stakePoolObject.objectId;\n const type = stakePoolObject.type!;\n if (stakePoolObject.content && 'fields' in stakePoolObject.content) {\n const fields = stakePoolObject.content.fields as any;\n const maxPoint = Number(fields.max_distributed_point);\n const distributedPoint = Number(fields.distributed_point);\n const pointPerPeriod = Number(fields.distributed_point_per_period);\n const period = Number(fields.point_distribution_time);\n const maxStake = Number(fields.max_stakes);\n const stakeType = String(fields.stake_type.fields.name);\n const totalStaked = Number(fields.stakes);\n const index = Number(fields.index);\n const createdAt = Number(fields.created_at);\n const lastUpdate = Number(fields.last_update);\n stakePool = {\n id,\n type: normalizeStructTag(type),\n maxPoint,\n distributedPoint,\n pointPerPeriod,\n period,\n maxStake,\n stakeType: normalizeStructTag(stakeType),\n totalStaked,\n index,\n createdAt,\n lastUpdate,\n };\n }\n }\n return stakePool;\n};\n\n/**\n * Get stake reward pool of the owner.\n *\n * @description\n * For backward compatible, it is recommended to use `getSpool` method\n * to get reward info in spool data.\n *\n * @param query - The Scallop query instance.\n * @param marketCoinName - Specific support stake market coin name.\n * @return Stake reward pool.\n */\nexport const getStakeRewardPool = async (query: ScallopQuery, marketCoinName: SupportStakeMarketCoins) => {\n const poolId = query.address.get(`spool.pools.${marketCoinName}.rewardPoolId`);\n let stakeRewardPool: StakeRewardPool | undefined;\n const stakeRewardPoolObjectResponse = await query.client.getObject({\n id: poolId,\n options: {\n showContent: true,\n showType: true,\n },\n });\n if (stakeRewardPoolObjectResponse.data) {\n const stakeRewardPoolObject = stakeRewardPoolObjectResponse.data;\n const id = stakeRewardPoolObject.objectId;\n const type = stakeRewardPoolObject.type!;\n if (stakeRewardPoolObject.content && 'fields' in stakeRewardPoolObject.content) {\n const rewardPoolFields = stakeRewardPoolObject.content.fields as any;\n const stakePoolId = String(rewardPoolFields.spool_id);\n const ratioNumerator = Number(rewardPoolFields.exchange_rate_numerator);\n const ratioDenominator = Number(rewardPoolFields.exchange_rate_denominator);\n const rewards = Number(rewardPoolFields.rewards);\n const claimedRewards = Number(rewardPoolFields.claimed_rewards);\n\n stakeRewardPool = {\n id,\n type: normalizeStructTag(type),\n stakePoolId,\n ratioNumerator,\n ratioDenominator,\n rewards,\n claimedRewards,\n };\n }\n }\n return stakeRewardPool;\n};\n","import { SuiClient } from '@mysten/sui.js/client';\nimport { TransactionBlock } from '@mysten/sui.js/transactions';\nimport { normalizeStructTag } from '@mysten/sui.js/utils';\nimport BigNumber from 'bignumber.js';\n\nimport { SUPPORT_BORROW_INCENTIVE_POOLS } from '../constants';\nimport type { ScallopAddress, ScallopQuery } from '../models';\nimport type {\n BorrowIncentiveAccountsQueryInterface,\n BorrowIncentiveAccounts,\n SupportBorrowIncentiveCoins,\n BorrowIncentivePoolsQueryInterface,\n BorrowIncentivePools,\n OptionalKeys,\n BorrowIncentivePoolPoints,\n SupportBorrowIncentiveRewardCoins,\n} from '../types';\nimport { parseOriginBorrowIncentiveAccountData, parseOriginBorrowIncentivePoolData } from '../utils';\n\n/**\n * Query borrow incentive accounts data.\n *\n * @param query - The Scallop query instance.\n * @param borrowIncentiveCoinNames - Specific an array of support borrow incentive coin name.\n * @return Borrow incentive accounts data.\n */\nexport const queryBorrowIncentiveAccounts = async (\n query: ScallopQuery,\n obligationId: string,\n sender: string,\n borrowIncentiveCoinNames?: SupportBorrowIncentiveCoins[],\n) => {\n const coinName = borrowIncentiveCoinNames || [...SUPPORT_BORROW_INCENTIVE_POOLS];\n const queryPkgId = query.address.get('borrowIncentive.query');\n const incentiveAccountsId = query.address.get('borrowIncentive.incentiveAccounts');\n const queryTarget =\n `${queryPkgId}::incentive_account_query::incentive_account_data` as `${string}::${string}::${string}`;\n const txBlock = new TransactionBlock();\n txBlock.moveCall({\n target: queryTarget,\n arguments: [txBlock.object(incentiveAccountsId), txBlock.object(obligationId)],\n });\n const queryResult = await query.client.devInspectTransactionBlock({\n transactionBlock: txBlock,\n sender,\n });\n const borrowIncentiveAccountsQueryData = queryResult.events[0].parsedJson as BorrowIncentiveAccountsQueryInterface;\n\n const borrowIncentiveAccounts: BorrowIncentiveAccounts = {};\n\n borrowIncentiveAccountsQueryData.pool_records.forEach((accountData) => {\n const parsedBorrowIncentiveAccount = parseOriginBorrowIncentiveAccountData(accountData);\n const { poolType } = parsedBorrowIncentiveAccount;\n const parsedCoinName = query.utils.parseCoinNameFromType<SupportBorrowIncentiveCoins>(poolType);\n if (coinName.length >= 1 && coinName.includes(parsedCoinName)) {\n borrowIncentiveAccounts[parsedCoinName] = parsedBorrowIncentiveAccount;\n }\n }, {} as BorrowIncentiveAccounts);\n return borrowIncentiveAccounts;\n};\n\n/**\n * Query borrow incentive pools data.\n *\n * @param query - The Scallop query instance.\n * @param borrowIncentiveCoinNames - Specific an array of support borrow incentive coin name.\n * @param indexer - Whether to use indexer.\n * @return Borrow incentive pools data.\n */\nexport const queryBorrowIncentivePools = async (query: ScallopQuery, coinNames?: SupportBorrowIncentiveCoins[]) => {\n const borrowIncentiveCoinNames = coinNames || [...SUPPORT_BORROW_INCENTIVE_POOLS];\n const queryPkgId = query.address.get('borrowIncentive.query');\n const incentivePoolsId = query.address.get('borrowIncentive.incentivePools');\n\n const txBlock = new TransactionBlock();\n const queryTarget = `${queryPkgId}::incentive_pools_query::incentive_pools_data` as `${string}::${string}::${string}`;\n txBlock.moveCall({ target: queryTarget, arguments: [txBlock.object(incentivePoolsId)] });\n const queryResult = await query.client.devInspectTransactionBlock({\n transactionBlock: txBlock,\n sender: query.params.walletAddress,\n });\n const borrowIncentivePoolsQueryData = queryResult.events[0].parsedJson as BorrowIncentivePoolsQueryInterface;\n\n const borrowIncentivePools: BorrowIncentivePools = {};\n\n for (let i = 0; i < borrowIncentivePoolsQueryData.incentive_pools.length; i++) {\n const pool = borrowIncentivePoolsQueryData.incentive_pools[i];\n const borrowIncentivePoolPoints: OptionalKeys<Record<'sui' | 'sca', BorrowIncentivePoolPoints>> = {};\n const parsedBorrowIncentivePoolData = parseOriginBorrowIncentivePoolData(pool);\n const poolCoinType = normalizeStructTag(pool.pool_type.name);\n const poolCoinName = query.utils.parseCoinNameFromType<SupportBorrowIncentiveCoins>(poolCoinType);\n\n // Filter pools not yet supported by the SDK.\n if (!borrowIncentiveCoinNames.includes(poolCoinName)) {\n continue;\n }\n // pool points for borrow incentive reward ('sui' and 'sca')\n\n Object.entries(parsedBorrowIncentivePoolData.poolPoints).forEach(([coinName, poolPoint]) => {\n const baseIndexRate = 1_000_000_000;\n const rewardCoinType = normalizeStructTag(poolPoint.pointType);\n const rewardCoinName = query.utils.parseCoinNameFromType<SupportBorrowIncentiveRewardCoins>(rewardCoinType);\n const timeDelta = BigNumber(Math.floor(new Date().getTime() / 1000) - poolPoint.lastUpdate)\n .dividedBy(poolPoint.period)\n .toFixed(0);\n\n const accumulatedPoints = BigNumber.minimum(\n BigNumber(timeDelta).multipliedBy(poolPoint.distributedPointPerPeriod),\n BigNumber(poolPoint.points),\n );\n\n const currentPointIndex = BigNumber(poolPoint.index).plus(\n accumulatedPoints.dividedBy(poolPoint.weightedAmount).isFinite()\n ? BigNumber(baseIndexRate).multipliedBy(accumulatedPoints).dividedBy(poolPoint.weightedAmount)\n : 0,\n );\n borrowIncentivePoolPoints[coinName as SupportBorrowIncentiveRewardCoins] = {\n points: poolPoint.points,\n coinDecimal: query.utils.getCoinDecimal(rewardCoinName),\n distributedPoint: poolPoint.distributedPoint,\n weightedAmount: poolPoint.weightedAmount,\n currentPointIndex: currentPointIndex.toNumber(),\n };\n });\n\n borrowIncentivePools[poolCoinName] = {\n coinName: poolCoinName,\n symbol: query.utils.parseSymbol(poolCoinName),\n coinType: poolCoinType,\n points: borrowIncentivePoolPoints,\n };\n }\n\n return borrowIncentivePools;\n};\n\nexport const getBindedVeScaKey = async (\n {\n address,\n client,\n }: {\n address: ScallopAddress;\n client: SuiClient;\n },\n obligationId: string,\n): Promise<string | null> => {\n const borrowIncentiveObjectId = address.get('borrowIncentive.object');\n const incentiveAccountsId = address.get('borrowIncentive.incentiveAccounts');\n const corePkg = address.get('core.object');\n\n // get IncentiveAccounts object\n const incentiveAccountsObject = await client.getObject({\n id: incentiveAccountsId,\n options: {\n showContent: true,\n },\n });\n if (incentiveAccountsObject?.data?.content?.dataType !== 'moveObject') {\n return null;\n }\n const incentiveAccountsTableId = (incentiveAccountsObject.data.content.fields as any).accounts.fields.id.id;\n\n // Search in the table\n const bindedIncentiveAcc = await client.getDynamicFieldObject({\n parentId: incentiveAccountsTableId,\n name: {\n type: `${borrowIncentiveObjectId}::typed_id::TypedID<${corePkg}::obligation::Obligation>`,\n value: obligationId,\n },\n });\n\n if (bindedIncentiveAcc?.data?.content?.dataType !== 'moveObject') {\n return null;\n }\n const bindedIncentiveAccFields = bindedIncentiveAcc.data.content.fields as any;\n\n return bindedIncentiveAccFields.value.fields.binded_ve_sca_key?.fields.id ?? null;\n};\n","import { TransactionBlock } from '@mysten/sui.js/transactions';\n\nimport {\n MAX_LOCK_DURATION,\n MAX_LOCK_ROUNDS,\n MIN_INITIAL_LOCK_AMOUNT,\n MIN_TOP_UP_AMOUNT,\n UNLOCK_ROUND_DURATION,\n} from '../constants';\nimport { SuiObjectArg } from '../types';\n\n/**\n * Check and get the sender from the transaction block.\n *\n * @param txBlock - TxBlock created by SuiKit.\n * @return Sender of transaction.\n */\nexport const requireSender = (txBlock: TransactionBlock) => {\n const { sender } = txBlock.blockData;\n if (!sender) {\n throw new Error('Sender is required');\n }\n return sender;\n};\n\nexport const checkLockSca = (\n scaAmountOrCoin?: number | SuiObjectArg | undefined,\n lockPeriodInDays?: number,\n newUnlockAtInSecondTimestamp?: number,\n prevUnlockAtInSecondTimestamp?: number,\n) => {\n const isInitialLock = !prevUnlockAtInSecondTimestamp;\n const isLockExpired = !isInitialLock && prevUnlockAtInSecondTimestamp * 1000 <= new Date().getTime();\n if (isInitialLock || isLockExpired) {\n if (scaAmountOrCoin !== undefined && lockPeriodInDays !== undefined) {\n if (lockPeriodInDays <= 0) {\n throw new Error('Lock period must be greater than 0');\n }\n if (typeof scaAmountOrCoin === 'number' && scaAmountOrCoin < MIN_INITIAL_LOCK_AMOUNT) {\n throw new Error(\n `Minimum lock amount for ${isLockExpired ? 'renewing expired veSca' : 'initial lock'} is 10 SCA`,\n );\n }\n const extendLockPeriodInSecond = lockPeriodInDays * UNLOCK_ROUND_DURATION;\n if (extendLockPeriodInSecond > MAX_LOCK_DURATION) {\n throw new Error(`Maximum lock period is ~4 years (${MAX_LOCK_ROUNDS} days)`);\n }\n } else {\n throw new Error(\n `SCA amount and lock period is required for ${isLockExpired ? 'renewing expired veSca' : 'initial lock'}`,\n );\n }\n } else {\n checkVesca(prevUnlockAtInSecondTimestamp);\n if (typeof scaAmountOrCoin === 'number' && scaAmountOrCoin < MIN_TOP_UP_AMOUNT) {\n throw new Error('Minimum top up amount is 1 SCA');\n }\n\n if (!!newUnlockAtInSecondTimestamp && !!prevUnlockAtInSecondTimestamp) {\n const totalLockDuration = newUnlockAtInSecondTimestamp - prevUnlockAtInSecondTimestamp;\n if (totalLockDuration > MAX_LOCK_DURATION - UNLOCK_ROUND_DURATION) {\n throw new Error(`Maximum lock period is ~4 years (${MAX_LOCK_ROUNDS - 1} days)`);\n }\n }\n }\n};\n\nexport const checkExtendLockPeriod = (\n lockPeriodInDays: number,\n newUnlockAtInSecondTimestamp: number,\n prevUnlockAtInSecondTimestamp?: number,\n) => {\n checkVesca(prevUnlockAtInSecondTimestamp);\n\n if (lockPeriodInDays <= 0) {\n throw new Error('Lock period must be greater than 0');\n }\n\n const isInitialLock = !prevUnlockAtInSecondTimestamp;\n const isLockExpired = !isInitialLock && prevUnlockAtInSecondTimestamp * 1000 <= new Date().getTime();\n if (isLockExpired) {\n throw new Error('veSca is expired, use renewExpiredVeScaQuick instead');\n }\n\n if (prevUnlockAtInSecondTimestamp) {\n const totalLockDuration = newUnlockAtInSecondTimestamp - (prevUnlockAtInSecondTimestamp ?? 0);\n if (totalLockDuration > MAX_LOCK_DURATION - UNLOCK_ROUND_DURATION) {\n throw new Error(`Maximum lock period is ~4 years (${MAX_LOCK_ROUNDS - 1} days)`);\n }\n }\n};\n\nexport const checkExtendLockAmount = (scaAmount: number, prevUnlockAtInSecondTimestamp?: number) => {\n checkVesca(prevUnlockAtInSecondTimestamp);\n\n if (scaAmount < MIN_TOP_UP_AMOUNT) {\n throw new Error('Minimum top up amount is 1 SCA');\n }\n\n const isInitialLock = !prevUnlockAtInSecondTimestamp;\n const isLockExpired = !isInitialLock && prevUnlockAtInSecondTimestamp * 1000 <= new Date().getTime();\n if (isLockExpired) {\n throw new Error('veSca is expired, use renewExpiredVeScaQuick instead');\n }\n};\n\nexport const checkRenewExpiredVeSca = (\n scaAmount: number,\n lockPeriodInDays: number,\n prevUnlockAtInSecondTimestamp?: number,\n) => {\n checkVesca(prevUnlockAtInSecondTimestamp);\n\n if (scaAmount < MIN_INITIAL_LOCK_AMOUNT) {\n throw new Error('Minimum lock amount for renewing expired vesca 10 SCA');\n }\n\n const extendLockPeriodInSecond = lockPeriodInDays * UNLOCK_ROUND_DURATION;\n if (extendLockPeriodInSecond >= MAX_LOCK_DURATION - UNLOCK_ROUND_DURATION) {\n throw new Error(`Maximum lock period is ~4 years (${MAX_LOCK_ROUNDS - 1} days)`);\n }\n};\n\nexport const checkVesca = (prevUnlockAtInSecondTimestamp?: number) => {\n if (prevUnlockAtInSecondTimestamp === undefined) {\n throw new Error('veSca not found');\n }\n};\n","import { normalizeStructTag, parseStructTag } from '@mysten/sui.js/utils';\n// eslint-disable-next-line import/no-extraneous-dependencies\nimport BigNumber from 'bignumber.js';\n\nimport type { ScallopUtils } from '../models';\nimport type {\n OriginMarketPoolData,\n ParsedMarketPoolData,\n CalculatedMarketPoolData,\n OriginMarketCollateralData,\n ParsedMarketCollateralData,\n CalculatedMarketCollateralData,\n OriginSpoolData,\n ParsedSpoolData,\n CalculatedSpoolData,\n OriginSpoolRewardPoolData,\n ParsedSpoolRewardPoolData,\n CalculatedSpoolRewardPoolData,\n OriginBorrowIncentivePoolData,\n ParsedBorrowIncentivePoolData,\n OriginBorrowIncentiveAccountData,\n ParsedBorrowIncentiveAccountData,\n SupportPoolCoins,\n SupportCollateralCoins,\n OriginBorrowIncentiveAccountPoolData,\n ParsedBorrowIncentiveAccountPoolData,\n SupportBorrowIncentiveRewardCoins,\n ParsedBorrowIncentivePoolPointData,\n OriginBorrowIncentivePoolPointData,\n} from '../types';\n\n/**\n * Parse origin market pool data to a more readable format.\n *\n * @param originMarketPoolData - Origin market pool data\n * @return Parsed market pool data\n */\nexport const parseOriginMarketPoolData = (originMarketPoolData: OriginMarketPoolData): ParsedMarketPoolData => ({\n coinType: normalizeStructTag(originMarketPoolData.type.name),\n // Parse origin data required for basic calculations.\n maxBorrowRate: Number(originMarketPoolData.maxBorrowRate.value) / 2 ** 32,\n borrowRate: Number(originMarketPoolData.interestRate.value) / 2 ** 32,\n borrowRateScale: Number(originMarketPoolData.interestRateScale),\n borrowIndex: Number(originMarketPoolData.borrowIndex),\n lastUpdated: Number(originMarketPoolData.lastUpdated),\n cashAmount: Number(originMarketPoolData.cash),\n debtAmount: Number(originMarketPoolData.debt),\n marketCoinSupplyAmount: Number(originMarketPoolData.marketCoinSupply),\n reserveAmount: Number(originMarketPoolData.reserve),\n reserveFactor: Number(originMarketPoolData.reserveFactor.value) / 2 ** 32,\n borrowWeight: Number(originMarketPoolData.borrowWeight.value) / 2 ** 32,\n borrowFee: Number(originMarketPoolData.borrowFeeRate.value) / 2 ** 32,\n // Parse origin data required for additional display.\n baseBorrowRate: Number(originMarketPoolData.baseBorrowRatePerSec.value) / 2 ** 32,\n borrowRateOnHighKink: Number(originMarketPoolData.borrowRateOnHighKink.value) / 2 ** 32,\n borrowRateOnMidKink: Number(originMarketPoolData.borrowRateOnMidKink.value) / 2 ** 32,\n highKink: Number(originMarketPoolData.highKink.value) / 2 ** 32,\n midKink: Number(originMarketPoolData.midKink.value) / 2 ** 32,\n minBorrowAmount: Number(originMarketPoolData.minBorrowAmount),\n});\n\nexport const calculateMarketPoolData = (\n utils: ScallopUtils,\n parsedMarketPoolData: ParsedMarketPoolData,\n): CalculatedMarketPoolData => {\n const poolCoinName = utils.parseCoinNameFromType<SupportPoolCoins>(parsedMarketPoolData.coinType);\n const coinDecimal = utils.getCoinDecimal(poolCoinName);\n\n const borrowYearFactor = 24 * 365 * 3600;\n\n const baseBorrowApr = (parsedMarketPoolData.baseBorrowRate * borrowYearFactor) / parsedMarketPoolData.borrowRateScale;\n const borrowAprOnHighKink =\n (parsedMarketPoolData.borrowRateOnHighKink * borrowYearFactor) / parsedMarketPoolData.borrowRateScale;\n const borrowAprOnMidKink =\n (parsedMarketPoolData.borrowRateOnMidKink * borrowYearFactor) / parsedMarketPoolData.borrowRateScale;\n const maxBorrowApr = (parsedMarketPoolData.maxBorrowRate * borrowYearFactor) / parsedMarketPoolData.borrowRateScale;\n const borrowApr = (parsedMarketPoolData.borrowRate * borrowYearFactor) / parsedMarketPoolData.borrowRateScale;\n\n const timeDelta = Math.floor(new Date().getTime() / 1000) - parsedMarketPoolData.lastUpdated;\n const borrowIndexDelta = BigNumber(parsedMarketPoolData.borrowIndex)\n .multipliedBy(BigNumber(timeDelta).multipliedBy(parsedMarketPoolData.borrowRate))\n .dividedBy(parsedMarketPoolData.borrowRateScale);\n const currentBorrowIndex = BigNumber(parsedMarketPoolData.borrowIndex).plus(borrowIndexDelta);\n // How much accumulated interest since `lastUpdate`.\n const growthInterest = BigNumber(currentBorrowIndex).dividedBy(parsedMarketPoolData.borrowIndex).minus(1);\n const increasedDebtAmount = BigNumber(parsedMarketPoolData.debtAmount).multipliedBy(growthInterest);\n const borrowAmount = increasedDebtAmount.plus(parsedMarketPoolData.debtAmount);\n const borrowCoin = borrowAmount.shiftedBy(-1 * coinDecimal);\n const reserveAmount = BigNumber(parsedMarketPoolData.reserveAmount).plus(\n increasedDebtAmount.multipliedBy(parsedMarketPoolData.reserveFactor),\n );\n const reserveCoin = reserveAmount.shiftedBy(-1 * coinDecimal);\n const supplyAmount = BigNumber(borrowAmount).plus(\n Math.max(parsedMarketPoolData.cashAmount - reserveAmount.toNumber(), 0),\n );\n const supplyCoin = supplyAmount.shiftedBy(-1 * coinDecimal);\n let utilizationRate = BigNumber(borrowAmount).dividedBy(supplyAmount);\n utilizationRate = utilizationRate.isFinite() ? utilizationRate : BigNumber(0);\n let supplyApr = BigNumber(borrowApr)\n .multipliedBy(utilizationRate)\n .multipliedBy(1 - parsedMarketPoolData.reserveFactor);\n supplyApr = supplyApr.isFinite() ? supplyApr : BigNumber(0);\n let conversionRate = supplyAmount.dividedBy(parsedMarketPoolData.marketCoinSupplyAmount);\n conversionRate = conversionRate.isFinite() && !conversionRate.isNaN() ? conversionRate : BigNumber(1);\n\n return {\n baseBorrowApr,\n baseBorrowApy: utils.parseAprToApy(baseBorrowApr),\n borrowAprOnHighKink,\n borrowApyOnHighKink: utils.parseAprToApy(borrowAprOnHighKink),\n borrowAprOnMidKink,\n borrowApyOnMidKink: utils.parseAprToApy(borrowAprOnMidKink),\n maxBorrowApr,\n maxBorrowApy: utils.parseAprToApy(maxBorrowApr),\n borrowApr: Math.min(borrowApr, maxBorrowApr),\n borrowApy: Math.min(utils.parseAprToApy(borrowApr), utils.parseAprToApy(maxBorrowApr)),\n borrowIndex: currentBorrowIndex.toNumber(),\n growthInterest: growthInterest.toNumber(),\n supplyAmount: supplyAmount.toNumber(),\n supplyCoin: supplyCoin.toNumber(),\n borrowAmount: borrowAmount.toNumber(),\n borrowCoin: borrowCoin.toNumber(),\n reserveAmount: reserveAmount.toNumber(),\n reserveCoin: reserveCoin.toNumber(),\n utilizationRate: utilizationRate.toNumber(),\n supplyApr: supplyApr.toNumber(),\n supplyApy: utils.parseAprToApy(supplyApr.toNumber()),\n conversionRate: conversionRate.toNumber(),\n };\n};\n\n/**\n * Parse origin market collateral data to a more readable format.\n *\n * @param originMarketCollateralData - Origin market collateral data\n * @return Parsed market collateral data\n */\nexport const parseOriginMarketCollateralData = (\n originMarketCollateralData: OriginMarketCollateralData,\n): ParsedMarketCollateralData => ({\n coinType: normalizeStructTag(originMarketCollateralData.type.name),\n collateralFactor: Number(originMarketCollateralData.collateralFactor.value) / 2 ** 32,\n liquidationFactor: Number(originMarketCollateralData.liquidationFactor.value) / 2 ** 32,\n liquidationDiscount: Number(originMarketCollateralData.liquidationDiscount.value) / 2 ** 32,\n liquidationPanelty: Number(originMarketCollateralData.liquidationPanelty.value) / 2 ** 32,\n liquidationReserveFactor: Number(originMarketCollateralData.liquidationReserveFactor.value) / 2 ** 32,\n maxCollateralAmount: Number(originMarketCollateralData.maxCollateralAmount),\n totalCollateralAmount: Number(originMarketCollateralData.totalCollateralAmount),\n});\n\nexport const calculateMarketCollateralData = (\n utils: ScallopUtils,\n parsedMarketCollateralData: ParsedMarketCollateralData,\n): CalculatedMarketCollateralData => {\n const collateralCoinName = utils.parseCoinNameFromType<SupportCollateralCoins>(parsedMarketCollateralData.coinType);\n const coinDecimal = utils.getCoinDecimal(collateralCoinName);\n\n const maxCollateralCoin = BigNumber(parsedMarketCollateralData.maxCollateralAmount).shiftedBy(-1 * coinDecimal);\n const depositCoin = BigNumber(parsedMarketCollateralData.totalCollateralAmount).shiftedBy(-1 * coinDecimal);\n\n return {\n maxDepositAmount: parsedMarketCollateralData.maxCollateralAmount,\n maxDepositCoin: maxCollateralCoin.toNumber(),\n depositAmount: parsedMarketCollateralData.totalCollateralAmount,\n depositCoin: depositCoin.toNumber(),\n };\n};\n\n/**\n * Parse origin spool data to a more readable format.\n *\n * @param originSpoolData - Origin spool data\n * @return Parsed spool data\n */\nexport const parseOriginSpoolData = (originSpoolData: OriginSpoolData): ParsedSpoolData => ({\n stakeType: normalizeStructTag(originSpoolData.stakeType.fields.name),\n maxPoint: Number(originSpoolData.maxDistributedPoint),\n distributedPoint: Number(originSpoolData.distributedPoint),\n pointPerPeriod: Number(originSpoolData.distributedPointPerPeriod),\n period: Number(originSpoolData.pointDistributionTime),\n maxStake: Number(originSpoolData.maxStake),\n staked: Number(originSpoolData.stakes),\n index: Number(originSpoolData.index),\n createdAt: Number(originSpoolData.createdAt),\n lastUpdate: Number(originSpoolData.lastUpdate),\n});\n\nexport const calculateSpoolData = (\n parsedSpoolData: ParsedSpoolData,\n stakeMarketCoinPrice: number,\n stakeMarketCoinDecimal: number,\n): CalculatedSpoolData => {\n const baseIndexRate = 1_000_000_000;\n\n const distributedPointPerSec = BigNumber(parsedSpoolData.pointPerPeriod).dividedBy(parsedSpoolData.period);\n\n const pointPerSec = BigNumber(parsedSpoolData.pointPerPeriod).dividedBy(parsedSpoolData.period);\n const remainingPeriod = BigNumber(parsedSpoolData.maxPoint)\n .minus(parsedSpoolData.distributedPoint)\n .dividedBy(pointPerSec);\n const startDate = parsedSpoolData.createdAt;\n const endDate = remainingPeriod.plus(parsedSpoolData.lastUpdate).integerValue().toNumber();\n\n const timeDelta = BigNumber(Math.floor(new Date().getTime() / 1000) - parsedSpoolData.lastUpdate)\n .dividedBy(parsedSpoolData.period)\n .toFixed(0);\n const remainingPoints = BigNumber(parsedSpoolData.maxPoint).minus(parsedSpoolData.distributedPoint);\n const accumulatedPoints = BigNumber.minimum(\n BigNumber(timeDelta).multipliedBy(parsedSpoolData.pointPerPeriod),\n remainingPoints,\n );\n\n const currentPointIndex = BigNumber(parsedSpoolData.index).plus(\n accumulatedPoints.dividedBy(parsedSpoolData.staked).isFinite()\n ? BigNumber(baseIndexRate).multipliedBy(accumulatedPoints).dividedBy(parsedSpoolData.staked)\n : 0,\n );\n const currentTotalDistributedPoint = BigNumber(parsedSpoolData.distributedPoint).plus(accumulatedPoints);\n\n const stakedAmount = BigNumber(parsedSpoolData.staked);\n const stakedCoin = stakedAmount.shiftedBy(-1 * stakeMarketCoinDecimal);\n const stakedValue = stakedCoin.multipliedBy(stakeMarketCoinPrice);\n\n return {\n distributedPointPerSec: distributedPointPerSec.toNumber(),\n accumulatedPoints: accumulatedPoints.toNumber(),\n currentPointIndex: currentPointIndex.toNumber(),\n currentTotalDistributedPoint: currentTotalDistributedPoint.toNumber(),\n startDate: new Date(startDate * 1000),\n endDate: new Date(endDate * 1000),\n stakedAmount: stakedAmount.toNumber(),\n stakedCoin: stakedCoin.toNumber(),\n stakedValue: stakedValue.toNumber(),\n };\n};\n\n/**\n * Parse origin spool reward pool data to a more readable format.\n *\n * @param originRewardPoolData - Origin reward pool data\n * @return Parsed spool reward pool data\n */\nexport const parseOriginSpoolRewardPoolData = (\n originSpoolRewardPoolData: OriginSpoolRewardPoolData,\n): ParsedSpoolRewardPoolData => ({\n claimedRewards: Number(originSpoolRewardPoolData.claimed_rewards),\n exchangeRateDenominator: Number(originSpoolRewardPoolData.exchange_rate_denominator),\n exchangeRateNumerator: Number(originSpoolRewardPoolData.exchange_rate_numerator),\n rewards: Number(originSpoolRewardPoolData.rewards),\n spoolId: String(originSpoolRewardPoolData.spool_id),\n});\n\nexport const calculateSpoolRewardPoolData = (\n parsedSpoolData: ParsedSpoolData,\n parsedSpoolRewardPoolData: ParsedSpoolRewardPoolData,\n calculatedSpoolData: CalculatedSpoolData,\n rewardCoinPrice: number,\n rewardCoinDecimal: number,\n): CalculatedSpoolRewardPoolData => {\n const rateYearFactor = 365 * 24 * 60 * 60;\n\n const rewardPerSec = BigNumber(calculatedSpoolData.distributedPointPerSec)\n .multipliedBy(parsedSpoolRewardPoolData.exchangeRateNumerator)\n .dividedBy(parsedSpoolRewardPoolData.exchangeRateDenominator);\n const totalRewardAmount = BigNumber(parsedSpoolData.maxPoint)\n .multipliedBy(parsedSpoolRewardPoolData.exchangeRateNumerator)\n .dividedBy(parsedSpoolRewardPoolData.exchangeRateDenominator);\n const totalRewardCoin = totalRewardAmount.shiftedBy(-1 * rewardCoinDecimal);\n const totalRewardValue = totalRewardCoin.multipliedBy(rewardCoinPrice);\n const remaindRewardAmount = BigNumber(parsedSpoolRewardPoolData.rewards);\n const remaindRewardCoin = remaindRewardAmount.shiftedBy(-1 * rewardCoinDecimal);\n const remaindRewardValue = remaindRewardCoin.multipliedBy(rewardCoinPrice);\n const claimedRewardAmount = BigNumber(parsedSpoolRewardPoolData.claimedRewards);\n const claimedRewardCoin = claimedRewardAmount.shiftedBy(-1 * rewardCoinDecimal);\n const claimedRewardValue = claimedRewardCoin.multipliedBy(rewardCoinPrice);\n\n const rewardValueForYear = BigNumber(rewardPerSec)\n .shiftedBy(-1 * rewardCoinDecimal)\n .multipliedBy(rateYearFactor)\n .multipliedBy(rewardCoinPrice);\n\n let rewardRate = rewardValueForYear.dividedBy(calculatedSpoolData.stakedValue).isFinite()\n ? rewardValueForYear.dividedBy(calculatedSpoolData.stakedValue).toNumber()\n : Infinity;\n\n if (parsedSpoolData.maxPoint === parsedSpoolData.distributedPoint) {\n rewardRate = Infinity;\n }\n\n return {\n rewardApr: rewardRate,\n totalRewardAmount: totalRewardAmount.toNumber(),\n totalRewardCoin: totalRewardCoin.toNumber(),\n totalRewardValue: totalRewardValue.toNumber(),\n remaindRewardAmount: remaindRewardAmount.toNumber(),\n remaindRewardCoin: remaindRewardCoin.toNumber(),\n remaindRewardValue: remaindRewardValue.toNumber(),\n claimedRewardAmount: claimedRewardAmount.toNumber(),\n claimedRewardCoin: claimedRewardCoin.toNumber(),\n claimedRewardValue: claimedRewardValue.toNumber(),\n rewardPerSec: rewardPerSec.toNumber(),\n };\n};\n\n/**\n * Parse origin borrow incentive pool data to a more readable format.\n *\n * @param originBorrowIncentivePoolData - Origin borrow incentive pool data\n * @return Parsed borrow incentive pool data\n */\nexport const parseOriginBorrowIncentivesPoolPointData = (\n originBorrowIncentivePoolPointData: OriginBorrowIncentivePoolPointData,\n): ParsedBorrowIncentivePoolPointData => ({\n pointType: normalizeStructTag(originBorrowIncentivePoolPointData.point_type.name),\n distributedPointPerPeriod: Number(originBorrowIncentivePoolPointData.distributed_point_per_period),\n period: Number(originBorrowIncentivePoolPointData.point_distribution_time),\n distributedPoint: Number(originBorrowIncentivePoolPointData.distributed_point),\n points: Number(originBorrowIncentivePoolPointData.points),\n index: Number(originBorrowIncentivePoolPointData.index),\n baseWeight: Number(originBorrowIncentivePoolPointData.base_weight),\n weightedAmount: Number(originBorrowIncentivePoolPointData.weighted_amount),\n lastUpdate: Number(originBorrowIncentivePoolPointData.last_update),\n});\nexport const parseOriginBorrowIncentivePoolData = (\n originBorrowIncentivePoolData: OriginBorrowIncentivePoolData,\n): ParsedBorrowIncentivePoolData => ({\n poolType: normalizeStructTag(originBorrowIncentivePoolData.pool_type.name),\n minStakes: Number(originBorrowIncentivePoolData.min_stakes),\n maxStakes: Number(originBorrowIncentivePoolData.max_stakes),\n staked: Number(originBorrowIncentivePoolData.stakes),\n createdAt: Number(originBorrowIncentivePoolData.created_at),\n poolPoints: originBorrowIncentivePoolData.points.reduce(\n (acc, point) => {\n const parsed = parseOriginBorrowIncentivesPoolPointData(point);\n const name = parseStructTag(parsed.pointType).name.toLowerCase() as SupportBorrowIncentiveRewardCoins;\n acc[name] = parsed;\n return acc;\n },\n {} as Record<SupportBorrowIncentiveRewardCoins, ParsedBorrowIncentivePoolPointData>,\n ),\n});\n\n/**\n * Parse origin borrow incentive reward pool data to a more readable format.\n *\n * @param originBorrowIncentiveRewardPoolData - Origin borrow incentive reward pool data\n * @return Parsed borrow incentive reward pool data\n */\n\nexport const minBigNumber = (...args: BigNumber.Value[]) =>\n BigNumber(args.reduce((min, current) => (new BigNumber(current).lt(min) ? current : min)));\n\nexport const maxBigNumber = (...args: BigNumber.Value[]) =>\n BigNumber(args.reduce((max, current) => (new BigNumber(current).gt(max) ? current : max)));\n\n/**\n * Dynamically adjust the decrease or increase ratio according to the amout\n * @param amount - The amount required to calculate factor.\n * @param scaleStep - The scale step required to determine the factor..\n * @param type - The type of the calculation.\n * @return The estimated factor\n * */\nexport const estimatedFactor = (amount: number, scaleStep: number, type: 'increase' | 'decrease') => {\n const amountOfDigits = Math.max(1, Math.floor(Math.log10(Math.abs(amount)) + 1));\n\n const adjustScale = Math.max(Math.floor((amountOfDigits - 1) / scaleStep), 1) + 1;\n\n let adjustFactor = 10 ** -adjustScale;\n adjustFactor = type === 'increase' ? 1 - adjustFactor : 1 + adjustFactor;\n\n return adjustFactor;\n};\n\nexport const parseOriginBorrowIncentiveAccountPoolPointData = (\n originBorrowIncentiveAccountPoolPointData: OriginBorrowIncentiveAccountPoolData,\n): ParsedBorrowIncentiveAccountPoolData => ({\n pointType: normalizeStructTag(originBorrowIncentiveAccountPoolPointData.point_type.name),\n weightedAmount: Number(originBorrowIncentiveAccountPoolPointData.weighted_amount),\n points: Number(originBorrowIncentiveAccountPoolPointData.points),\n totalPoints: Number(originBorrowIncentiveAccountPoolPointData.total_points),\n index: Number(originBorrowIncentiveAccountPoolPointData.index),\n});\n\n/**\n * Parse origin borrow incentive account data to a more readable format.\n *\n * @param originBorrowIncentiveAccountData - Origin borrow incentive account data\n * @return Parsed borrow incentive account data\n */\nexport const parseOriginBorrowIncentiveAccountData = (\n originBorrowIncentiveAccountData: OriginBorrowIncentiveAccountData,\n): ParsedBorrowIncentiveAccountData => ({\n poolType: normalizeStructTag(originBorrowIncentiveAccountData.pool_type.name),\n debtAmount: Number(originBorrowIncentiveAccountData.debt_amount),\n pointList: originBorrowIncentiveAccountData.points_list.reduce(\n (acc, point) => {\n const parsed = parseOriginBorrowIncentiveAccountPoolPointData(point);\n const name = parseStructTag(parsed.pointType).name.toLowerCase() as SupportBorrowIncentiveRewardCoins;\n acc[name] = parsed;\n return acc;\n },\n {} as Record<SupportBorrowIncentiveRewardCoins, ParsedBorrowIncentiveAccountPoolData>,\n ),\n});\n","import { SUPPORT_POOLS, SUPPORT_COLLATERALS, SUPPORT_SPOOLS_REWARDS, MAX_LOCK_DURATION } from '../constants';\nimport type { SupportAssetCoins, SupportCoins, SupportMarketCoins } from '../types';\n\nexport const isMarketCoin = (coinName: SupportCoins): coinName is SupportMarketCoins => {\n const assetCoinName = coinName.slice(1).toLowerCase() as SupportAssetCoins;\n return (\n coinName.charAt(0).toLowerCase() === 's' &&\n [...new Set([...SUPPORT_POOLS, ...SUPPORT_COLLATERALS, ...SUPPORT_SPOOLS_REWARDS])].includes(assetCoinName)\n );\n};\n\nexport const parseAssetSymbol = (coinName: SupportAssetCoins): string => {\n switch (coinName) {\n case 'afsui':\n return 'afSUI';\n case 'hasui':\n return 'haSUI';\n case 'vsui':\n return 'vSUI';\n default:\n return coinName.toUpperCase();\n }\n};\n\n/**\n * Find the closest unlock round timestamp (12AM) to the given unlock at timestamp in seconds.\n *\n * @param unlockAtInSecondTimestamp - Unlock at in seconds timestamp to find the closest round.\n * @returns Closest round (12AM) in seconds timestamp.\n */\nexport const findClosestUnlockRound = (unlockAtInSecondTimestamp: number) => {\n const unlockDate = new Date(unlockAtInSecondTimestamp * 1000);\n const closestTwelveAM = new Date(unlockAtInSecondTimestamp * 1000);\n\n closestTwelveAM.setUTCHours(0, 0, 0, 0); // Set the time to the next 12 AM UTC\n\n // If the current time is past 12 AM, set the date to the next day\n if (unlockDate.getUTCHours() >= 0) {\n closestTwelveAM.setUTCDate(closestTwelveAM.getUTCDate() + 1);\n }\n\n const now = new Date().getTime();\n // check if unlock period > 4 years\n if (closestTwelveAM.getTime() - now > MAX_LOCK_DURATION * 1000) {\n closestTwelveAM.setUTCDate(closestTwelveAM.getUTCDate() - 1);\n }\n return Math.floor(closestTwelveAM.getTime() / 1000);\n};\n","import type { ScallopQuery } from '../models';\nimport type { SupportAssetCoins } from '../types';\n\n/**\n * Get price from pyth fee object.\n *\n * @param query - The Scallop query instance.\n * @param assetCoinName - Specific support asset coin name.\n * @return Asset coin price.\n */\nexport const getPythPrice = async (query: ScallopQuery, assetCoinName: SupportAssetCoins) => {\n const pythFeedObjectId = query.address.get(`core.coins.${assetCoinName}.oracle.pyth.feedObject`);\n const priceFeedObjectResponse = await query.client.getObject({\n id: pythFeedObjectId,\n options: {\n showContent: true,\n },\n });\n\n if (priceFeedObjectResponse.data) {\n const priceFeedPoolObject = priceFeedObjectResponse.data;\n if (priceFeedPoolObject.content && 'fields' in priceFeedPoolObject.content) {\n const fields = priceFeedPoolObject.content.fields as any;\n const expoMagnitude = Number(fields.price_info.fields.price_feed.fields.price.fields.expo.fields.magnitude);\n const expoNegative = Number(fields.price_info.fields.price_feed.fields.price.fields.expo.fields.negative);\n const priceMagnitude = Number(fields.price_info.fields.price_feed.fields.price.fields.price.fields.magnitude);\n const priceNegative = Number(fields.price_info.fields.price_feed.fields.price.fields.price.fields.negative);\n\n return priceMagnitude * 10 ** ((expoNegative ? -1 : 1) * expoMagnitude) * (priceNegative ? -1 : 1);\n }\n }\n\n return 0;\n};\n","import type { SuiObjectResponse, SuiObjectData } from '@mysten/sui.js/client';\nimport BigNumber from 'bignumber.js';\n\nimport type { ScallopQuery } from '../models';\nimport { Vesca } from '../types';\n\n/**\n * Query all owned veSca key.\n *\n * @param query - The Scallop query instance.\n * @param ownerAddress - The owner address.\n * @return Owned veSca key.\n */\nexport const getVescaKeys = async (query: ScallopQuery, ownerAddress?: string) => {\n const owner = ownerAddress;\n const veScaPkgId = query.address.get('vesca.id');\n const veScaKeyType = `${veScaPkgId}::ve_sca::VeScaKey`;\n const keyObjectsResponse: SuiObjectResponse[] = [];\n let hasNextPage = false;\n let nextCursor: string | null | undefined = null;\n do {\n const paginatedKeyObjectsResponse = await query.client.getOwnedObjects({\n owner,\n filter: {\n StructType: veScaKeyType,\n },\n cursor: nextCursor,\n });\n keyObjectsResponse.push(...paginatedKeyObjectsResponse.data);\n if (paginatedKeyObjectsResponse.hasNextPage && paginatedKeyObjectsResponse.nextCursor) {\n hasNextPage = true;\n nextCursor = paginatedKeyObjectsResponse.nextCursor;\n } else {\n hasNextPage = false;\n }\n } while (hasNextPage);\n\n const keyObjectDatas = keyObjectsResponse\n .map((objResponse) => objResponse.data)\n .filter((data) => !!data) as SuiObjectData[];\n return keyObjectDatas;\n};\n\n/**\n * Query all owned veSca.\n *\n * @param query - The Scallop query instance.\n * @param ownerAddress - The owner address.\n * @return Owned veScas.\n */\nexport const getVeScas = async (query: ScallopQuery, ownerAddress?: string) => {\n const keyObjectDatas = await getVescaKeys(query, ownerAddress);\n const keyObjectId: string[] = keyObjectDatas.map((data) => data.objectId);\n\n const veScas: Vesca[] = [];\n for (let i = 0; i < keyObjectId.length; i++) {\n const veSca = await getVeSca(query, keyObjectId[i]);\n if (veSca) {\n veScas.push(veSca);\n }\n }\n return veScas;\n};\n\n/**\n * Get veSca data.\n *\n * @param query - The Scallop query instance.\n * @param veScaKeyId - The vesca key id.\n * @param ownerAddress - The owner address.\n * @returns Vesca data.\n */\nexport const getVeSca = async (query: ScallopQuery, veScaKeyId?: string, ownerAddress?: string) => {\n const tableId = query.address.get(`vesca.tableId`);\n const veScaKeyIdValue = veScaKeyId || (await getVescaKeys(query, ownerAddress))[0].objectId;\n\n let vesca: Vesca | undefined;\n\n const veScaDynamicFieldObjectResponse = await query.client.getDynamicFieldObject({\n parentId: tableId,\n name: {\n type: '0x2::object::ID',\n value: veScaKeyIdValue,\n },\n });\n const veScaDynamicFieldObject = veScaDynamicFieldObjectResponse.data;\n if (\n veScaDynamicFieldObject &&\n veScaDynamicFieldObject.content &&\n veScaDynamicFieldObject.content.dataType === 'moveObject' &&\n 'fields' in veScaDynamicFieldObject.content\n ) {\n const dynamicFields = (veScaDynamicFieldObject.content.fields as any).value.fields;\n vesca = {\n id: veScaDynamicFieldObject.objectId,\n keyId: veScaKeyIdValue,\n lockedScaAmount: BigNumber(dynamicFields.locked_sca_amount).toNumber(),\n lockedScaCoin: BigNumber(dynamicFields.locked_sca_amount).shiftedBy(-9).toNumber(),\n unlockAt: BigNumber(dynamicFields.unlock_at).toNumber(),\n } as Vesca;\n }\n\n return vesca;\n};\n","import { SuiClient } from '@mysten/sui.js/client';\n\nimport { ScallopAddress } from './scallopAddress';\nimport { ScallopUtils } from './scallopUtils';\nimport { SUPPORT_SPOOLS } from '../constants';\nimport {\n getObligations,\n getStakeAccounts,\n getStakePool,\n getStakeRewardPool,\n getPythPrice,\n queryBorrowIncentiveAccounts,\n getCoinAmounts,\n getCoinAmount,\n getMarketCoinAmounts,\n getMarketCoinAmount,\n queryObligation,\n} from '../queries';\nimport {\n ScallopQueryParams,\n ScallopInstanceParams,\n SupportStakeMarketCoins,\n SupportAssetCoins,\n SupportMarketCoins,\n StakePools,\n StakeRewardPools,\n SupportBorrowIncentiveCoins,\n SuiAddressArg,\n} from '../types';\n\n/**\n * @description\n * It provides methods for getting on-chain data from the Scallop contract.\n *\n * @example\n * ```typescript\n * const scallopQuery = new ScallopQuery(<parameters>);\n * await scallopQuery.init();\n * scallopQuery.<query functions>();\n * await scallopQuery.<query functions>();\n * ```\n */\nexport class ScallopQuery {\n public readonly params: ScallopQueryParams;\n\n public address: ScallopAddress;\n\n public client: SuiClient;\n\n public utils: ScallopUtils;\n\n public constructor(params: ScallopQueryParams, instance?: Omit<ScallopInstanceParams, 'query' | 'builder'>) {\n this.params = params;\n this.client = params.client;\n\n const { address, utils } = instance;\n this.address = address;\n this.utils = utils;\n }\n\n /* ==================== Core Query Methods ==================== */\n /**\n * Get obligations data.\n *\n * @param ownerAddress - The owner address.\n * @return Obligations data.\n */\n public async getObligations(ownerAddress: string = this.params.walletAddress) {\n return getObligations(this, ownerAddress);\n }\n\n /**\n * Get all asset coin amounts.\n *\n * @param assetCoinNames - Specific an array of support asset coin name.\n * @param ownerAddress - The owner address.\n * @return All coin amounts.\n */\n public async getCoinAmounts(ownerAddress: string, assetCoinNames?: SupportAssetCoins[]) {\n return getCoinAmounts(this, ownerAddress, assetCoinNames);\n }\n\n /**\n * Get asset coin amount.\n *\n * @param assetCoinName - Specific support asset coin name.\n * @param ownerAddress - The owner address.\n * @return Coin amount.\n */\n public async getCoinAmount(assetCoinName: SupportAssetCoins, ownerAddress: string = this.params.walletAddress) {\n return getCoinAmount(this, assetCoinName, ownerAddress);\n }\n\n /**\n * Get all market coin amounts.\n *\n * @param coinNames - Specific an array of support market coin name.\n * @param ownerAddress - The owner address.\n * @return All market market coin amounts.\n */\n public async getMarketCoinAmounts(ownerAddress: string, marketCoinNames?: SupportMarketCoins[]) {\n return getMarketCoinAmounts(this, ownerAddress, marketCoinNames);\n }\n\n /**\n * Get market coin amount.\n *\n * @param coinNames - Specific support market coin name.\n * @param ownerAddress - The owner address.\n * @return Market market coin amount.\n */\n public async getMarketCoinAmount(\n marketCoinName: SupportMarketCoins,\n ownerAddress: string = this.params.walletAddress,\n ) {\n return getMarketCoinAmount(this, marketCoinName, ownerAddress);\n }\n\n /**\n * Get price from pyth fee object.\n *\n * @param assetCoinName - Specific support asset coin name.\n * @return Asset coin price.\n */\n public async getPriceFromPyth(assetCoinName: SupportAssetCoins) {\n return getPythPrice(this, assetCoinName);\n }\n\n /* ==================== Spool Query Methods ==================== */\n\n /**\n * Get stake accounts data for all stake pools (spools).\n *\n * @param ownerAddress - The owner address.\n * @return All Stake accounts data.\n */\n public async getAllStakeAccounts(ownerAddress: string = this.params.walletAddress) {\n return getStakeAccounts(this, ownerAddress);\n }\n\n /**\n * Get stake accounts data for specific stake pool (spool).\n *\n * @param stakeMarketCoinName - Specific support stake market coin name.\n * @param ownerAddress - The owner address.\n * @return Stake accounts data.\n */\n public async getStakeAccounts(\n stakeMarketCoinName: SupportStakeMarketCoins,\n ownerAddress: string = this.params.walletAddress,\n ) {\n const allStakeAccount = await this.getAllStakeAccounts(ownerAddress);\n return allStakeAccount[stakeMarketCoinName] ?? [];\n }\n\n /**\n * Get stake pools (spools) data.\n *\n * @description\n * For backward compatible, it is recommended to use `getSpools` method\n * to get all spools data.\n *\n * @param stakeMarketCoinNames - Specific an array of support stake market coin name.\n * @return Stake pools data.\n */\n public async getStakePools(stakeMarketCoinNames: SupportStakeMarketCoins[] = [...SUPPORT_SPOOLS]) {\n const stakePools: StakePools = {};\n for (let i = 0; i < stakeMarketCoinNames.length; i++) {\n const stakeMarketCoinName = stakeMarketCoinNames[i];\n const stakePool = await getStakePool(this, stakeMarketCoinName);\n\n if (stakePool) {\n stakePools[stakeMarketCoinName] = stakePool;\n }\n }\n return stakePools;\n }\n\n /**\n * Get stake pool (spool) data.\n *\n * @description\n * For backward compatible, it is recommended to use `getSpool` method\n * to get all spool data.\n *\n * @param stakeMarketCoinName - Specific support stake market coin name.\n * @return Stake pool data.\n */\n public async getStakePool(stakeMarketCoinName: SupportStakeMarketCoins) {\n return getStakePool(this, stakeMarketCoinName);\n }\n\n /**\n * Get stake reward pools data.\n *\n * @description\n * For backward compatible, it is recommended to use `getSpools` method\n * to get all spools data.\n *\n * @param stakeMarketCoinNames - Specific an array of stake market coin name.\n * @return Stake reward pools data.\n */\n public async getStakeRewardPools(stakeMarketCoinNames: SupportStakeMarketCoins[] = [...SUPPORT_SPOOLS]) {\n const stakeRewardPools: StakeRewardPools = {};\n for (let i = 0; i < stakeMarketCoinNames.length; i++) {\n const stakeRewardPool = await getStakeRewardPool(this, stakeMarketCoinNames[i]);\n\n if (stakeRewardPool) {\n stakeRewardPools[stakeMarketCoinNames[i]] = stakeRewardPool;\n }\n }\n return stakeRewardPools;\n }\n\n /**\n * Get stake reward pool data.\n *\n * @description\n * For backward compatible, it is recommended to use `getSpool` method\n * to get spool data.\n *\n * @param marketCoinName - Specific support stake market coin name.\n * @return Stake reward pool data.\n */\n public async getStakeRewardPool(stakeMarketCoinName: SupportStakeMarketCoins) {\n return getStakeRewardPool(this, stakeMarketCoinName);\n }\n\n /**\n * Get borrow incentive accounts data.\n *\n * @param coinNames - Specific support borrow incentive coin name.\n * @param ownerAddress - The owner address.\n * @return Borrow incentive accounts data.\n */\n public async getBorrowIncentiveAccounts(\n obligationId: string,\n walletAddress: string = this.params.walletAddress,\n coinNames?: SupportBorrowIncentiveCoins[],\n ) {\n return queryBorrowIncentiveAccounts(this, obligationId, walletAddress, coinNames);\n }\n\n /**\n * Get all asset coin names in the obligation record by obligation id.\n *\n * @description\n * This can often be used to determine which assets in an obligation require\n * price updates before interacting with specific instructions of the Scallop contract.\n *\n * @param obligationId - The obligation id.\n * @return Asset coin Names.\n */\n public async getObligationCoinNames(obligationId: SuiAddressArg) {\n const obligation = await queryObligation(this, obligationId);\n const collateralCoinTypes = obligation.collaterals.map((collateral) => `0x${collateral.type.name}`);\n const debtCoinTypes = obligation.debts.map((debt) => `0x${debt.type.name}`);\n const obligationCoinTypes = [...new Set([...collateralCoinTypes, ...debtCoinTypes])];\n const obligationCoinNames = obligationCoinTypes.map((coinType) => this.utils.parseCoinNameFromType(coinType));\n return obligationCoinNames;\n }\n}\n","import { SuiClient } from '@mysten/sui.js/client';\nimport { TransactionBlock } from '@mysten/sui.js/transactions';\nimport { SUI_TYPE_ARG, normalizeStructTag } from '@mysten/sui.js/utils';\n\nimport { ScallopAddress } from './scallopAddress';\nimport {\n PROTOCOL_OBJECT_ID,\n spoolRewardCoins,\n borrowIncentiveRewardCoins,\n coinDecimals,\n wormholeCoinIds,\n voloCoinIds,\n coinIds,\n UNLOCK_ROUND_DURATION,\n MAX_LOCK_DURATION,\n sCoinIds,\n SUPPORT_SCOIN,\n} from '../constants';\nimport type {\n ScallopUtilsParams,\n SupportCoins,\n SupportAssetCoins,\n SupportMarketCoins,\n SupportStakeMarketCoins,\n SupportBorrowIncentiveCoins,\n CoinWrappedType,\n SupportPoolCoins,\n SuiTxArg,\n SupportSCoin,\n} from '../types';\nimport { findClosestUnlockRound, isMarketCoin, parseAssetSymbol } from '../utils';\n\n/**\n * @description\n * Integrates some helper functions frequently used in interactions with the Scallop contract.\n *\n * @example\n * ```typescript\n * const scallopUtils = new ScallopUtils(<parameters>);\n * await scallopUtils.init();\n * scallopUtils.<utils functions>();\n * await scallopUtils.<utils functions>();\n * ```\n */\nexport class ScallopUtils {\n public readonly params: ScallopUtilsParams;\n\n public readonly isTestnet: boolean;\n\n private _address: ScallopAddress;\n\n public client: SuiClient;\n\n public constructor(params: ScallopUtilsParams, address: ScallopAddress) {\n this.params = params;\n this.client = params.client;\n\n this._address = address;\n }\n\n /**\n * Convert coin name to symbol.\n *\n * @param coinName - Specific support coin name.\n * @return Symbol string.\n */\n public parseSymbol(coinName: SupportCoins) {\n if (isMarketCoin(coinName)) {\n const assetCoinName = coinName.slice(1).toLowerCase() as SupportAssetCoins;\n return coinName.slice(0, 1).toLowerCase() + parseAssetSymbol(assetCoinName);\n }\n return parseAssetSymbol(coinName);\n }\n\n /**\n * Convert coin name to coin type.\n *\n * @description\n * The Coin type of wormhole is fixed `coin:Coin`. Here using package id\n * to determine and return the type.\n *\n * @param coinPackageId - Package id of coin.\n * @param coinName - Specific support coin name.\n * @return Coin type.\n */\n public parseCoinType(coinName: SupportCoins) {\n const validCoinName = isMarketCoin(coinName) ? this.parseCoinName(coinName) : coinName;\n const coinPackageId = coinIds[validCoinName as SupportPoolCoins];\n const wormHolePackageIds = [\n wormholeCoinIds.wusdc,\n wormholeCoinIds.wusdt,\n wormholeCoinIds.weth,\n wormholeCoinIds.wbtc,\n wormholeCoinIds.wsol,\n wormholeCoinIds.wapt,\n ];\n if (wormHolePackageIds.includes(coinPackageId)) {\n return `${coinPackageId}::coin::COIN`;\n }\n if (coinName === 'vsui') {\n return `${voloCoinIds.vsui}::cert::CERT`;\n }\n return `${coinPackageId}::${validCoinName}::${validCoinName.toUpperCase()}`;\n }\n\n /**\n * Convert coin name to market coin type.\n *\n * @param coinPackageId - Package id of coin.\n * @param coinName - Specific support coin name.\n * @return Market coin type.\n */\n public parseMarketCoinType(coinName: SupportCoins) {\n const protocolObjectId = this._address.get('core.object') || PROTOCOL_OBJECT_ID;\n const coinType = this.parseCoinType(coinName);\n return `${protocolObjectId}::reserve::MarketCoin<${coinType}>`;\n }\n\n /**\n * Convert coin type to coin name.\n *\n * @description\n * The coin name cannot be obtained directly from the wormhole type. Here\n * the package id is used to determine and return a specific name.\n *\n * @param coinType - Specific support coin type.\n * @return Coin Name.\n */\n public parseCoinNameFromType<T extends SupportAssetCoins>(\n coinType: string,\n ): T extends SupportAssetCoins ? T : SupportAssetCoins;\n public parseCoinNameFromType<T extends SupportMarketCoins>(\n coinType: string,\n ): T extends SupportMarketCoins ? T : SupportMarketCoins;\n public parseCoinNameFromType<T extends SupportCoins>(coinType: string): T extends SupportCoins ? T : SupportCoins;\n public parseCoinNameFromType(coinType: string) {\n let type = normalizeStructTag(coinType);\n const coinTypeRegex = /((0x[^:]+::[^:]+::[^<>]+))(?![^<>]*<)/;\n const coinTypeMatch = coinType.match(coinTypeRegex);\n const isMarketCoinType = coinType.includes('reserve::MarketCoin');\n type = coinTypeMatch?.[1] || coinType;\n\n const wormHoleCoinTypeMap: Record<string, SupportAssetCoins> = {\n [`${wormholeCoinIds.wusdc}::coin::COIN`]: 'wusdc',\n [`${wormholeCoinIds.wusdt}::coin::COIN`]: 'wusdt',\n [`${wormholeCoinIds.weth}::coin::COIN`]: 'weth',\n [`${wormholeCoinIds.wbtc}::coin::COIN`]: 'wbtc',\n [`${wormholeCoinIds.wsol}::coin::COIN`]: 'wsol',\n [`${wormholeCoinIds.wapt}::coin::COIN`]: 'wapt',\n };\n const voloCoinTypeMap: Record<string, SupportAssetCoins> = {\n [`${voloCoinIds.vsui}::cert::CERT`]: 'vsui',\n };\n\n const assetCoinName =\n wormHoleCoinTypeMap[type] || voloCoinTypeMap[type] || (type.split('::')[2].toLowerCase() as SupportAssetCoins);\n\n return isMarketCoinType ? this.parseMarketCoinName(assetCoinName) : assetCoinName;\n }\n\n /**\n * Convert marke coin name to coin name.\n *\n * @param marketCoinName - Specific support market coin name.\n * @return Coin Name.\n */\n public parseCoinName<T extends SupportAssetCoins>(marketCoinName: string) {\n return marketCoinName.slice(1) as T;\n }\n\n /**\n * Convert coin name to market coin name.\n *\n * @param coinName - Specific support coin name.\n * @return Market coin name.\n */\n public parseMarketCoinName<T extends SupportMarketCoins>(coinName: SupportCoins) {\n return `s${coinName}` as T;\n }\n\n /**\n * Get reward type of spool.\n *\n * @param stakeMarketCoinName - Support stake market coin.\n * @return Spool reward coin name.\n */\n public getSpoolRewardCoinName = (stakeMarketCoinName: SupportStakeMarketCoins) =>\n spoolRewardCoins[stakeMarketCoinName];\n\n /**\n * Get reward type of borrow incentive pool.\n *\n * @param borrowIncentiveCoinName - Support borrow incentive coin.\n * @return Borrow incentive reward coin name.\n */\n public getBorrowIncentiveRewardCoinName = (borrowIncentiveCoinName: SupportBorrowIncentiveCoins) =>\n borrowIncentiveRewardCoins[borrowIncentiveCoinName];\n\n /**\n * Get coin decimal.\n *\n * return Coin decimal.\n */\n public getCoinDecimal(coinName: SupportCoins) {\n return coinDecimals[coinName];\n }\n\n /**\n * Get coin wrapped type.\n *\n * return Coin wrapped type.\n */\n public getCoinWrappedType(assetCoinName: SupportAssetCoins): CoinWrappedType {\n return assetCoinName === 'wusdc' ||\n assetCoinName === 'wusdt' ||\n assetCoinName === 'weth' ||\n assetCoinName === 'wbtc' ||\n assetCoinName === 'wapt' ||\n assetCoinName === 'wsol'\n ? {\n from: 'Wormhole',\n type: 'Portal from Ethereum',\n }\n : undefined;\n }\n\n /**\n * Convert sCoin name into sCoin type\n * @param sCoinName\n * @returns sCoin type\n */\n public parseSCoinType(sCoinName: SupportSCoin) {\n return sCoinIds[sCoinName];\n }\n\n /**\n * Convert sCoin name into its underlying coin type\n * @param sCoinName\n * @returns coin type\n */\n public parseUnderlyingSCoinType(sCoinName: SupportSCoin) {\n const coinName = this.parseCoinName(sCoinName);\n return this.parseCoinType(coinName);\n }\n\n /**\n * Get sCoin treasury id from sCoin name\n * @param sCoinName\n * @returns sCoin treasury id\n */\n public getSCoinTreasury(sCoinName: SupportSCoin) {\n return this._address.get(`scoin.coins.${sCoinName}.treasury`);\n }\n\n /**\n * Select coin id that add up to the given amount as transaction arguments.\n *\n * @param ownerAddress - The address of the owner.\n * @param amount - The amount that including coin decimals.\n * @param coinType - The coin type, default is 0x2::SUI::SUI.\n * @return The selected transaction coin arguments.\n */\n public async selectCoins(amount: number, coinType: string = SUI_TYPE_ARG, ownerAddress?: string) {\n const address = ownerAddress;\n\n const selectedCoins: {\n objectId: string;\n digest: string;\n version: string;\n balance: string;\n }[] = [];\n let totalAmount = 0;\n let hasNext = true;\n let nextCursor: string | null | undefined = null;\n while (hasNext && totalAmount < amount) {\n const coins = await this.client.getCoins({\n owner: address,\n coinType,\n cursor: nextCursor,\n });\n // Sort the coins by balance in descending order\n coins.data.sort((a, b) => parseInt(b.balance, 10) - parseInt(a.balance, 10));\n for (let i = 0; i < coins.data.length; i++) {\n selectedCoins.push({\n objectId: coins.data[i].coinObjectId,\n digest: coins.data[i].digest,\n version: coins.data[i].version,\n balance: coins.data[i].balance,\n });\n totalAmount += parseInt(coins.data[i].balance, 10);\n if (totalAmount >= amount) {\n break;\n }\n }\n nextCursor = coins.nextCursor;\n hasNext = coins.hasNextPage;\n }\n\n if (!selectedCoins.length) {\n throw new Error('No valid coins found for the transaction.');\n }\n return selectedCoins;\n }\n\n /**\n * Select coin id that add up to the given amount as transaction arguments.\n *\n * @param ownerAddress - The address of the owner.\n * @param amount - The amount that including coin decimals.\n * @param coinType - The coin type, default is 0x2::SUI::SUI.\n * @return The selected transaction coin arguments.\n */\n public async selectCoinsMarketCoin(coinType: string = SUI_TYPE_ARG, ownerAddress?: string) {\n const address = ownerAddress;\n\n const selectedCoins: {\n objectId: string;\n digest: string;\n version: string;\n balance: string;\n }[] = [];\n let hasNext = true;\n let nextCursor: string | null | undefined = null;\n while (hasNext) {\n const coins = await this.client.getCoins({\n owner: address,\n coinType,\n cursor: nextCursor,\n });\n // Sort the coins by balance in descending order\n coins.data.sort((a, b) => parseInt(b.balance, 10) - parseInt(a.balance, 10));\n for (let i = 0; i < coins.data.length; i++) {\n selectedCoins.push({\n objectId: coins.data[i].coinObjectId,\n digest: coins.data[i].digest,\n version: coins.data[i].version,\n balance: coins.data[i].balance,\n });\n if (selectedCoins.length > 50) {\n break;\n }\n }\n nextCursor = coins.nextCursor;\n hasNext = coins.hasNextPage;\n }\n\n return selectedCoins;\n }\n\n public async selectCoinIds(amount: number, coinType: string = SUI_TYPE_ARG, ownerAddress?: string) {\n const selectedCoins = await this.selectCoins(amount, coinType, ownerAddress);\n return selectedCoins.map((coin) => coin.objectId);\n }\n\n /**\n * Convert apr to apy.\n *\n * @param apr The annual percentage rate (APR).\n * @param compoundFrequency How often interest is compounded per year. Default is daily (365 times a year).\n * @return The equivalent annual percentage yield (APY) for the given APR and compounding frequency.\n */\n public parseAprToApy(apr: number, compoundFrequency = 365) {\n return (1 + apr / compoundFrequency) ** compoundFrequency - 1;\n }\n\n /**\n * Convert apr to apy.\n *\n * @param apr The equivalent annual percentage yield (APY).\n * @param compoundFrequency How often interest is compounded per year. Default is daily (365 times a year).\n * @return The equivalent annual percentage rate (APR) for the given APY and compounding frequency.\n */\n public parseApyToApr(apy: number, compoundFrequency = 365) {\n return ((1 + apy) ** (1 / compoundFrequency) - 1) * compoundFrequency;\n }\n\n public takeAmountFromCoins(txBlock: TransactionBlock, coinObjectId: string[], amount: SuiTxArg) {\n const coinObjects = coinObjectId.map((objectId) => txBlock.object(objectId));\n const mergedCoin = coinObjects[0];\n if (coinObjects.length > 1) {\n txBlock.mergeCoins(mergedCoin, coinObjects.slice(1));\n }\n const [sendCoin] = txBlock.splitCoins(mergedCoin, [txBlock.pure(amount)]);\n return [sendCoin, mergedCoin];\n }\n\n /**\n * Give extend lock period to get unlock at in seconds timestamp.\n *\n * @description\n * - When the user without remaining unlock period, If the extended unlock day is not specified,\n * the unlock period will be increased by one day by default.\n * - When the given extended day plus the user's remaining unlock period exceeds the maximum\n * unlock period, the maximum unlock period is used as unlock period.\n *\n * @param extendLockPeriodInDay The extend lock period in day.\n * @param unlockAtInSecondTimestamp The unlock timestamp from veSca object.\n * @return New unlock at in seconds timestamp.\n */\n public getUnlockAt(extendLockPeriodInDay?: number, unlockAtInSecondTimestamp?: number) {\n const now = Math.floor(new Date().getTime() / 1000);\n const remainingLockPeriod = unlockAtInSecondTimestamp ? Math.max(unlockAtInSecondTimestamp - now, 0) : 0;\n\n let newUnlockAtInSecondTimestamp = 0;\n\n if (remainingLockPeriod === 0) {\n const lockPeriod = (extendLockPeriodInDay ?? 1) * UNLOCK_ROUND_DURATION;\n newUnlockAtInSecondTimestamp = Math.min(now + lockPeriod, now + MAX_LOCK_DURATION);\n } else {\n const lockPeriod = Math.min(\n extendLockPeriodInDay\n ? extendLockPeriodInDay * UNLOCK_ROUND_DURATION + remainingLockPeriod\n : remainingLockPeriod,\n MAX_LOCK_DURATION,\n );\n newUnlockAtInSecondTimestamp = now + lockPeriod;\n }\n return findClosestUnlockRound(newUnlockAtInSecondTimestamp);\n }\n\n /**\n * Convert coin name to sCoin name.\n *\n * @param coinName - Specific support coin name.\n * @return sCoin name.\n */\n public parseSCoinName<T extends SupportSCoin>(coinName: SupportCoins | SupportMarketCoins) {\n // need more check because sbtc, ssol and sapt has no sCoin type\n if (isMarketCoin(coinName) && SUPPORT_SCOIN.includes(coinName as SupportSCoin)) {\n return coinName as T;\n }\n const marketCoinName = `s${coinName}`;\n if (SUPPORT_SCOIN.includes(marketCoinName as SupportSCoin)) {\n return marketCoinName as T;\n }\n return undefined;\n }\n}\n","import { TransactionBlock } from '@mysten/sui.js/transactions';\nimport { SUI_CLOCK_OBJECT_ID, SUI_TYPE_ARG } from '@mysten/sui.js/utils';\n\nimport { OLD_BORROW_INCENTIVE_PROTOCOL_ID } from '../constants';\nimport type { ScallopBuilder } from '../models';\nimport { getObligations, getObligationLocked, getVeSca, getVeScas, getBindedVeScaKey } from '../queries';\nimport type {\n BorrowIncentiveIds,\n GenerateBorrowIncentiveNormalMethod,\n GenerateBorrowIncentiveQuickMethod,\n VescaIds,\n SuiAddressArg,\n} from '../types';\nimport { requireSender } from '../utils';\n\n/**\n * Check and get veSCA data from transaction block.\n *\n * @description\n * If the veScaKey id is provided, directly return it.\n * Otherwise, automatically get veScaKey from the sender.\n *\n * @param builder - Scallop builder instance.\n * @param txBlock - TxBlock created by SuiKit.\n * @param veScaKey - veSCA key.\n * @return veSCA key, ID, locked amount and unlock at timestamp.\n */\n\nexport const requireVeSca = async (\n ...params: [builder: ScallopBuilder, SuiTxBlock: TransactionBlock, veScaKey?: SuiAddressArg]\n) => {\n const [builder, txBlock, veScaKey] = params;\n if (params.length === 3 && veScaKey && typeof veScaKey === 'string') {\n const veSca = await getVeSca(builder.query, veScaKey);\n\n if (!veSca) {\n return undefined;\n }\n\n return veSca;\n }\n\n const sender = requireSender(txBlock);\n const veScas = await getVeScas(builder.query, sender);\n if (veScas.length === 0) {\n return undefined;\n }\n\n return veScas[0];\n};\n\n/**\n * Check veSca bind status\n * @param query\n * @param veScaKey\n * @returns\n */\nexport const getBindedObligationId = async (builder: ScallopBuilder, veScaKey: string) => {\n const borrowIncentiveObjId = builder.address.get('borrowIncentive.object');\n const incentivePoolsId = builder.address.get('borrowIncentive.incentivePools');\n const veScaPkgId = builder.address.get('vesca.id');\n\n const { client } = builder;\n\n // get incentive pools\n const incentivePoolsResponse = await client.getObject({\n id: incentivePoolsId,\n options: {\n showContent: true,\n },\n });\n\n if (incentivePoolsResponse.data?.content?.dataType !== 'moveObject') {\n return false;\n }\n const incentivePoolFields = incentivePoolsResponse.data.content.fields as any;\n const veScaBindTableId = incentivePoolFields.ve_sca_bind.fields.id.id as string;\n\n // check if veSca is inside the bind table\n const keyType = `${borrowIncentiveObjId}::typed_id::TypedID<${veScaPkgId}::ve_sca::VeScaKey>`;\n const veScaBindTableResponse = await client.getDynamicFieldObject({\n parentId: veScaBindTableId,\n name: {\n type: keyType,\n value: veScaKey,\n },\n });\n\n if (veScaBindTableResponse.data?.content?.dataType !== 'moveObject') {\n return false;\n }\n const veScaBindTableFields = veScaBindTableResponse.data.content.fields as any;\n // get obligationId pair\n const obligationId = veScaBindTableFields.value.fields.id as string;\n\n return obligationId;\n};\n\n/**\n * Check and get Obligation information from transaction block.\n *\n * @description\n * If the obligation id is provided, direactly return it.\n * If both obligation id and key is provided, direactly return them.\n * Otherwise, automatically get obligation id and key from the sender.\n *\n * @param builder - Scallop builder instance.\n * @param txBlock - TxBlock created by SuiKit.\n * @param obligationId - Obligation id.\n * @param obligationKey - Obligation key.\n * @return Obligation id and key.\n */\nconst requireObligationInfo = async (\n ...params: [builder: ScallopBuilder, txBlock: TransactionBlock, obligationId?: string, obligationKey?: string]\n) => {\n const [builder, txBlock, obligationId, obligationKey] = params;\n if (params.length === 4 && obligationId && obligationKey && typeof obligationId === 'string') {\n const obligationLocked = await getObligationLocked(builder.query, obligationId);\n return { obligationId, obligationKey, obligationLocked };\n }\n const sender = requireSender(txBlock);\n const obligations = await getObligations(builder.query, sender);\n if (obligations.length === 0) {\n throw new Error(`No obligation found for sender ${sender}`);\n }\n const selectedObligation =\n obligations.find((obligation) => obligation.id === obligationId || obligation.keyId === obligationKey) ??\n obligations[0];\n\n return {\n obligationId: selectedObligation.id,\n obligationKey: selectedObligation.keyId,\n obligationLocked: selectedObligation.locked,\n };\n};\n\n/**\n * Generate borrow incentive normal methods.\n *\n * @param builder - Scallop builder instance.\n * @param txBlock - TxBlock created by SuiKit .\n * @return Borrow incentive normal methods.\n */\nexport const generateBorrowIncentiveNormalMethod: GenerateBorrowIncentiveNormalMethod = async ({\n builder,\n txBlock,\n}) => {\n const borrowIncentiveIds: BorrowIncentiveIds = {\n borrowIncentivePkg: builder.address.get('borrowIncentive.id'),\n query: builder.address.get('borrowIncentive.query'),\n incentivePools: builder.address.get('borrowIncentive.incentivePools'),\n incentiveAccounts: builder.address.get('borrowIncentive.incentiveAccounts'),\n obligationAccessStore: builder.address.get('core.obligationAccessStore'),\n config: builder.address.get('borrowIncentive.config'),\n };\n const OldBorrowIncentiveContract = {\n id: '0xc63072e7f5f4983a2efaf5bdba1480d5e7d74d57948e1c7cc436f8e22cbeb410',\n incentivePools: '0x64972b713ccec45ec3964809e477cea6f97350c0c50ca3aec85bb631639266ec',\n incentiveAccounts: '0x3c0b707068bdcea8bb859d751ad3e2149a9f83c13fcf4054ef91372a00bccdd3',\n };\n const veScaIds: Omit<VescaIds, 'pkgId'> = {\n table: builder.address.get('vesca.table'),\n treasury: builder.address.get('vesca.treasury'),\n config: builder.address.get('vesca.config'),\n };\n\n return {\n stakeObligation: (obligationId, obligationKey) => {\n txBlock.moveCall({\n target: `${borrowIncentiveIds.borrowIncentivePkg}::user::stake`,\n arguments: [\n txBlock.object(borrowIncentiveIds.config),\n txBlock.object(borrowIncentiveIds.incentivePools),\n txBlock.object(borrowIncentiveIds.incentiveAccounts),\n txBlock.object(obligationKey as string),\n txBlock.object(obligationId as string),\n txBlock.object(borrowIncentiveIds.obligationAccessStore),\n txBlock.object(SUI_CLOCK_OBJECT_ID),\n ],\n });\n },\n stakeObligationWithVesca: (obligationId, obligationKey, veScaKey) => {\n txBlock.moveCall({\n target: `${borrowIncentiveIds.borrowIncentivePkg}::user::stake_with_ve_sca`,\n arguments: [\n txBlock.object(borrowIncentiveIds.config),\n txBlock.object(borrowIncentiveIds.incentivePools),\n txBlock.object(borrowIncentiveIds.incentiveAccounts),\n txBlock.object(obligationKey as string),\n txBlock.object(obligationId as string),\n txBlock.object(borrowIncentiveIds.obligationAccessStore),\n txBlock.object(veScaIds.config),\n txBlock.object(veScaIds.treasury),\n txBlock.object(veScaIds.table),\n txBlock.object(veScaKey as string),\n txBlock.object(SUI_CLOCK_OBJECT_ID),\n ],\n });\n },\n unstakeObligation: (obligationId, obligationKey) => {\n txBlock.moveCall({\n target: `${borrowIncentiveIds.borrowIncentivePkg}::user::unstake`,\n arguments: [\n txBlock.object(borrowIncentiveIds.config),\n txBlock.object(borrowIncentiveIds.incentivePools),\n txBlock.object(borrowIncentiveIds.incentiveAccounts),\n txBlock.object(obligationKey as string),\n txBlock.object(obligationId as string),\n txBlock.object(SUI_CLOCK_OBJECT_ID),\n ],\n });\n },\n oldUnstakeObligation: (obligationId, obligationKey) => {\n txBlock.moveCall({\n target: `${borrowIncentiveIds.borrowIncentivePkg}::user::unstake`,\n arguments: [\n txBlock.object(OldBorrowIncentiveContract.incentivePools),\n txBlock.object(OldBorrowIncentiveContract.incentiveAccounts),\n txBlock.object(obligationKey as string),\n txBlock.object(obligationId as string),\n txBlock.object(SUI_CLOCK_OBJECT_ID),\n ],\n typeArguments: [SUI_TYPE_ARG],\n });\n },\n claimBorrowIncentive: (obligationId, obligationKey, rewardCoinName) => {\n const rewardType = builder.utils.parseCoinType(rewardCoinName);\n return txBlock.moveCall({\n target: `${borrowIncentiveIds.borrowIncentivePkg}::user::redeem_rewards`,\n arguments: [\n txBlock.object(borrowIncentiveIds.config),\n txBlock.object(borrowIncentiveIds.incentivePools),\n txBlock.object(borrowIncentiveIds.incentiveAccounts),\n txBlock.object(obligationKey as string),\n txBlock.object(obligationId as string),\n txBlock.object(SUI_CLOCK_OBJECT_ID),\n ],\n typeArguments: [rewardType],\n });\n },\n oldClaimBorrowIncentive(obligationId, obligationKey, rewardCoinName) {\n const rewardType = builder.utils.parseCoinType(rewardCoinName);\n return txBlock.moveCall({\n target: `${OldBorrowIncentiveContract.id}::user::redeem_rewards`,\n arguments: [\n txBlock.object(OldBorrowIncentiveContract.incentivePools),\n txBlock.object(OldBorrowIncentiveContract.incentiveAccounts),\n txBlock.object(obligationKey as string),\n txBlock.object(obligationId as string),\n txBlock.object(SUI_CLOCK_OBJECT_ID),\n ],\n typeArguments: [rewardType],\n });\n },\n };\n};\n\n/**\n * Generate spool quick methods.\n *\n * @description\n * The quick methods are the same as the normal methods, but they will automatically\n * help users organize transaction blocks, include get stake account info, and transfer\n * coins to the sender. So, they are all asynchronous methods.\n *\n * @param builder - Scallop builder instance.\n * @param txBlock - TxBlock created by SuiKit .\n * @return Spool quick methods.\n */\nexport const generateBorrowIncentiveQuickMethod: GenerateBorrowIncentiveQuickMethod = async ({ builder, txBlock }) => {\n const normalMethod = await generateBorrowIncentiveNormalMethod({ builder, txBlock });\n return {\n normalMethod,\n stakeObligationQuick: async (obligation, obligationKey) => {\n const {\n obligationId: obligationArg,\n obligationKey: obligationtKeyArg,\n obligationLocked,\n } = await requireObligationInfo(builder, txBlock, obligation as string, obligationKey as string);\n\n const unstakeObligationBeforeStake = !!txBlock.blockData.transactions.find(\n (txn) =>\n txn.kind === 'MoveCall' &&\n (txn.target === `${OLD_BORROW_INCENTIVE_PROTOCOL_ID}::user::unstake` ||\n txn.target === `${builder.address.get('borrowIncentive.id')}::user::unstake`),\n );\n\n if (!obligationLocked || unstakeObligationBeforeStake) {\n normalMethod.stakeObligation(obligationArg, obligationtKeyArg);\n }\n },\n unstakeObligationQuick: async (obligation, obligationKey) => {\n const {\n obligationId: obligationArg,\n obligationKey: obligationtKeyArg,\n obligationLocked,\n } = await requireObligationInfo(builder, txBlock, obligation as string, obligationKey as string);\n\n if (obligationLocked) {\n normalMethod.unstakeObligation(obligationArg, obligationtKeyArg);\n }\n },\n stakeObligationWithVeScaQuick: async (obligation, obligationKey, veScaKey) => {\n const {\n obligationId: obligationArg,\n obligationKey: obligationtKeyArg,\n obligationLocked,\n } = await requireObligationInfo(builder, txBlock, obligation as string, obligationKey as string);\n\n const unstakeObligationBeforeStake = !!txBlock.blockData.transactions.find(\n async (txn) =>\n txn.kind === 'MoveCall' &&\n (txn.target === `${OLD_BORROW_INCENTIVE_PROTOCOL_ID}::user::unstake` ||\n txn.target === `${builder.address.get('borrowIncentive.id')}::user::unstake`),\n );\n\n if (!obligationLocked || unstakeObligationBeforeStake) {\n const bindedVeScaKey = await getBindedVeScaKey(\n { address: builder.address, client: builder.client },\n obligationArg,\n );\n if (veScaKey && veScaKey !== bindedVeScaKey) {\n throw new Error('Binded veScaKey is not equal to the provided veScaKey');\n }\n if (bindedVeScaKey) {\n normalMethod.stakeObligationWithVesca(obligationArg, obligationtKeyArg, bindedVeScaKey);\n } else {\n normalMethod.stakeObligation(obligationArg, obligationtKeyArg);\n }\n }\n },\n claimBorrowIncentiveQuick: (rewardCoinName, obligation, obligationKey) =>\n normalMethod.claimBorrowIncentive(obligation, obligationKey, rewardCoinName),\n };\n};\n","import { TransactionArgument, TransactionBlock } from '@mysten/sui.js/transactions';\nimport { SUI_CLOCK_OBJECT_ID } from '@mysten/sui.js/utils';\n\nimport { updateOracles } from './oracle';\nimport { generateSCoinNormalMethod } from './sCoinBuilder';\nimport type { ScallopBuilder } from '../models';\nimport { getObligations } from '../queries';\nimport type {\n CoreIds,\n GenerateCoreNormalMethod,\n ScallopTxBlock,\n GenerateCoreQuickMethod,\n SuiAddressArg,\n} from '../types';\nimport { requireSender } from '../utils';\n\n/**\n * Check and get Obligation information from transaction block.\n *\n * @description\n * If the obligation id is provided, direactly return it.\n * If both obligation id and key is provided, direactly return them.\n * Otherwise, automatically get obligation id and key from the sender.\n *\n * @param builder - Scallop builder instance.\n * @param txBlock - TxBlock created by SuiKit.\n * @param obligationId - Obligation id.\n * @param obligationKey - Obligation key.\n * @return Obligation id and key.\n */\nconst requireObligationInfo = async (\n ...params: [\n txBlock: TransactionBlock,\n builder: ScallopBuilder,\n obligationId?: SuiAddressArg,\n obligationKey?: SuiAddressArg,\n ]\n) => {\n const [txBlock, builder, obligationId, obligationKey] = params;\n if (params.length === 3 && obligationId) {\n return { obligationId };\n }\n if (params.length === 4 && obligationId && obligationKey) {\n return { obligationId, obligationKey };\n }\n const sender = requireSender(txBlock);\n const obligations = await getObligations(builder.query, sender);\n if (obligations.length === 0) {\n throw new Error(`No obligation found for sender ${sender}`);\n }\n return {\n obligationId: obligations[0].id,\n obligationKey: obligations[0].keyId,\n };\n};\n\n/**\n * Generate core normal methods.\n *\n * @param builder - Scallop builder instance.\n * @param txBlock - TxBlock created by SuiKit.\n * @return Core normal methods.\n */\nexport const generateCoreNormalMethod: GenerateCoreNormalMethod = async ({ builder, txBlock }) => {\n const coreIds: CoreIds = {\n protocolPkg: builder.address.get('core.packages.protocol.id'),\n market: builder.address.get('core.market'),\n version: builder.address.get('core.version'),\n coinDecimalsRegistry: builder.address.get('core.coinDecimalsRegistry'),\n xOracle: builder.address.get('core.oracles.xOracle'),\n };\n\n const referralPkgId = builder.address.get('referral.id');\n const referralWitnessType = `${referralPkgId}::scallop_referral_program::REFERRAL_WITNESS`;\n\n return {\n openObligation: () =>\n txBlock.moveCall({\n target: `${coreIds.protocolPkg}::open_obligation::open_obligation`,\n arguments: [txBlock.object(coreIds.version)],\n }),\n returnObligation: (obligation, obligationHotPotato) =>\n txBlock.moveCall({\n target: `${coreIds.protocolPkg}::open_obligation::return_obligation`,\n arguments: [\n txBlock.object(coreIds.version),\n txBlock.object(obligation as string),\n txBlock.object(obligationHotPotato as string),\n ],\n }),\n openObligationEntry: () =>\n txBlock.moveCall({\n target: `${coreIds.protocolPkg}::open_obligation::open_obligation_entry`,\n arguments: [txBlock.object(coreIds.version)],\n }),\n addCollateral: (obligation, coin, collateralCoinName) => {\n const coinType = builder.utils.parseCoinType(collateralCoinName);\n return txBlock.moveCall({\n target: `${coreIds.protocolPkg}::deposit_collateral::deposit_collateral`,\n arguments: [\n txBlock.object(coreIds.version),\n txBlock.object(obligation as string),\n txBlock.object(coreIds.market),\n typeof coin !== 'string' ? (coin as TransactionArgument) : txBlock.pure(coin),\n ],\n typeArguments: [coinType],\n });\n },\n takeCollateral: (obligation, obligationKey, amount, collateralCoinName) => {\n const coinType = builder.utils.parseCoinType(collateralCoinName);\n return txBlock.moveCall({\n target: `${coreIds.protocolPkg}::withdraw_collateral::withdraw_collateral`,\n arguments: [\n txBlock.object(coreIds.version),\n txBlock.object(obligation as string),\n txBlock.object(obligationKey as string),\n txBlock.object(coreIds.market),\n txBlock.object(coreIds.coinDecimalsRegistry),\n txBlock.pure(amount),\n txBlock.object(coreIds.xOracle),\n txBlock.object(SUI_CLOCK_OBJECT_ID),\n ],\n typeArguments: [coinType],\n });\n },\n deposit: (coin, poolCoinName) => {\n const coinType = builder.utils.parseCoinType(poolCoinName);\n return txBlock.moveCall({\n target: `${coreIds.protocolPkg}::mint::mint`,\n arguments: [\n txBlock.object(coreIds.version),\n txBlock.object(coreIds.market),\n typeof coin !== 'string' ? (coin as TransactionArgument) : txBlock.pure(coin),\n txBlock.object(SUI_CLOCK_OBJECT_ID),\n ],\n typeArguments: [coinType],\n });\n },\n depositEntry: (coin, poolCoinName) => {\n const coinType = builder.utils.parseCoinType(poolCoinName);\n return txBlock.moveCall({\n target: `${coreIds.protocolPkg}::mint::mint_entry`,\n arguments: [\n txBlock.object(coreIds.version),\n txBlock.object(coreIds.market),\n typeof coin !== 'string' ? (coin as TransactionArgument) : txBlock.pure(coin),\n txBlock.object(SUI_CLOCK_OBJECT_ID),\n ],\n typeArguments: [coinType],\n });\n },\n withdraw: (marketCoin, poolCoinName) => {\n const coinType = builder.utils.parseCoinType(poolCoinName);\n return txBlock.moveCall({\n target: `${coreIds.protocolPkg}::redeem::redeem`,\n arguments: [\n txBlock.object(coreIds.version),\n txBlock.object(coreIds.market),\n typeof marketCoin !== 'string' ? (marketCoin as TransactionArgument) : txBlock.pure(marketCoin),\n txBlock.object(SUI_CLOCK_OBJECT_ID),\n ],\n typeArguments: [coinType],\n });\n },\n withdrawEntry: (marketCoin, poolCoinName) => {\n const coinType = builder.utils.parseCoinType(poolCoinName);\n return txBlock.moveCall({\n target: `${coreIds.protocolPkg}::redeem::redeem_entry`,\n arguments: [\n txBlock.object(coreIds.version),\n txBlock.object(coreIds.market),\n typeof marketCoin !== 'string' ? (marketCoin as TransactionArgument) : txBlock.pure(marketCoin),\n txBlock.object(SUI_CLOCK_OBJECT_ID),\n ],\n typeArguments: [coinType],\n });\n },\n borrow: (obligation, obligationKey, amount, poolCoinName) => {\n const coinType = builder.utils.parseCoinType(poolCoinName);\n return txBlock.moveCall({\n target: `${coreIds.protocolPkg}::borrow::borrow`,\n arguments: [\n txBlock.object(coreIds.version),\n txBlock.object(obligation as string),\n txBlock.object(obligationKey as string),\n txBlock.object(coreIds.market),\n txBlock.object(coreIds.coinDecimalsRegistry),\n txBlock.pure(amount),\n txBlock.object(coreIds.xOracle),\n txBlock.object(SUI_CLOCK_OBJECT_ID),\n ],\n typeArguments: [coinType],\n });\n },\n borrowEntry: (obligation, obligationKey, amount, poolCoinName) => {\n const coinType = builder.utils.parseCoinType(poolCoinName);\n return txBlock.moveCall({\n target: `${coreIds.protocolPkg}::borrow::borrow_entry`,\n arguments: [\n txBlock.object(coreIds.version),\n txBlock.object(obligation as string),\n txBlock.object(obligationKey as string),\n txBlock.object(coreIds.market),\n txBlock.object(coreIds.coinDecimalsRegistry),\n txBlock.pure(amount),\n txBlock.object(coreIds.xOracle),\n txBlock.object(SUI_CLOCK_OBJECT_ID),\n ],\n typeArguments: [coinType],\n });\n },\n borrowWithReferral: (obligation, obligationKey, borrowReferral, amount, poolCoinName) => {\n const coinType = builder.utils.parseCoinType(poolCoinName);\n return txBlock.moveCall({\n target: `${coreIds.protocolPkg}::borrow::borrow_with_referral`,\n arguments: [\n txBlock.object(coreIds.version),\n txBlock.object(obligation as string),\n txBlock.object(obligationKey as string),\n txBlock.object(coreIds.market),\n txBlock.object(coreIds.coinDecimalsRegistry),\n txBlock.object(borrowReferral as string),\n txBlock.pure(amount),\n txBlock.object(coreIds.xOracle),\n txBlock.object(SUI_CLOCK_OBJECT_ID),\n ],\n typeArguments: [coinType, referralWitnessType],\n });\n },\n repay: (obligation, coin, poolCoinName) => {\n const coinType = builder.utils.parseCoinType(poolCoinName);\n return txBlock.moveCall({\n target: `${coreIds.protocolPkg}::repay::repay`,\n arguments: [\n txBlock.object(coreIds.version),\n txBlock.object(obligation as string),\n txBlock.object(coreIds.market),\n typeof coin !== 'string' ? (coin as TransactionArgument) : txBlock.pure(coin),\n txBlock.object(SUI_CLOCK_OBJECT_ID),\n ],\n typeArguments: [coinType],\n });\n },\n borrowFlashLoan: (amount, poolCoinName) => {\n const coinType = builder.utils.parseCoinType(poolCoinName);\n return txBlock.moveCall({\n target: `${coreIds.protocolPkg}::flash_loan::borrow_flash_loan`,\n arguments: [txBlock.object(coreIds.version), txBlock.object(coreIds.market), txBlock.pure(amount)],\n typeArguments: [coinType],\n });\n },\n repayFlashLoan: (coin, loan, poolCoinName) => {\n const coinType = builder.utils.parseCoinType(poolCoinName);\n return txBlock.moveCall({\n target: `${coreIds.protocolPkg}::flash_loan::repay_flash_loan`,\n arguments: [\n txBlock.object(coreIds.version),\n txBlock.object(coreIds.market),\n txBlock.pure(coin),\n txBlock.object(loan as string),\n ],\n typeArguments: [coinType],\n });\n },\n };\n};\n\n/**\n * Generate core quick methods.\n *\n * @description\n * The quick methods are the same as the normal methods, but they will automatically\n * help users organize transaction blocks, include query obligation info, and transfer\n * coins to the sender. So, they are all asynchronous methods.\n *\n * @param builder - Scallop builder instance.\n * @param txBlock - TxBlock created by SuiKit.\n * @return Core quick methods.\n */\nexport const generateCoreQuickMethod: GenerateCoreQuickMethod = async ({ builder, txBlock }) => {\n const normalMethod = await generateCoreNormalMethod({ builder, txBlock });\n const scoinNormalMethod = await generateSCoinNormalMethod({ builder, txBlock });\n return {\n normalMethod,\n addCollateralQuick: async (amount, collateralCoinName, obligationId) => {\n const sender = requireSender(txBlock);\n const { obligationId: obligationArg } = await requireObligationInfo(txBlock, builder, obligationId);\n\n if (collateralCoinName === 'sui') {\n const [suiCoin] = txBlock.splitCoins(txBlock.gas, [amount]);\n normalMethod.addCollateral(obligationArg, suiCoin, collateralCoinName);\n } else {\n const { leftCoin, takeCoin } = await builder.selectCoin(\n txBlock as ScallopTxBlock,\n collateralCoinName,\n amount,\n sender,\n );\n normalMethod.addCollateral(obligationArg, takeCoin, collateralCoinName);\n txBlock.transferObjects([leftCoin], sender);\n }\n },\n takeCollateralQuick: async (amount, collateralCoinName, obligationId, obligationKey) => {\n const obligationInfo = await requireObligationInfo(txBlock, builder, obligationId, obligationKey);\n const updateCoinNames = await builder.query.getObligationCoinNames(obligationInfo.obligationId);\n await updateOracles(builder, txBlock, updateCoinNames);\n return normalMethod.takeCollateral(\n obligationInfo.obligationId,\n obligationInfo.obligationKey as SuiAddressArg,\n amount,\n collateralCoinName,\n );\n },\n depositQuick: async (amount, poolCoinName, walletAddress) => {\n if (poolCoinName === 'sui') {\n const [suiCoin] = txBlock.splitCoins(txBlock.gas, [amount]);\n return normalMethod.deposit(suiCoin, poolCoinName);\n }\n const { leftCoin, takeCoin } = await builder.selectCoin(\n txBlock as ScallopTxBlock,\n poolCoinName,\n amount,\n walletAddress as string,\n );\n txBlock.transferObjects([leftCoin], walletAddress as string);\n return normalMethod.deposit(takeCoin, poolCoinName);\n },\n withdrawQuick: async (amount, poolCoinName) => {\n const sender = requireSender(txBlock);\n const marketCoinName = builder.utils.parseMarketCoinName(poolCoinName);\n // check if user has sCoin instead of marketCoin\n try {\n const sCoinName = builder.utils.parseSCoinName(poolCoinName);\n if (!sCoinName) {\n throw new Error(`No sCoin for ${poolCoinName}`);\n }\n const {\n leftCoin,\n takeCoin,\n totalAmount: sCoinAmount,\n } = await builder.selectSCoin(txBlock, sCoinName, amount, sender);\n txBlock.transferObjects([leftCoin], sender);\n const marketCoin = scoinNormalMethod.burnSCoin(sCoinName, takeCoin);\n\n const txResult = normalMethod.withdraw(marketCoin, poolCoinName);\n\n // check amount\n const amountLeft = amount - sCoinAmount;\n try {\n if (amountLeft > 0) {\n // sCoin is not enough, try market coin\n const { leftCoin: leftMarketCoin, takeCoin: takeMarketCoin } = await builder.selectMarketCoin(\n txBlock,\n marketCoinName,\n amountLeft,\n sender,\n );\n txBlock.transferObjects([leftMarketCoin], sender);\n txBlock.mergeCoins(txResult, [normalMethod.withdraw(takeMarketCoin, poolCoinName)]);\n }\n } catch (e) {\n // ignore\n }\n return txResult;\n } catch (e) {\n // no sCoin found\n const { leftCoin, takeCoin } = await builder.selectMarketCoin(txBlock, marketCoinName, amount, sender);\n txBlock.transferObjects([leftCoin], sender);\n return normalMethod.withdraw(takeCoin, poolCoinName);\n }\n },\n borrowQuick: async (amount, poolCoinName, obligationId, obligationKey) => {\n const obligationInfo = await requireObligationInfo(txBlock, builder, obligationId, obligationKey);\n const obligationCoinNames = await builder.query.getObligationCoinNames(obligationInfo.obligationId);\n const updateCoinNames = [...obligationCoinNames, poolCoinName];\n await updateOracles(builder, txBlock, updateCoinNames);\n return normalMethod.borrow(\n obligationInfo.obligationId,\n obligationInfo.obligationKey as SuiAddressArg,\n amount,\n poolCoinName,\n );\n },\n borrowWithReferralQuick: async (amount, poolCoinName, borrowReferral, obligationId, obligationKey) => {\n const obligationInfo = await requireObligationInfo(txBlock, builder, obligationId, obligationKey);\n const obligationCoinNames = await builder.query.getObligationCoinNames(obligationInfo.obligationId);\n const updateCoinNames = [...obligationCoinNames, poolCoinName];\n await updateOracles(builder, txBlock, updateCoinNames);\n return normalMethod.borrowWithReferral(\n obligationInfo.obligationId,\n obligationInfo.obligationKey as SuiAddressArg,\n borrowReferral,\n amount,\n poolCoinName,\n );\n },\n repayQuick: async (amount, poolCoinName, obligationId, walletAddress) => {\n const obligationInfo = await requireObligationInfo(txBlock, builder, obligationId);\n\n if (poolCoinName === 'sui') {\n const [suiCoin] = txBlock.splitCoins(txBlock.gas, [amount]);\n return normalMethod.repay(obligationInfo.obligationId, suiCoin, poolCoinName);\n }\n const { leftCoin, takeCoin } = await builder.selectCoin(\n txBlock as ScallopTxBlock,\n poolCoinName,\n amount,\n walletAddress as string,\n );\n txBlock.transferObjects([leftCoin], walletAddress as string);\n return normalMethod.repay(obligationInfo.obligationId, takeCoin, poolCoinName);\n },\n updateAssetPricesQuick: async (assetCoinNames) => updateOracles(builder, txBlock, assetCoinNames),\n };\n};\n","import type { TransactionArgument, TransactionBlock } from '@mysten/sui.js/transactions';\nimport { SUI_CLOCK_OBJECT_ID } from '@mysten/sui.js/utils';\n// eslint-disable-next-line import/no-extraneous-dependencies\nimport axios from 'axios';\n\nimport { SUPPORT_COLLATERALS, SUPPORT_POOLS } from '../constants';\nimport { PYTH_ENDPOINTS } from '../constants/pyth';\nimport type { ScallopBuilder } from '../models';\nimport { PythClient } from '../models/pythClient';\nimport type { SupportAssetCoins, SupportOracleType } from '../types';\n\nexport const getLatestVaas = async (endpoint: string, priceIds: string[]) => {\n const response = await axios.get(`${endpoint}/api/latest_vaas`, {\n params: {\n ids: priceIds,\n },\n });\n const latestVaas = response.data;\n return latestVaas.map((vaa: string) => Buffer.from(vaa, 'base64'));\n};\n\n/**\n * Update the price of the oracle for multiple coin.\n *\n * @param builder - The scallop builder.\n * @param txBlock - TxBlock created by SuiKit.\n * @param assetCoinNames - Specific an array of support asset coin name.\n */\nexport const updateOracles = async (\n builder: ScallopBuilder,\n txBlock: TransactionBlock,\n assetCoinNames?: SupportAssetCoins[],\n) => {\n const coinNames = assetCoinNames ?? [...new Set([...SUPPORT_POOLS, ...SUPPORT_COLLATERALS])];\n const rules: SupportOracleType[] = builder.isTestnet ? ['pyth'] : ['pyth'];\n if (rules.includes('pyth')) {\n const pythClient = new PythClient(\n builder.client as any,\n builder.address.get('core.oracles.pyth.state'),\n builder.address.get('core.oracles.pyth.wormholeState'),\n );\n const priceIds: string[] = [];\n await Promise.all(\n coinNames.map(async (assetCoinName) =>\n priceIds.push(builder.address.get(`core.coins.${assetCoinName}.oracle.pyth.feed`)),\n ),\n );\n\n // iterate through the endpoints\n const endpoints = builder.params.pythEndpoints ?? PYTH_ENDPOINTS[builder.isTestnet ? 'testnet' : 'mainnet'];\n try {\n const priceUpdateData = await getLatestVaas(endpoints[0], priceIds);\n await pythClient.updatePriceFeeds(txBlock as any, priceUpdateData, priceIds);\n } catch (e) {\n console.warn(`Failed to update price feeds with endpoint ${endpoints[0]}: ${e}`);\n }\n }\n\n // Remove duplicate coin names.\n const updateAssetCoinNames = [...new Set(coinNames)];\n for (let i = 0; i < updateAssetCoinNames.length; i++) {\n await updateOracle(builder, txBlock, updateAssetCoinNames[i], rules);\n }\n};\n\n/**\n * Update the price of the oracle for specific coin.\n *\n * @param builder - The scallop builder.\n * @param txBlock - TxBlock created by SuiKit.\n * @param assetCoinName - Specific support asset coin name.\n */\nconst updateOracle = async (\n builder: ScallopBuilder,\n txBlock: TransactionBlock,\n assetCoinName: SupportAssetCoins,\n rules: SupportOracleType[],\n) => {\n const coinType = builder.utils.parseCoinType(assetCoinName);\n\n updatePrice(\n txBlock,\n rules,\n builder.address.get('core.packages.xOracle.id'),\n builder.address.get('core.oracles.xOracle'),\n builder.address.get('core.packages.pyth.id'),\n builder.address.get('core.oracles.pyth.registry'),\n builder.address.get('core.oracles.pyth.state'),\n builder.address.get(`core.coins.${assetCoinName}.oracle.pyth.feedObject`),\n builder.address.get('core.packages.switchboard.id'),\n builder.address.get('core.oracles.switchboard.registry'),\n builder.address.get(`core.coins.${assetCoinName}.oracle.switchboard`),\n builder.address.get('core.packages.supra.id'),\n builder.address.get('core.oracles.supra.registry'),\n builder.address.get(`core.oracles.supra.holder`),\n coinType,\n );\n};\n\n/**\n * Construct a transaction block for update the price.\n *\n * @param txBlock - The transaction block.\n * @param rules - The oracle rules.\n * @param xOraclePackageId - The xOracle package id.\n * @param xOracleId - The xOracle Id from xOracle package.\n * @param pythPackageId - The pyth package id.\n * @param pythRegistryId - The registry id from pyth package.\n * @param pythStateId - The price state id from pyth package.\n * @param pythFeedObjectId - The feed object id from pyth package.\n * @param switchboardPackageId - The switchboard package id.\n * @param switchboardRegistryId - The registry id from switchboard package.\n * @param switchboardAggregatorId - The aggregator id from switchboard package.\n * @param supraPackageId - The supra package id.\n * @param supraRegistryId - The registry id from supra package.\n * @param supraHolderId - The holder id from supra package.\n * @param coinType - The type of coin.\n * @return TxBlock created by SuiKit.\n */\nconst updatePrice = (\n txBlock: TransactionBlock,\n rules: SupportOracleType[],\n xOraclePackageId: string,\n xOracleId: TransactionArgument | string,\n pythPackageId: string,\n pythRegistryId: TransactionArgument | string,\n pythStateId: TransactionArgument | string,\n pythFeedObjectId: TransactionArgument | string,\n switchboardPackageId: string,\n switchboardRegistryId: TransactionArgument | string,\n switchboardAggregatorId: TransactionArgument | string,\n supraPackageId: string,\n supraRegistryId: TransactionArgument | string,\n supraHolderId: TransactionArgument | string,\n coinType: string,\n) => {\n const request = priceUpdateRequest(txBlock, xOraclePackageId, xOracleId, coinType);\n if (rules.includes('pyth')) {\n updatePythPrice(txBlock, pythPackageId, request, pythStateId, pythFeedObjectId, pythRegistryId, coinType);\n }\n if (rules.includes('switchboard')) {\n updateSwitchboardPrice(\n txBlock,\n switchboardPackageId,\n request,\n switchboardAggregatorId,\n switchboardRegistryId,\n coinType,\n );\n }\n if (rules.includes('supra')) {\n updateSupraPrice(txBlock, supraPackageId, request, supraHolderId, supraRegistryId, coinType);\n }\n confirmPriceUpdateRequest(txBlock, xOraclePackageId, xOracleId, request, coinType);\n return txBlock;\n};\n\n/**\n * Construct a transaction block for request price update.\n *\n * @param txBlock - The transaction block.\n * @param packageId - The xOracle package id.\n * @param xOracleId - The xOracle Id from xOracle package.\n * @param coinType - The type of coin.\n * @return TxBlock created by SuiKit.\n */\nconst priceUpdateRequest = (\n txBlock: TransactionBlock,\n packageId: string,\n xOracleId: TransactionArgument | string,\n coinType: string,\n) => {\n const validXOracleId = typeof xOracleId === 'string' ? txBlock.object(xOracleId) : xOracleId;\n const target = `${packageId}::x_oracle::price_update_request` as `${string}::${string}::${string}`;\n const typeArgs = [coinType];\n return txBlock.moveCall({ target, arguments: [validXOracleId], typeArguments: typeArgs });\n};\n\n/**\n * Construct a transaction block for confirm price update request.\n *\n * @param txBlock - The transaction block.\n * @param packageId - The xOracle package id.\n * @param xOracleId - The xOracle Id from xOracle package.\n * @param request - The result of the request.\n * @param coinType - The type of coin.\n * @return TxBlock created by SuiKit.\n */\nconst confirmPriceUpdateRequest = (\n txBlock: TransactionBlock,\n packageId: string,\n xOracleId: TransactionArgument | string,\n request: TransactionArgument,\n coinType: string,\n) => {\n const target = `${packageId}::x_oracle::confirm_price_update_request` as `${string}::${string}::${string}`;\n const typeArgs = [coinType];\n const validXOracleId = typeof xOracleId === 'string' ? txBlock.object(xOracleId) : xOracleId;\n txBlock.moveCall({\n target,\n arguments: [validXOracleId, request, txBlock.object(SUI_CLOCK_OBJECT_ID)],\n typeArguments: typeArgs,\n });\n return txBlock;\n};\n\n/**\n * Construct a transaction block for update supra price.\n *\n * @param txBlock - The transaction block.\n * @param packageId - The supra package id.\n * @param request - The result of the request.\n * @param holderId - The holder id from supra package.\n * @param registryId - The registry id from supra package.\n * @param coinType - The type of coin.\n * @return TxBlock created by SuiKit.\n */\nconst updateSupraPrice = (\n txBlock: TransactionBlock,\n packageId: string,\n request: TransactionArgument,\n holderId: TransactionArgument | string,\n registryId: TransactionArgument | string,\n coinType: string,\n) => {\n const validHolderId = typeof holderId === 'string' ? txBlock.object(holderId) : holderId;\n const validRegistryId = typeof registryId === 'string' ? txBlock.object(registryId) : registryId;\n txBlock.moveCall({\n target: `${packageId}::rule::set_price`,\n arguments: [request, validHolderId, validRegistryId, txBlock.object(SUI_CLOCK_OBJECT_ID)],\n typeArguments: [coinType],\n });\n};\n\n/**\n * Construct a transaction block for update switchboard price.\n *\n * @param txBlock - The transaction block.\n * @param packageId - The switchboard package id.\n * @param request - The result of the request.\n * @param aggregatorId - The aggregator id from switchboard package.\n * @param registryId - The registry id from switchboard package.\n * @param coinType - The type of coin.\n * @return TxBlock created by SuiKit.\n */\nconst updateSwitchboardPrice = (\n txBlock: TransactionBlock,\n packageId: string,\n request: TransactionArgument,\n aggregatorId: TransactionArgument | string,\n registryId: TransactionArgument | string,\n coinType: string,\n) => {\n const validAggregatorId = typeof aggregatorId === 'string' ? txBlock.object(aggregatorId) : aggregatorId;\n const validRegistryId = typeof registryId === 'string' ? txBlock.object(registryId) : registryId;\n txBlock.moveCall({\n target: `${packageId}::rule::set_price`,\n arguments: [request, validAggregatorId, validRegistryId, txBlock.object(SUI_CLOCK_OBJECT_ID)],\n typeArguments: [coinType],\n });\n};\n\n/**\n * Construct a transaction block for update pyth price.\n *\n * @param txBlock - The transaction block.\n * @param packageId - The pyth package id.\n * @param request - The result of the request.\n * @param stateId - The price state id from pyth package.\n * @param wormholeStateId - The whormhole state id from pyth package.\n * @param feedObjectId - The feed object id from pyth package.\n * @param vaaFromFeeId - The vaa from pyth api with feed id.\n * @param registryId - The registry id from pyth package.\n * @param coinType - The type of coin.\n * @return TxBlock created by SuiKit.\n */\nconst updatePythPrice = (\n txBlock: TransactionBlock,\n packageId: string,\n request: TransactionArgument | string,\n stateId: TransactionArgument | string,\n feedObjectId: TransactionArgument | string,\n registryId: TransactionArgument | string,\n coinType: string,\n) => {\n const validRequest = typeof request === 'string' ? txBlock.object(request) : request;\n const validStateId = typeof stateId === 'string' ? txBlock.object(stateId) : stateId;\n const validFeedObjectId = typeof feedObjectId === 'string' ? txBlock.object(feedObjectId) : feedObjectId;\n const validRegistryId = typeof registryId === 'string' ? txBlock.object(registryId) : registryId;\n\n txBlock.moveCall({\n target: `${packageId}::rule::set_price`,\n arguments: [validRequest, validStateId, validFeedObjectId, validRegistryId, txBlock.object(SUI_CLOCK_OBJECT_ID)],\n typeArguments: [coinType],\n });\n};\n","export const PYTH_ENDPOINTS: {\n [k in 'mainnet' | 'testnet']: Readonly<string[]>;\n} = {\n testnet: ['https://hermes-beta.pyth.network'],\n mainnet: ['https://hermes.pyth.network', 'https://scallop.rpc.p2p.world'],\n} as const;\n","import { bcs } from '@mysten/sui.js/bcs';\nimport { SuiClient } from '@mysten/sui.js/client';\nimport { TransactionBlock } from '@mysten/sui.js/transactions';\nimport { SUI_CLOCK_OBJECT_ID } from '@mysten/sui.js/utils';\n\nconst MAX_ARGUMENT_SIZE = 16 * 1024;\n\nexport class PythClient {\n provider: SuiClient;\n\n pythStateId: string;\n\n wormholeStateId: string;\n\n private pythPackageId: any;\n\n private wormholePackageId: any;\n\n private priceTableInfo: { id: string; fieldType: string };\n\n private priceFeedObjectIdCache: Map<string, string> = new Map();\n\n private baseUpdateFee: any;\n\n constructor(provider: SuiClient, pythStateId: string, wormholeStateId: string) {\n this.provider = provider;\n this.pythStateId = pythStateId;\n this.wormholeStateId = wormholeStateId;\n this.pythPackageId = undefined;\n this.wormholePackageId = undefined;\n }\n\n async getBaseUpdateFee() {\n if (this.baseUpdateFee === undefined) {\n const result = await this.provider.getObject({\n id: this.pythStateId,\n options: { showContent: true },\n });\n if (!result.data || !result.data.content || result.data.content.dataType !== 'moveObject') {\n throw new Error('Unable to fetch pyth state object');\n }\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n this.baseUpdateFee = result.data.content.fields.base_update_fee;\n }\n return this.baseUpdateFee;\n }\n\n /**\n * getPackageId returns the latest package id that the object belongs to. Use this to\n * fetch the latest package id for a given object id and handle package upgrades automatically.\n * @param objectId\n * @returns package id\n */\n async getPackageId(objectId: string) {\n const state = await this.provider\n .getObject({\n id: objectId,\n options: {\n showContent: true,\n },\n })\n .then((result) => {\n if (result.data?.content?.dataType === 'moveObject') {\n return result.data.content.fields;\n }\n throw new Error(`Cannot fetch package id for object ${objectId}`);\n });\n if ('upgrade_cap' in state) {\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n return state.upgrade_cap.fields.package;\n }\n throw new Error('upgrade_cap not found');\n }\n\n /**\n * Adds the commands for calling wormhole and verifying the vaas and returns the verified vaas.\n * @param vaas array of vaas to verify\n * @param tx transaction block to add commands to\n */\n async verifyVaas(vaas: Buffer[], tx: TransactionBlock) {\n const wormholePackageId = await this.getWormholePackageId();\n const verifiedVaas: {\n index: number;\n resultIndex: number;\n kind: 'NestedResult';\n }[] = [];\n vaas.forEach((vaa) => {\n const [verifiedVaa] = tx.moveCall({\n target: `${wormholePackageId}::vaa::parse_and_verify`,\n arguments: [\n tx.object(this.wormholeStateId),\n tx.pure(\n bcs\n .ser('vector<u8>', Array.from(vaa), {\n maxSize: MAX_ARGUMENT_SIZE,\n })\n .toBytes(),\n ),\n tx.object(SUI_CLOCK_OBJECT_ID),\n ],\n });\n verifiedVaas.push(verifiedVaa);\n });\n return verifiedVaas;\n }\n\n /**\n * Adds the necessary commands for updating the pyth price feeds to the transaction block.\n * @param tx transaction block to add commands to\n * @param updates array of price feed updates received from the price service\n * @param feedIds array of feed ids to update (in hex format)\n */\n async updatePriceFeeds(tx: TransactionBlock, updates: Buffer[], feedIds: string[]) {\n const packageId = await this.getPythPackageId();\n let priceUpdatesHotPotato;\n if (updates.length > 1) {\n throw new Error('SDK does not support sending multiple accumulator messages in a single transaction');\n }\n const vaa = this.extractVaaBytesFromAccumulatorMessage(updates[0]);\n const verifiedVaas = await this.verifyVaas([vaa], tx);\n [priceUpdatesHotPotato] = tx.moveCall({\n target: `${packageId}::pyth::create_authenticated_price_infos_using_accumulator`,\n arguments: [\n tx.object(this.pythStateId),\n tx.pure(\n bcs\n .ser('vector<u8>', Array.from(updates[0]), {\n maxSize: MAX_ARGUMENT_SIZE,\n })\n .toBytes(),\n ),\n verifiedVaas[0],\n tx.object(SUI_CLOCK_OBJECT_ID),\n ],\n });\n const priceInfoObjects = [];\n const baseUpdateFee = await this.getBaseUpdateFee();\n const coins = tx.splitCoins(\n tx.gas,\n feedIds.map(() => tx.pure(baseUpdateFee)),\n );\n let coinId = 0;\n for (let i = 0; i < feedIds.length; i++) {\n const priceInfoObjectId = await this.getPriceFeedObjectId(feedIds[i]);\n if (!priceInfoObjectId) {\n throw new Error(`Price feed ${feedIds[0]} not found, please create it first`);\n }\n priceInfoObjects.push(priceInfoObjectId);\n [priceUpdatesHotPotato] = tx.moveCall({\n target: `${packageId}::pyth::update_single_price_feed`,\n arguments: [\n tx.object(this.pythStateId),\n priceUpdatesHotPotato,\n tx.object(priceInfoObjectId),\n coins[coinId],\n tx.object(SUI_CLOCK_OBJECT_ID),\n ],\n });\n coinId++;\n }\n tx.moveCall({\n target: `${packageId}::hot_potato_vector::destroy`,\n arguments: [priceUpdatesHotPotato],\n typeArguments: [`${packageId}::price_info::PriceInfo`],\n });\n return priceInfoObjects;\n }\n\n async createPriceFeed(tx: TransactionBlock, updates: Buffer[]) {\n const packageId = await this.getPythPackageId();\n if (updates.length > 1) {\n throw new Error('SDK does not support sending multiple accumulator messages in a single transaction');\n }\n const vaa = this.extractVaaBytesFromAccumulatorMessage(updates[0]);\n const verifiedVaas = await this.verifyVaas([vaa], tx);\n tx.moveCall({\n target: `${packageId}::pyth::create_price_feeds_using_accumulator`,\n arguments: [\n tx.object(this.pythStateId),\n tx.pure(\n bcs\n .ser('vector<u8>', Array.from(updates[0]), {\n maxSize: MAX_ARGUMENT_SIZE,\n })\n .toBytes(),\n ),\n verifiedVaas[0],\n tx.object(SUI_CLOCK_OBJECT_ID),\n ],\n });\n }\n\n /**\n * Get the packageId for the wormhole package if not already cached\n */\n async getWormholePackageId() {\n if (!this.wormholePackageId) {\n this.wormholePackageId = await this.getPackageId(this.wormholeStateId);\n }\n return this.wormholePackageId;\n }\n\n /**\n * Get the packageId for the pyth package if not already cached\n */\n async getPythPackageId() {\n if (!this.pythPackageId) {\n this.pythPackageId = await this.getPackageId(this.pythStateId);\n }\n return this.pythPackageId;\n }\n\n /**\n * Get the priceFeedObjectId for a given feedId if not already cached\n * @param feedId\n */\n async getPriceFeedObjectId(feedId: string) {\n const normalizedFeedId = feedId.replace('0x', '');\n if (!this.priceFeedObjectIdCache.has(normalizedFeedId)) {\n const { id: tableId, fieldType } = await this.getPriceTableInfo();\n const result = await this.provider.getDynamicFieldObject({\n parentId: tableId,\n name: {\n type: `${fieldType}::price_identifier::PriceIdentifier`,\n value: {\n bytes: Array.from(Buffer.from(normalizedFeedId, 'hex')),\n },\n },\n });\n if (!result.data || !result.data.content) {\n return undefined;\n }\n if (result.data.content.dataType !== 'moveObject') {\n throw new Error('Price feed type mismatch');\n }\n this.priceFeedObjectIdCache.set(\n normalizedFeedId,\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n result.data.content.fields.value,\n );\n }\n return this.priceFeedObjectIdCache.get(normalizedFeedId);\n }\n\n /**\n * Fetches the price table object id for the current state id if not cached\n * @returns price table object id\n */\n async getPriceTableInfo() {\n if (this.priceTableInfo === undefined) {\n const result = await this.provider.getDynamicFieldObject({\n parentId: this.pythStateId,\n name: {\n type: 'vector<u8>',\n value: 'price_info',\n },\n });\n if (!result.data || !result.data.type) {\n throw new Error('Price Table not found, contract may not be initialized');\n }\n let type = result.data.type.replace('0x2::table::Table<', '');\n type = type.replace('::price_identifier::PriceIdentifier, 0x2::object::ID>', '');\n this.priceTableInfo = { id: result.data.objectId, fieldType: type };\n }\n return this.priceTableInfo;\n }\n\n /**\n * Obtains the vaa bytes embedded in an accumulator message.\n * @param accumulatorMessage - the accumulator price update message\n * @returns vaa bytes as a uint8 array\n */\n extractVaaBytesFromAccumulatorMessage(accumulatorMessage: Buffer): Buffer {\n // the first 6 bytes in the accumulator message encode the header, major, and minor bytes\n // we ignore them, since we are only interested in the VAA bytes\n const trailingPayloadSize = accumulatorMessage.readUint8(6);\n const vaaSizeOffset =\n 7 + // header bytes (header(4) + major(1) + minor(1) + trailing payload size(1))\n trailingPayloadSize + // trailing payload (variable number of bytes)\n 1; // proof_type (1 byte)\n const vaaSize = accumulatorMessage.readUint16BE(vaaSizeOffset);\n const vaaOffset = vaaSizeOffset + 2;\n return accumulatorMessage.subarray(vaaOffset, vaaOffset + vaaSize);\n }\n}\n","import { TransactionArgument } from '@mysten/sui.js/transactions';\n\nimport { SUPPORT_SCOIN } from '../constants';\nimport { GenerateSCoinNormalMethod, GenerateSCoinQuickMethod, SCoinPkgIds, sCoinTreasuryIds } from '../types';\n\nexport const generateSCoinNormalMethod: GenerateSCoinNormalMethod = async ({ builder, txBlock }) => {\n const sCoinPkgIds: SCoinPkgIds = {\n pkgId: builder.address.get('scoin.id'),\n };\n\n const treasuryIds: sCoinTreasuryIds = {};\n await Promise.all(\n SUPPORT_SCOIN.map(async (sCoinName) => {\n const treasuryId = builder.utils.getSCoinTreasury(sCoinName);\n treasuryIds[sCoinName] = treasuryId;\n }),\n );\n\n return {\n mintSCoin: (marketCoinName, marketCoin) =>\n txBlock.moveCall({\n target: `${sCoinPkgIds.pkgId}::s_coin_converter::mint_s_coin`,\n arguments: [\n txBlock.object(treasuryIds[marketCoinName]),\n typeof marketCoin !== 'string' ? (marketCoin as TransactionArgument) : txBlock.pure(marketCoin),\n ],\n typeArguments: [\n builder.utils.parseSCoinType(marketCoinName),\n builder.utils.parseUnderlyingSCoinType(marketCoinName),\n ],\n }),\n burnSCoin: (sCoinName, sCoin) =>\n txBlock.moveCall({\n target: `${sCoinPkgIds.pkgId}::s_coin_converter::burn_s_coin`,\n arguments: [\n txBlock.object(treasuryIds[sCoinName]),\n typeof sCoin !== 'string' ? (sCoin as TransactionArgument) : txBlock.pure(sCoin),\n ],\n typeArguments: [builder.utils.parseSCoinType(sCoinName), builder.utils.parseUnderlyingSCoinType(sCoinName)],\n }),\n };\n};\n\nexport const generateSCoinQuickMethod: GenerateSCoinQuickMethod = async ({ builder, txBlock }) => ({\n mintSCoinQuick: async (marketCoinName, amount, walletAddress) => {\n const { leftCoin, takeCoin } = await builder.selectMarketCoin(txBlock, marketCoinName, amount, walletAddress);\n\n txBlock.transferObjects([leftCoin], walletAddress);\n return txBlock.mintSCoin(marketCoinName, takeCoin);\n },\n burnSCoinQuick: async (sCoinName, amount, walletAddress) => {\n const { leftCoin, takeCoin } = await builder.selectSCoin(txBlock, sCoinName, amount, walletAddress);\n\n txBlock.transferObjects([leftCoin], walletAddress);\n return txBlock.burnSCoin(sCoinName, takeCoin);\n },\n});\n","import { TransactionObjectArgument } from '@mysten/sui.js/transactions';\nimport { SUI_CLOCK_OBJECT_ID } from '@mysten/sui.js/utils';\n\nimport { SUPPORT_POOLS } from '../constants';\nimport {\n SupportCoins,\n SupportPoolCoins,\n GenerateReferralNormalMethod,\n GenerateReferralQuickMethod,\n ReferralIds,\n SuiObjectArg,\n} from '../types';\n\nexport const generateReferralNormalMethod: GenerateReferralNormalMethod = async ({ builder, txBlock }) => {\n const referralIds: ReferralIds = {\n referralPgkId: builder.address.get('referral.id'),\n referralBindings: builder.address.get('referral.referralBindings'),\n referralRevenuePool: builder.address.get('referral.referralRevenuePool'),\n authorizedWitnessList: builder.address.get('referral.authorizedWitnessList'),\n referralTiers: builder.address.get('referral.referralTiers'),\n version: builder.address.get('referral.version'),\n };\n\n const veScaTable = builder.address.get('vesca.table');\n\n return {\n bindToReferral: (veScaKeyId: string) =>\n txBlock.moveCall({\n target: `${referralIds.referralPgkId}::referral_bindings::bind_ve_sca_referrer`,\n arguments: [\n txBlock.object(referralIds.referralBindings),\n txBlock.pure(veScaKeyId),\n txBlock.object(veScaTable),\n txBlock.object(SUI_CLOCK_OBJECT_ID),\n ],\n typeArguments: [],\n }),\n claimReferralTicket: (poolCoinName: SupportCoins) => {\n const coinType = builder.utils.parseCoinType(poolCoinName);\n return txBlock.moveCall({\n target: `${referralIds.referralPgkId}::scallop_referral_program::claim_ve_sca_referral_ticket`,\n arguments: [\n txBlock.object(referralIds.version),\n txBlock.object(veScaTable),\n txBlock.object(referralIds.referralBindings),\n txBlock.object(referralIds.authorizedWitnessList),\n txBlock.object(referralIds.referralTiers),\n txBlock.object(SUI_CLOCK_OBJECT_ID),\n ],\n typeArguments: [coinType],\n });\n },\n burnReferralTicket: (ticket: SuiObjectArg, poolCoinName: SupportCoins) => {\n const coinType = builder.utils.parseCoinType(poolCoinName);\n return txBlock.moveCall({\n target: `${referralIds.referralPgkId}::scallop_referral_program::burn_ve_sca_referral_ticket`,\n arguments: [\n txBlock.object(referralIds.version),\n txBlock.object(ticket as string),\n txBlock.object(referralIds.referralRevenuePool),\n txBlock.object(SUI_CLOCK_OBJECT_ID),\n ],\n typeArguments: [coinType],\n });\n },\n claimReferralRevenue: (veScaKey: SuiObjectArg, poolCoinName: SupportCoins) => {\n const coinType = builder.utils.parseCoinType(poolCoinName);\n return txBlock.moveCall({\n target: `${referralIds.referralPgkId}::referral_revenue_pool::claim_revenue_with_ve_sca_key`,\n arguments: [\n txBlock.object(referralIds.version),\n txBlock.object(referralIds.referralRevenuePool),\n txBlock.object(veScaKey as string),\n txBlock.object(SUI_CLOCK_OBJECT_ID),\n ],\n typeArguments: [coinType],\n });\n },\n };\n};\n\nexport const generateReferralQuickMethod: GenerateReferralQuickMethod = async ({ builder, txBlock }) => {\n const normalMethod = await generateReferralNormalMethod({ builder, txBlock });\n return {\n claimReferralRevenueQuick: async (\n veScaKey: SuiObjectArg,\n walletAddress: string,\n coinNames: SupportPoolCoins[] = [...SUPPORT_POOLS],\n ) => {\n const objToTransfer: SuiObjectArg[] = [];\n for (let i = 0; i < coinNames.length; i++) {\n if (coinNames[i] === 'sui') {\n const rewardCoin = normalMethod.claimReferralRevenue(veScaKey, coinNames[i]);\n objToTransfer.push(rewardCoin);\n } else {\n const rewardCoin = normalMethod.claimReferralRevenue(veScaKey, coinNames[i]);\n try {\n // get the matching user coin if exists\n const coins = await builder.utils.selectCoinIds(\n Infinity,\n builder.utils.parseCoinType(coinNames[i]),\n walletAddress,\n );\n txBlock.mergeCoins(rewardCoin, coins.slice(0, 500));\n } catch (e) {\n // ignore\n } finally {\n objToTransfer.push(rewardCoin);\n }\n }\n }\n if (objToTransfer.length > 0) {\n txBlock.transferObjects(objToTransfer as (string | TransactionObjectArgument)[], txBlock.pure(walletAddress));\n }\n },\n };\n};\n","import { TransactionArgument, TransactionBlock } from '@mysten/sui.js/transactions';\n\nexport const SlippageContract = {\n packageId: '0x5857d185897aaff40ae37b2eecc895efc1a9dff1b210c4fb894eabbce4ac2603',\n} as const;\n\nexport const SlippageTxBuilder = {\n check_slippage: (\n tx: TransactionBlock,\n resultCoin: TransactionArgument,\n slippage: number,\n expectedAmount: number | string,\n coinType: string,\n ) =>\n tx.moveCall({\n target: `${SlippageContract.packageId}::slippage_check::check_slippage`,\n arguments: [resultCoin, tx.pure(slippage), tx.pure(expectedAmount)],\n typeArguments: [coinType],\n }),\n} as const;\n","import { TransactionBlock } from '@mysten/sui.js/transactions';\nimport type { TransactionResult } from '@mysten/sui.js/transactions';\nimport { SUI_CLOCK_OBJECT_ID } from '@mysten/sui.js/utils';\n\nimport { generateSCoinNormalMethod } from './sCoinBuilder';\nimport { SUPPORT_SPOOLS } from '../constants';\nimport { spoolRewardCoins } from '../constants/enum';\nimport type { ScallopBuilder } from '../models';\nimport { getStakeAccounts } from '../queries/spoolQuery';\nimport type {\n SpoolIds,\n GenerateSpoolNormalMethod,\n GenerateSpoolQuickMethod,\n SupportStakeMarketCoins,\n SuiAddressArg,\n StakePoolIds,\n RewardPoolIds,\n StakeMarketCoinTypes,\n} from '../types';\nimport { requireSender } from '../utils';\n\nconst stakeHelper = async (\n builder: ScallopBuilder,\n txBlock: TransactionBlock,\n stakeAccount: SuiAddressArg,\n coinName: SupportStakeMarketCoins,\n amount: number,\n sender: string,\n isSCoin = false,\n) => {\n const scoinNormalMethod = await generateSCoinNormalMethod({ builder, txBlock });\n const spoolNormalMethod = await generateSpoolNormalMethod({ builder, txBlock });\n try {\n const { takeCoin, leftCoin, totalAmount } = isSCoin\n ? await builder.selectSCoin(txBlock, coinName, amount, sender)\n : await builder.selectMarketCoin(txBlock, coinName, amount, sender);\n if (isSCoin) {\n const marketCoin = scoinNormalMethod.burnSCoin(coinName, takeCoin);\n spoolNormalMethod.stake(stakeAccount, marketCoin, coinName);\n } else {\n spoolNormalMethod.stake(stakeAccount, takeCoin, coinName);\n }\n txBlock.transferObjects([leftCoin], sender);\n return totalAmount;\n } catch (e) {\n return 0;\n }\n};\n\n/**\n * Check and get stake account id from transaction block.\n *\n * @description\n * If the stake account id is provided, directly return it.\n * Otherwise, automatically get all stake account id from the sender.\n *\n * @param builder - Scallop builder instance.\n * @param txBlock - TxBlock created by SuiKit.\n * @param stakeMarketCoinName - The name of the market coin supported for staking.\n * @param stakeAccountId - Stake account id.\n * @return Stake account ids.\n */\nconst requireStakeAccountIds = async (\n ...params: [\n builder: ScallopBuilder,\n txBlock: TransactionBlock,\n stakeMarketCoinName: SupportStakeMarketCoins,\n stakeAccountId?: SuiAddressArg,\n ]\n) => {\n const [builder, txBlock, stakeMarketCoinName, stakeAccountId] = params;\n if (params.length === 4 && stakeAccountId) {\n return [stakeAccountId];\n }\n const sender = requireSender(txBlock);\n const stakeAccounts = await getStakeAccounts(builder.query, sender);\n return stakeAccounts[stakeMarketCoinName].map((account) => account.id);\n};\n\n/**\n * Check and get stake accounts information from transaction block.\n *\n * @description\n * If the stake account id is provided, directly return its account.\n * Otherwise, automatically get all stake account from the sender.\n *\n * @param builder - Scallop builder instance.\n * @param txBlock - TxBlock created by SuiKit.\n * @param stakeMarketCoinName - The name of the market coin supported for staking.\n * @param stakeAccountId - Stake account id.\n * @return Stake accounts.\n */\nconst requireStakeAccounts = async (\n ...params: [\n builder: ScallopBuilder,\n txBlock: TransactionBlock,\n stakeMarketCoinName: SupportStakeMarketCoins,\n stakeAccountId?: SuiAddressArg,\n ]\n) => {\n const [builder, txBlock, stakeMarketCoinName, stakeAccountId] = params;\n const sender = requireSender(txBlock);\n const stakeAccounts = await getStakeAccounts(builder.query, sender);\n if (stakeAccounts[stakeMarketCoinName].length === 0) {\n throw new Error(`No stake account found for sender ${sender}`);\n }\n\n const specificStakeAccounts = stakeAccountId\n ? stakeAccounts[stakeMarketCoinName].filter((account) => account.id === stakeAccountId)\n : stakeAccounts[stakeMarketCoinName];\n\n return specificStakeAccounts;\n};\n\n/**\n * Generate spool normal methods.\n *\n * @param builder - Scallop builder instance.\n * @param txBlock - TxBlock created by SuiKit .\n * @return Spool normal methods.\n */\nexport const generateSpoolNormalMethod: GenerateSpoolNormalMethod = async ({ builder, txBlock }) => {\n const spoolIds: SpoolIds = {\n spoolPkg: builder.address.get('spool.id'),\n };\n const stakePoolIds: StakePoolIds = {};\n const rewardPoolIds: RewardPoolIds = {};\n const stakeMarketCoinTypes: StakeMarketCoinTypes = {};\n SUPPORT_SPOOLS.forEach((stakeMarketCoinName) => {\n const spoolId = builder.address.get(`spool.pools.${stakeMarketCoinName}.id`);\n const rewardId = builder.address.get(`spool.pools.${stakeMarketCoinName}.rewardPoolId`);\n const marketCoinType = builder.utils.parseMarketCoinType(stakeMarketCoinName);\n stakePoolIds[stakeMarketCoinName] = spoolId;\n rewardPoolIds[stakeMarketCoinName] = rewardId;\n stakeMarketCoinTypes[stakeMarketCoinName] = marketCoinType;\n });\n return {\n createStakeAccount: (stakeMarketCoinName) => {\n const marketCoinType = stakeMarketCoinTypes[stakeMarketCoinName];\n const stakePoolId = stakePoolIds[stakeMarketCoinName];\n return txBlock.moveCall({\n target: `${spoolIds.spoolPkg}::user::new_spool_account`,\n arguments: [txBlock.object(stakePoolId), txBlock.object(SUI_CLOCK_OBJECT_ID)],\n typeArguments: [marketCoinType],\n });\n },\n stake: (stakeAccount, coin, stakeMarketCoinName) => {\n const marketCoinType = stakeMarketCoinTypes[stakeMarketCoinName];\n const stakePoolId = stakePoolIds[stakeMarketCoinName];\n txBlock.moveCall({\n target: `${spoolIds.spoolPkg}::user::stake`,\n arguments: [\n txBlock.object(stakePoolId),\n txBlock.object(stakeAccount as string),\n typeof coin === 'string' ? txBlock.pure(coin) : (coin as any),\n txBlock.object(SUI_CLOCK_OBJECT_ID),\n ],\n typeArguments: [marketCoinType],\n });\n },\n unstake: (stakeAccount, amount, stakeMarketCoinName) => {\n const marketCoinType = stakeMarketCoinTypes[stakeMarketCoinName];\n const stakePoolId = stakePoolIds[stakeMarketCoinName];\n return txBlock.moveCall({\n target: `${spoolIds.spoolPkg}::user::unstake`,\n arguments: [\n txBlock.object(stakePoolId),\n txBlock.object(stakeAccount as string),\n txBlock.pure(amount),\n txBlock.object(SUI_CLOCK_OBJECT_ID),\n ],\n typeArguments: [marketCoinType],\n });\n },\n claim: (stakeAccount, stakeMarketCoinName) => {\n const stakePoolId = stakePoolIds[stakeMarketCoinName];\n const rewardPoolId = rewardPoolIds[stakeMarketCoinName];\n const marketCoinType = stakeMarketCoinTypes[stakeMarketCoinName];\n const rewardCoinName = spoolRewardCoins[stakeMarketCoinName];\n const rewardCoinType = builder.utils.parseCoinType(rewardCoinName);\n return txBlock.moveCall({\n target: `${spoolIds.spoolPkg}::user::redeem_rewards`,\n arguments: [\n txBlock.object(stakePoolId),\n txBlock.object(rewardPoolId),\n txBlock.object(stakeAccount as string),\n txBlock.object(SUI_CLOCK_OBJECT_ID),\n ],\n typeArguments: [marketCoinType, rewardCoinType],\n });\n },\n };\n};\n\n/**\n * Generate spool quick methods.\n *\n * @description\n * The quick methods are the same as the normal methods, but they will automatically\n * help users organize transaction blocks, include get stake account info, and transfer\n * coins to the sender. So, they are all asynchronous methods.\n *\n * @param builder - Scallop builder instance.\n * @param txBlock - TxBlock created by SuiKit .\n * @return Spool quick methods.\n */\nexport const generateSpoolQuickMethod: GenerateSpoolQuickMethod = async ({ builder, txBlock }) => {\n const normalMethod = await generateSpoolNormalMethod({ builder, txBlock });\n const scoinMethod = await generateSCoinNormalMethod({ builder, txBlock });\n return {\n normalMethod,\n stakeQuick: async (amountOrMarketCoin, stakeMarketCoinName, stakeAccountId) => {\n const sender = requireSender(txBlock);\n const stakeAccountIds = await requireStakeAccountIds(builder, txBlock, stakeMarketCoinName, stakeAccountId);\n const createdStakeAccount = [];\n if (stakeAccountIds.length === 0) {\n const stakeAccount = normalMethod.createStakeAccount(stakeMarketCoinName);\n createdStakeAccount.push(stakeAccount);\n }\n\n if (typeof amountOrMarketCoin === 'number') {\n // try stake market coin\n const stakedMarketCoinAmount = await stakeHelper(\n builder,\n txBlock,\n stakeAccountIds.length > 0 ? stakeAccountIds[0] : createdStakeAccount[0],\n stakeMarketCoinName,\n amountOrMarketCoin,\n sender,\n );\n\n // eslint-disable-next-line no-param-reassign\n amountOrMarketCoin -= stakedMarketCoinAmount;\n // no market coin, try sCoin\n if (!stakedMarketCoinAmount) {\n await stakeHelper(\n builder,\n txBlock,\n stakeAccountIds.length > 0 ? stakeAccountIds[0] : createdStakeAccount[0],\n stakeMarketCoinName,\n amountOrMarketCoin,\n sender,\n true,\n );\n }\n } else {\n normalMethod.stake(\n stakeAccountIds.length > 0 ? stakeAccountIds[0] : createdStakeAccount[0],\n amountOrMarketCoin,\n stakeMarketCoinName,\n );\n }\n if (createdStakeAccount.length > 0) {\n txBlock.transferObjects(createdStakeAccount, sender);\n }\n },\n unstakeQuick: async (amount, stakeMarketCoinName, stakeAccountId, returnSCoin) => {\n const stakeAccounts = await requireStakeAccounts(builder, txBlock, stakeMarketCoinName, stakeAccountId);\n const toTransfer: TransactionResult[] = [];\n let amountUnstake = amount;\n // eslint-disable-next-line no-restricted-syntax\n for (const account of stakeAccounts) {\n if (account.staked === 0) {\n continue;\n }\n const amountToUnstake = Math.min(amountUnstake, account.staked);\n const marketCoin = normalMethod.unstake(account.id, amountToUnstake, stakeMarketCoinName);\n\n // convert to new sCoin\n if (returnSCoin) {\n const sCoin = scoinMethod.mintSCoin(stakeMarketCoinName, marketCoin);\n toTransfer.push(sCoin);\n } else {\n toTransfer.push(marketCoin);\n }\n\n amountUnstake -= amountToUnstake;\n if (amount <= 0) {\n break;\n }\n }\n if (toTransfer.length > 0) {\n const mergedCoin = toTransfer[0];\n\n if (toTransfer.length > 1) {\n txBlock.mergeCoins(mergedCoin, toTransfer.slice(1));\n }\n return mergedCoin;\n }\n return undefined;\n },\n claimQuick: async (stakeMarketCoinName, stakeAccountId) => {\n const stakeAccountIds = await requireStakeAccountIds(builder, txBlock, stakeMarketCoinName, stakeAccountId);\n const rewardCoins: TransactionResult[] = [];\n stakeAccountIds.forEach((accountId) => {\n const rewardCoin = normalMethod.claim(accountId, stakeMarketCoinName);\n rewardCoins.push(rewardCoin);\n });\n return rewardCoins;\n },\n };\n};\n","import { TransactionArgument, TransactionObjectArgument } from '@mysten/sui.js/transactions';\nimport { SUI_CLOCK_OBJECT_ID } from '@mysten/sui.js/utils';\n\nimport { requireVeSca } from './borrowIncentiveBuilder';\nimport { SCA_COIN_TYPE } from '../constants';\nimport { GenerateVeScaNormalMethod, GenerateVeScaQuickMethod, SuiAddressArg, SuiObjectArg, VescaIds } from '../types';\nimport {\n requireSender,\n checkLockSca,\n checkExtendLockPeriod,\n checkExtendLockAmount,\n checkRenewExpiredVeSca,\n checkVesca,\n} from '../utils';\n\n/**\n * Generate veSCA normal methods.\n *\n * @param builder - Scallop builder instance.\n * @param txBlock - TxBlock created by SuiKit .\n * @return veSCA normal methods.\n */\nexport const generateNormalVeScaMethod: GenerateVeScaNormalMethod = async ({ builder, txBlock }) => {\n const veScaIds: VescaIds = {\n pkgId: builder.address.get('vesca.id'),\n table: builder.address.get('vesca.table'),\n treasury: builder.address.get('vesca.treasury'),\n config: builder.address.get('vesca.config'),\n };\n\n return {\n lockSca: (scaCoin, unlockAtInSecondTimestamp) =>\n txBlock.moveCall({\n target: `${veScaIds.pkgId}::ve_sca::mint_ve_sca_key`,\n arguments: [\n txBlock.object(veScaIds.config),\n txBlock.object(veScaIds.table),\n txBlock.object(veScaIds.treasury),\n typeof scaCoin === 'string' ? txBlock.pure(scaCoin) : (scaCoin as TransactionArgument),\n txBlock.pure(unlockAtInSecondTimestamp),\n txBlock.object(SUI_CLOCK_OBJECT_ID),\n ],\n }),\n extendLockPeriod: (veScaKey, newUnlockAtInSecondTimestamp) => {\n txBlock.moveCall({\n target: `${veScaIds.pkgId}::ve_sca::extend_lock_period`,\n arguments: [\n txBlock.object(veScaIds.config),\n txBlock.object(veScaKey as string),\n txBlock.object(veScaIds.table),\n txBlock.object(veScaIds.treasury),\n txBlock.pure(newUnlockAtInSecondTimestamp),\n txBlock.object(SUI_CLOCK_OBJECT_ID),\n ],\n });\n },\n extendLockAmount: (veScaKey, scaCoin) => {\n txBlock.moveCall({\n target: `${veScaIds.pkgId}::ve_sca::lock_more_sca`,\n arguments: [\n txBlock.object(veScaIds.config),\n txBlock.object(veScaKey as string),\n txBlock.object(veScaIds.table),\n txBlock.object(veScaIds.treasury),\n typeof scaCoin === 'string' ? txBlock.pure(scaCoin) : (scaCoin as TransactionArgument),\n txBlock.object(SUI_CLOCK_OBJECT_ID),\n ],\n });\n },\n renewExpiredVeSca: (veScaKey, scaCoin, newUnlockAtInSecondTimestamp) => {\n txBlock.moveCall({\n target: `${veScaIds.pkgId}::ve_sca::renew_expired_ve_sca`,\n arguments: [\n txBlock.object(veScaIds.config),\n txBlock.object(veScaKey as string),\n txBlock.object(veScaIds.table),\n txBlock.object(veScaIds.treasury),\n typeof scaCoin === 'string' ? txBlock.pure(scaCoin) : (scaCoin as TransactionArgument),\n txBlock.pure(newUnlockAtInSecondTimestamp),\n txBlock.object(SUI_CLOCK_OBJECT_ID),\n ],\n });\n },\n redeemSca: (veScaKey) =>\n txBlock.moveCall({\n target: `${veScaIds.pkgId}::ve_sca::redeem`,\n arguments: [\n txBlock.object(veScaIds.config),\n txBlock.object(veScaKey as string),\n txBlock.object(veScaIds.table),\n txBlock.object(veScaIds.treasury),\n txBlock.object(SUI_CLOCK_OBJECT_ID),\n ],\n }),\n mintEmptyVeSca: () =>\n txBlock.moveCall({\n target: `${veScaIds.pkgId}::ve_sca::mint_ve_sca_placeholder_key`,\n arguments: [txBlock.object(veScaIds.config), txBlock.object(veScaIds.table)],\n typeArguments: [],\n }),\n };\n};\n\n/**\n * Generate veSCA quick methods.\n *\n * @description\n * The quick methods are the same as the normal methods, but they will automatically\n * help users organize transaction blocks, include get veSca info, and transfer\n * coins to the sender. So, they are all asynchronous methods.\n *\n * @param builder - Scallop builder instance.\n * @param txBlock - TxBlock created by SuiKit .\n * @return veSCA quick methods.\n */\nexport const generateQuickVeScaMethod: GenerateVeScaQuickMethod = async ({ builder, txBlock }) => {\n const normalMethod = await generateNormalVeScaMethod({ builder, txBlock });\n return {\n normalMethod,\n lockScaQuick: async (amountOrCoin, lockPeriodInDays, autoCheck = true) => {\n const sender = requireSender(txBlock);\n const veSca = await requireVeSca(builder, txBlock);\n\n let scaCoin: TransactionObjectArgument | SuiObjectArg | undefined;\n const transferObjects = [];\n if (amountOrCoin !== undefined && typeof amountOrCoin === 'number') {\n const coins = await builder.utils.selectCoinIds(amountOrCoin, SCA_COIN_TYPE, sender);\n const [takeCoin, leftCoin] = builder.utils.takeAmountFromCoins(txBlock, coins, amountOrCoin);\n scaCoin = takeCoin;\n transferObjects.push(leftCoin);\n } else {\n // With amountOrCoin is SuiObjectArg, we cannot validate the minimum sca amount for locking and topup\n scaCoin = amountOrCoin as SuiObjectArg;\n }\n\n const newUnlockAt = builder.utils.getUnlockAt(lockPeriodInDays, veSca?.unlockAt);\n if (autoCheck) {\n checkLockSca(amountOrCoin, lockPeriodInDays, newUnlockAt, veSca?.unlockAt);\n }\n console.log(\n new Date(newUnlockAt * 1000).toLocaleString('en-CA', {\n hour12: true,\n }),\n );\n\n const isInitialLock = !veSca?.unlockAt;\n const isLockExpired = !isInitialLock && veSca.unlockAt * 1000 <= new Date().getTime();\n if (isInitialLock || isLockExpired) {\n if (scaCoin) {\n if (isInitialLock) {\n const veScaKey = normalMethod.lockSca(scaCoin, newUnlockAt);\n transferObjects.push(veScaKey);\n } else {\n // user must withdraw current unlocked SCA first if any\n if (veSca.lockedScaAmount !== 0) {\n const unlockedSca = normalMethod.redeemSca(veSca.keyId);\n transferObjects.push(unlockedSca);\n }\n // enforce renew on expired\n normalMethod.renewExpiredVeSca(veSca.keyId, scaCoin, newUnlockAt);\n }\n }\n } else if (!!scaCoin && !!lockPeriodInDays) {\n normalMethod.extendLockPeriod(veSca.keyId, newUnlockAt);\n normalMethod.extendLockAmount(veSca.keyId, scaCoin);\n } else if (lockPeriodInDays) {\n normalMethod.extendLockPeriod(veSca.keyId, newUnlockAt);\n } else if (scaCoin) {\n normalMethod.extendLockAmount(veSca.keyId, scaCoin);\n }\n\n if (transferObjects.length > 0) {\n txBlock.transferObjects(transferObjects, sender);\n }\n },\n extendLockPeriodQuick: async (lockPeriodInDays: number, veScaKey?: SuiAddressArg, autoCheck = true) => {\n const veSca = await requireVeSca(builder, txBlock, veScaKey);\n\n const newUnlockAt = builder.utils.getUnlockAt(lockPeriodInDays);\n if (autoCheck) {\n checkExtendLockPeriod(lockPeriodInDays, newUnlockAt, veSca?.unlockAt);\n }\n\n if (veSca) {\n normalMethod.extendLockPeriod(veSca.keyId, newUnlockAt);\n }\n },\n extendLockAmountQuick: async (scaAmount: number, veScaKey?: SuiAddressArg, autoCheck = true) => {\n const sender = requireSender(txBlock);\n const veSca = await requireVeSca(builder, txBlock, veScaKey);\n\n if (autoCheck) {\n checkExtendLockAmount(scaAmount, veSca?.unlockAt);\n }\n\n if (veSca) {\n const scaCoins = await builder.utils.selectCoinIds(scaAmount, SCA_COIN_TYPE, sender);\n const [takeCoin, leftCoin] = builder.utils.takeAmountFromCoins(txBlock, scaCoins, scaAmount);\n\n normalMethod.extendLockAmount(veSca.keyId, takeCoin);\n txBlock.transferObjects([leftCoin], sender);\n }\n },\n renewExpiredVeScaQuick: async (\n scaAmount: number,\n lockPeriodInDays: number,\n veScaKey?: SuiAddressArg,\n autoCheck = true,\n ) => {\n const sender = requireSender(txBlock);\n const veSca = await requireVeSca(builder, txBlock, veScaKey);\n\n const newUnlockAt = builder.utils.getUnlockAt(lockPeriodInDays, veSca?.unlockAt);\n if (autoCheck) {\n checkRenewExpiredVeSca(scaAmount, lockPeriodInDays, veSca?.unlockAt);\n }\n\n if (veSca) {\n const transferObjects = [];\n if (veSca.lockedScaAmount !== 0) {\n const unlockedSca = normalMethod.redeemSca(veSca.keyId);\n transferObjects.push(unlockedSca);\n }\n const scaCoins = await builder.utils.selectCoinIds(scaAmount, SCA_COIN_TYPE, sender);\n const [takeCoin, leftCoin] = builder.utils.takeAmountFromCoins(txBlock, scaCoins, scaAmount);\n transferObjects.push(leftCoin);\n\n normalMethod.renewExpiredVeSca(veSca.keyId, takeCoin, newUnlockAt);\n txBlock.transferObjects(transferObjects, sender);\n }\n },\n redeemScaQuick: async (veScaKey?: SuiAddressArg) => {\n const sender = requireSender(txBlock);\n const veSca = await requireVeSca(builder, txBlock, veScaKey);\n\n checkVesca(veSca?.unlockAt);\n\n if (veSca) {\n const sca = normalMethod.redeemSca(veSca.keyId);\n txBlock.transferObjects([sca], sender);\n }\n },\n };\n};\n","import { SuiClient } from '@mysten/sui.js/client';\nimport { TransactionBlock, TransactionObjectInput } from '@mysten/sui.js/transactions';\nimport { normalizeStructTag } from '@mysten/sui.js/utils';\n\n// eslint-disable-next-line import/no-cycle\nimport { DeepBookTxBuilder } from './txbuilder';\nimport { ScallopUtils } from '../../models';\n\ntype ConstructorParams = {\n client: SuiClient;\n currentAddress: string;\n scallopUtils: ScallopUtils;\n accountCap?: string;\n};\n\ntype CoinType = 'sui' | 'wusdc' | 'wusdt' | 'usdc';\ntype SwapParams = {\n tx: TransactionBlock;\n tokenObjectIn: TransactionObjectInput;\n baseCoinName: CoinType;\n quoteCoinName: CoinType;\n};\n\nexport class DeepBookSwap {\n private suiClient: SuiClient;\n\n private scallopUtils: ScallopUtils;\n\n private _clientOrderId = 0;\n\n private _accountCap?: string;\n\n private currentAddress: string;\n\n constructor({ client, currentAddress, accountCap, scallopUtils }: ConstructorParams) {\n this.currentAddress = currentAddress;\n this.suiClient = client;\n this._accountCap = accountCap;\n this.scallopUtils = scallopUtils;\n }\n\n private get clientOrderId() {\n const id = this._clientOrderId;\n this._clientOrderId++;\n return id;\n }\n\n private async accountCap(tx: TransactionBlock) {\n if (this._accountCap) {\n return this._accountCap;\n }\n\n try {\n const { data: accountCapsResponse } = await this.suiClient.getOwnedObjects({\n owner: this.currentAddress,\n filter: {\n StructType: normalizeStructTag('0xdee9::custodian_v2::AccountCap'),\n },\n limit: 1,\n });\n\n if (accountCapsResponse.length === 0 || !accountCapsResponse[0].data) {\n // create new accountCap\n const accountCap = DeepBookTxBuilder.createAccount(tx);\n return accountCap;\n }\n return {\n objectId: accountCapsResponse[0].data.objectId,\n version: accountCapsResponse[0].data.version,\n digest: accountCapsResponse[0].data.digest,\n };\n } catch (e) {\n throw new Error('Failed to create account cap');\n }\n }\n\n public async swapToken({ tokenObjectIn, baseCoinName, quoteCoinName, tx }: SwapParams) {\n const accountCap = await this.accountCap(tx);\n return {\n swapResult: DeepBookTxBuilder.swap(\n tx,\n tokenObjectIn,\n baseCoinName,\n quoteCoinName,\n this.clientOrderId,\n accountCap,\n this.scallopUtils,\n ),\n accountCap,\n };\n }\n}\n","import type { TransactionBlock, TransactionObjectInput, TransactionResult } from '@mysten/sui.js/transactions';\nimport { SUI_CLOCK_OBJECT_ID } from '@mysten/sui.js/utils';\n\nimport { DeepBookContract, DeepBookHelperContract, DeepBookModuleAndMethod, DeepBookPools } from './contract';\n// eslint-disable-next-line import/no-cycle\nimport { ScallopUtils } from '../../models';\n\ntype CoinType = 'sui' | 'wusdc' | 'wusdt' | 'usdc';\n\nconst SUI_CLOCK_OBJECT = {\n objectId: SUI_CLOCK_OBJECT_ID,\n initialSharedVersion: '1',\n mutable: false,\n};\n\nconst getDeepBookPool = (coinAName: CoinType, coinBName: CoinType) => {\n if (coinAName === 'sui') {\n switch (coinBName) {\n case 'wusdc':\n return {\n pool: DeepBookPools.pools.sui2usdc,\n aToB: true,\n };\n default:\n throw new Error(`Invalid coin pair: ${coinAName} and ${coinBName}`);\n }\n } else if (coinAName === 'wusdc') {\n switch (coinBName) {\n case 'sui':\n return {\n pool: DeepBookPools.pools.sui2usdc,\n aToB: false,\n };\n case 'wusdt':\n return {\n pool: DeepBookPools.pools.usdt2usdc,\n aToB: false,\n };\n case 'usdc':\n return {\n pool: DeepBookPools.pools.wusdc2usdc,\n aToB: true,\n };\n default:\n throw new Error(`Invalid coin pair: ${coinAName} and ${coinBName}`);\n }\n } else if (coinAName === 'wusdt') {\n switch (coinBName) {\n case 'wusdc':\n return {\n pool: DeepBookPools.pools.usdt2usdc,\n aToB: true,\n };\n default:\n throw new Error(`Invalid coin pair: ${coinAName} and ${coinBName}`);\n }\n } else {\n throw new Error(`Invalid coin pair: ${coinAName} and ${coinBName}`);\n }\n};\n\nexport const DeepBookTxBuilder = {\n createAccount: (tx: TransactionBlock) =>\n tx.moveCall({\n target: `${DeepBookContract.id}::${DeepBookModuleAndMethod.clob_v2.create_account}`,\n arguments: [],\n typeArguments: [],\n }),\n swap: (\n tx: TransactionBlock,\n tokenInObject: TransactionObjectInput,\n baseCoinName: CoinType,\n quoteCoinName: CoinType,\n clientOrderId: number,\n accountCap: TransactionResult | string | { digest: string; objectId: string; version: string | number | bigint },\n scallopUtils: ScallopUtils,\n ) => {\n // determine the pool\n const { pool, aToB } = getDeepBookPool(baseCoinName, quoteCoinName);\n const coinAType = scallopUtils.parseCoinType(baseCoinName);\n const coinBType = scallopUtils.parseCoinType(quoteCoinName);\n const parsedAccountCap =\n // eslint-disable-next-line no-nested-ternary\n typeof accountCap === 'string'\n ? tx.object(accountCap)\n : 'objectId' in accountCap\n ? tx.objectRef(accountCap)\n : tx.object(accountCap);\n if (!pool) {\n throw new Error(`Deepbook: No pool found for ${baseCoinName} to ${quoteCoinName}`);\n }\n if (aToB) {\n return tx.moveCall({\n target: `${DeepBookHelperContract.id}::deepbook::deepbook_base_for_quote`,\n arguments: [\n tx.sharedObjectRef(pool.object),\n tx.pure(clientOrderId),\n parsedAccountCap,\n tx.object(tokenInObject),\n tx.sharedObjectRef(SUI_CLOCK_OBJECT),\n tx.pure(pool.lotsize),\n ],\n typeArguments: [coinAType, coinBType],\n });\n }\n return tx.moveCall({\n target: `${DeepBookHelperContract.id}::deepbook::deepbook_quote_for_base`,\n arguments: [\n tx.sharedObjectRef(pool.object),\n tx.pure(clientOrderId),\n parsedAccountCap,\n tx.sharedObjectRef(SUI_CLOCK_OBJECT),\n tx.object(tokenInObject),\n tx.pure(pool.lotsize),\n ],\n typeArguments: [coinBType, coinAType],\n });\n },\n};\n","type SharedObjectRef = {\n objectId: string;\n initialSharedVersion: string;\n mutable: boolean;\n};\nexport const DeepBookPools = {\n id: '0x000000000000000000000000000000000000000000000000000000000000dee9',\n pools: {\n sui2usdc: {\n object: {\n objectId: '0x4405b50d791fd3346754e8171aaab6bc2ed26c2c46efdd033c14b30ae507ac33',\n initialSharedVersion: '32079148',\n mutable: true,\n } as SharedObjectRef,\n lotsize: 100000000,\n },\n usdt2usdc: {\n object: {\n objectId: '0xd1f0a9baacc1864ab19534e2d4c5d6c14f2e071a1f075e8e7f9d51f2c17dc238',\n initialSharedVersion: '32079148',\n mutable: true,\n } as SharedObjectRef,\n lotsize: 100000,\n },\n wusdc2usdc: {\n object: {\n objectId: '0x39f2f7c126189b9b5cda6b770ab34031dde22307d19842e95ab576873c77fa14',\n initialSharedVersion: '82838334',\n mutable: true,\n } as SharedObjectRef,\n lotsize: 100000,\n },\n },\n} as const;\n\nexport const DeepBookContract = {\n id: '0x000000000000000000000000000000000000000000000000000000000000dee9',\n};\n\nexport const DeepBookHelperContract = {\n id: '0x2c6c36393db063a9534885d22a47caead720272475336470736be28f119971f3',\n};\n\nexport const DeepBookModuleAndMethod = {\n clob_v2: {\n swap_exact_quote_for_base: 'clob_v2::swap_exact_quote_for_base' as `${string}::${string}`,\n swap_exact_base_for_quote: 'clob_v2::swap_exact_base_for_quote' as `${string}::${string}`,\n create_account: 'clob_v2::create_account' as `${string}::${string}`,\n },\n};\n","import { ScallopAddress } from './scallopAddress';\nimport { ScallopBuilder } from './scallopBuilder';\nimport { ScallopClient } from './scallopClient';\nimport { ScallopQuery } from './scallopQuery';\nimport { ScallopUtils } from './scallopUtils';\nimport { ADDRESSES_ID } from '../constants';\nimport type { ScallopParams } from '../types';\n\n/**\n * @argument params - The parameters for the Scallop instance.\n * @argument cacheOptions - The cache options for the QueryClient.\n *\n * @description\n * The main instance that controls interaction with the Scallop contract.\n *\n * @example\n * ```typescript\n * const sdk = new Scallop(<parameters>);\n * const scallopAddress = await sdk.getScallopAddress();\n * const scallopBuilder = await sdk.createScallopBuilder();\n * const scallopClient = await sdk.createScallopClient();\n * const scallopIndexer= await sdk.createScallopIndexer();\n * const scallopUtils= await sdk.createScallopUtils();\n * ```\n */\nexport class Scallop {\n public params: ScallopParams;\n\n public client: ScallopClient;\n\n public builder: ScallopBuilder;\n\n public query: ScallopQuery;\n\n public utils: ScallopUtils;\n\n public address: ScallopAddress;\n\n public constructor(params: ScallopParams) {\n this.params = params;\n this.address = params.address;\n }\n\n public async init() {\n if (!this.address) {\n this.address = new ScallopAddress({\n id: ADDRESSES_ID,\n });\n }\n await this.address.read();\n this.client = new ScallopClient(this.params, this.address);\n\n const { builder, query, utils } = this.client;\n this.builder = builder;\n this.query = query;\n this.utils = utils;\n }\n}\n","import { TransactionType } from '@msafe/sui3-utils';\nimport { SuiClient } from '@mysten/sui/client';\nimport { Transaction } from '@mysten/sui/transactions';\nimport { IdentifierString, WalletAccount } from '@mysten/wallet-standard';\nimport { LENDING_MARKET_ID, LENDING_MARKET_TYPE, SuilendClient } from 'suilend-sdk';\nimport { phantom } from 'suilend-sdk/_generated/_framework/reified';\nimport { LendingMarket, ObligationOwnerCap } from 'suilend-sdk/_generated/suilend/lending-market/structs';\nimport { Obligation } from 'suilend-sdk/_generated/suilend/obligation/structs';\n\nimport { IAppHelperInternal } from '@/apps/interface/sui';\nimport { SuiNetworks } from '@/types';\n\nimport { Decoder } from './decoder';\nimport { BorrowIntention, BorrowIntentionData } from './intentions/borrow';\nimport { ClaimRewardsIntention, ClaimRewardsIntentionData } from './intentions/claimRewards';\nimport { DepositIntention, DepositIntentionData } from './intentions/deposit';\nimport { RepayIntention, RepayIntentionData } from './intentions/repay';\nimport { WithdrawIntention, WithdrawIntentionData } from './intentions/withdraw';\nimport { TransactionSubType } from './types';\n\nconst getSuilendClient = async (suiClient: SuiClient) =>\n SuilendClient.initializeWithLendingMarket(\n await LendingMarket.fetch(suiClient as any, phantom(LENDING_MARKET_TYPE), LENDING_MARKET_ID),\n suiClient as any,\n );\n\nconst getObligationOwnerCaps = async (suiClient: SuiClient, account: WalletAccount, suilendClient: SuilendClient) =>\n SuilendClient.getObligationOwnerCaps(account.address, suilendClient.lendingMarket.$typeArgs, suiClient as any);\n\nconst getObligations = async (\n suiClient: SuiClient,\n suilendClient: SuilendClient,\n obligationOwnerCaps: ObligationOwnerCap<string>[],\n) =>\n Promise.all(\n obligationOwnerCaps.map((ownerCap) =>\n SuilendClient.getObligation(ownerCap.obligationId, suilendClient.lendingMarket.$typeArgs, suiClient as any),\n ),\n );\n\nexport type SuilendIntention =\n | DepositIntention\n | WithdrawIntention\n | BorrowIntention\n | RepayIntention\n | ClaimRewardsIntention;\n\nexport type SuilendIntentionData =\n | DepositIntentionData\n | WithdrawIntentionData\n | BorrowIntentionData\n | RepayIntentionData\n | ClaimRewardsIntentionData;\n\nexport type IntentionInput = {\n network: SuiNetworks;\n suiClient: SuiClient;\n account: WalletAccount;\n suilendClient: SuilendClient;\n obligationOwnerCaps: ObligationOwnerCap<string>[];\n obligations: Obligation<string>[];\n};\n\nexport class SuilendAppHelper implements IAppHelperInternal<SuilendIntentionData> {\n application = 'Suilend';\n\n supportSDK = '@mysten/sui' as const;\n\n private suilendClient: SuilendClient | undefined;\n\n private obligationOwnerCaps: ObligationOwnerCap<string>[] | undefined;\n\n private obligations: Obligation<string>[] | undefined;\n\n async deserialize(input: {\n transaction: Transaction;\n chain: IdentifierString;\n network: SuiNetworks;\n suiClient: SuiClient;\n account: WalletAccount;\n appContext?: any;\n }): Promise<{ txType: TransactionType; txSubType: string; intentionData: SuilendIntentionData }> {\n const { transaction, suiClient, account } = input;\n\n if (!this.suilendClient) {\n this.suilendClient = await getSuilendClient(suiClient);\n }\n if (!this.obligationOwnerCaps) {\n this.obligationOwnerCaps = await getObligationOwnerCaps(suiClient, account, this.suilendClient);\n }\n if (!this.obligations) {\n this.obligations = await getObligations(suiClient, this.suilendClient, this.obligationOwnerCaps);\n }\n\n const decoder = new Decoder(transaction);\n const result = decoder.decode();\n\n return {\n txType: TransactionType.Other,\n txSubType: result.type,\n intentionData: result.intentionData,\n };\n }\n\n async build(input: {\n network: SuiNetworks;\n txType: TransactionType;\n txSubType: string;\n intentionData: SuilendIntentionData;\n suiClient: SuiClient;\n account: WalletAccount;\n }): Promise<Transaction> {\n const { network, txSubType, intentionData, suiClient, account } = input;\n\n if (!this.suilendClient) {\n this.suilendClient = await getSuilendClient(suiClient);\n }\n if (!this.obligationOwnerCaps) {\n this.obligationOwnerCaps = await getObligationOwnerCaps(suiClient, account, this.suilendClient);\n }\n if (!this.obligations) {\n this.obligations = await getObligations(suiClient, this.suilendClient, this.obligationOwnerCaps);\n }\n\n let intention: SuilendIntention;\n switch (txSubType) {\n case TransactionSubType.DEPOSIT:\n intention = DepositIntention.fromData(intentionData as DepositIntentionData);\n break;\n case TransactionSubType.WITHDRAW:\n intention = WithdrawIntention.fromData(intentionData as WithdrawIntentionData);\n break;\n case TransactionSubType.BORROW:\n intention = BorrowIntention.fromData(intentionData as BorrowIntentionData);\n break;\n case TransactionSubType.REPAY:\n intention = RepayIntention.fromData(intentionData as RepayIntentionData);\n break;\n case TransactionSubType.CLAIM_REWARDS:\n intention = ClaimRewardsIntention.fromData(intentionData as ClaimRewardsIntentionData);\n break;\n default:\n throw new Error('not implemented');\n }\n return intention.build({\n network,\n suiClient,\n account,\n suilendClient: this.suilendClient,\n obligationOwnerCaps: this.obligationOwnerCaps,\n obligations: this.obligations,\n } as IntentionInput);\n }\n}\n","import { TransactionType } from '@msafe/sui3-utils';\nimport { Transaction } from '@mysten/sui/transactions';\n\nimport { SuilendIntentionData } from './helper';\nimport { BorrowIntentionData } from './intentions/borrow';\nimport { DepositIntentionData } from './intentions/deposit';\nimport { RepayIntentionData } from './intentions/repay';\nimport { TransactionSubType } from './types';\n\nconst PACKAGE_ID = '0x93b70b8e21d77f695507558839715d900d05e0ee54acf25d176a179112001d7a';\nconst MODULE = 'lending_market';\n\ntype DecodeResult = {\n txType: TransactionType;\n type: TransactionSubType;\n intentionData: SuilendIntentionData;\n};\n\nexport class Decoder {\n constructor(public readonly transaction: Transaction) {}\n\n decode() {\n if (this.isDepositTransaction()) {\n return this.decodeDeposit();\n }\n if (this.isWithdrawTransaction()) {\n // return this.decodeWithdraw();\n }\n if (this.isBorrowTransaction()) {\n return this.decodeBorrow();\n }\n if (this.isRepayTransaction()) {\n return this.decodeRepay();\n }\n if (this.isClaimRewardsTransaction()) {\n return this.decodeClaimRewards();\n }\n\n throw new Error(`Unknown transaction type`);\n }\n\n private get commands() {\n return this.transaction\n .getData()\n .commands.filter((command) => command.MoveCall.package === PACKAGE_ID && command.MoveCall.module === MODULE);\n }\n\n private getMoveCallCommand(fn: string) {\n return this.commands.find((command) => command.$kind === 'MoveCall' && command.MoveCall.function === fn);\n }\n\n private getSplitCoinsCommands(indexFilter: (index: number) => boolean = () => true) {\n return this.commands.filter((command, index) => command.$kind === 'SplitCoins' && indexFilter(index));\n }\n\n // is*\n private isDepositTransaction() {\n return (\n !!this.getMoveCallCommand('deposit_liquidity_and_mint_ctokens') &&\n !!this.getMoveCallCommand('deposit_ctokens_into_obligation')\n );\n }\n\n private isWithdrawTransaction() {\n return (\n !!this.getMoveCallCommand('withdraw_ctokens') &&\n !!this.getMoveCallCommand('redeem_ctokens_and_withdraw_liquidity')\n );\n }\n\n private isBorrowTransaction() {\n return !!this.getMoveCallCommand('borrow');\n }\n\n private isRepayTransaction() {\n return !!this.getMoveCallCommand('repay');\n }\n\n private isClaimRewardsTransaction() {\n return !!this.getMoveCallCommand('claim_rewards');\n }\n\n // decode*\n private decodeDeposit(): DecodeResult {\n const commands = {\n splitCoins: this.getSplitCoinsCommands()[0],\n deposit_liquidity_and_mint_ctokens: this.getMoveCallCommand('deposit_liquidity_and_mint_ctokens'),\n };\n\n const coinType = commands.deposit_liquidity_and_mint_ctokens.MoveCall.typeArguments[1];\n const value = (commands.splitCoins.SplitCoins.amounts[0] as any).value as string;\n console.log('Decoder.decodeDeposit', coinType, value);\n\n return {\n txType: TransactionType.Other,\n type: TransactionSubType.DEPOSIT,\n intentionData: {\n coinType,\n value,\n } as DepositIntentionData,\n };\n }\n\n // private decodeWithdraw(): DecodeResult {\n // const commands = {\n // withdraw_ctokens: this.getMoveCallCommand('withdraw_ctokens'),\n // };\n // const events = {\n // redeem: this.transactionEvents.find((event) => event.type.endsWith('lending_market::RedeemEvent')),\n // };\n\n // const coinType = commands.withdraw_ctokens.MoveCall.typeArguments[1];\n // const value = (events.redeem.parsedJson as any).liquidity_amount as string;\n // console.log('Decoder.decodeWithdraw', coinType, value);\n\n // return {\n // txType: TransactionType.Other,\n // type: TransactionSubType.WITHDRAW,\n // intentionData: {\n // coinType,\n // value,\n // } as WithdrawIntentionData,\n // };\n // }\n\n private decodeBorrow(): DecodeResult {\n const commands = {\n borrow: this.getMoveCallCommand('borrow'),\n };\n\n const coinType = commands.borrow.MoveCall.typeArguments[1];\n const value = (commands.borrow.MoveCall.arguments[4] as any).value as string;\n console.log('Decoder.decodeBorrow', coinType, value);\n\n return {\n txType: TransactionType.Other,\n type: TransactionSubType.BORROW,\n intentionData: {\n coinType,\n value,\n } as BorrowIntentionData,\n };\n }\n\n private decodeRepay(): DecodeResult {\n const commands = {\n splitCoins: this.getSplitCoinsCommands()[0],\n repay: this.getMoveCallCommand('repay'),\n };\n\n const coinType = commands.repay.MoveCall.typeArguments[1];\n const value = (commands.splitCoins.SplitCoins.amounts[0] as any).value as string;\n console.log('Decoder.decodeRepay', coinType, value);\n\n return {\n txType: TransactionType.Other,\n type: TransactionSubType.REPAY,\n intentionData: {\n coinType,\n value,\n } as RepayIntentionData,\n };\n }\n\n private decodeClaimRewards(): DecodeResult {\n const commands = {\n splitCoins: this.getSplitCoinsCommands()[0],\n repay: this.getMoveCallCommand('repay'),\n };\n\n const coinType = commands.repay.MoveCall.typeArguments[1];\n const value = (commands.splitCoins.SplitCoins.amounts[0] as any).value as string;\n console.log('Decoder.decodeRepay', coinType, value);\n\n return {\n txType: TransactionType.Other,\n type: TransactionSubType.REPAY,\n intentionData: {\n coinType,\n value,\n } as RepayIntentionData,\n };\n }\n}\n","import { TransactionType } from '@msafe/sui3-utils';\nimport { Transaction } from '@mysten/sui/transactions';\n\nimport { TransactionSubType } from '../types';\nimport { SuilendBaseIntention } from './suilendBaseIntention';\nimport { IntentionInput } from '../helper';\n\nexport interface BorrowIntentionData {\n coinType: string;\n value: string;\n}\n\nexport class BorrowIntention extends SuilendBaseIntention<BorrowIntentionData> {\n txType: TransactionType.Other;\n\n txSubType: TransactionSubType.BORROW;\n\n constructor(public readonly data: BorrowIntentionData) {\n super(data);\n }\n\n async build(input: IntentionInput): Promise<Transaction> {\n const { suiClient, account, suilendClient, obligationOwnerCaps, obligations } = input;\n console.log('BorrowIntention.build', suiClient, account, suilendClient, obligationOwnerCaps, obligations);\n\n const transaction = new Transaction();\n await suilendClient.borrowFromObligation(\n account.address,\n obligationOwnerCaps[0].id,\n obligations[0].id,\n this.data.coinType,\n this.data.value,\n transaction as any,\n );\n\n return transaction;\n }\n\n static fromData(data: BorrowIntentionData) {\n console.log('BorrowIntention.fromData', data);\n return new BorrowIntention(data);\n }\n}\n","import { TransactionType } from '@msafe/sui3-utils';\nimport { Transaction } from '@mysten/sui/transactions';\nimport sortKeys from 'sort-keys-recursive';\n\nimport { BaseIntention } from '@/apps/interface/sui';\n\nimport { IntentionInput } from '../helper';\n\nexport abstract class SuilendBaseIntention<D> implements BaseIntention<D> {\n abstract txType: TransactionType;\n\n abstract txSubType: string;\n\n protected constructor(public readonly data: D) {}\n\n abstract build(input: IntentionInput): Promise<Transaction>;\n\n serialize() {\n return JSON.stringify(sortKeys(this.data));\n }\n}\n","import { TransactionType } from '@msafe/sui3-utils';\nimport { Transaction } from '@mysten/sui/transactions';\n\nimport { TransactionSubType } from '../types';\nimport { SuilendBaseIntention } from './suilendBaseIntention';\nimport { IntentionInput } from '../helper';\n\nexport interface ClaimRewardsIntentionData {\n coinType: string;\n value: string;\n}\n\nexport class ClaimRewardsIntention extends SuilendBaseIntention<ClaimRewardsIntentionData> {\n txType: TransactionType.Other;\n\n txSubType: TransactionSubType.CLAIM_REWARDS;\n\n constructor(public readonly data: ClaimRewardsIntentionData) {\n super(data);\n }\n\n async build(input: IntentionInput): Promise<Transaction> {\n const { suiClient, account, suilendClient, obligationOwnerCaps, obligations } = input;\n console.log('ClaimRewardsIntention.build', suiClient, account, suilendClient, obligationOwnerCaps, obligations);\n\n const transaction = new Transaction();\n // await suilendClient.ClaimRewardsFromObligation(\n // account.address,\n // obligationOwnerCaps[0].id,\n // obligations[0].id,\n // this.data.coinType,\n // this.data.value,\n // transaction as any,\n // );\n\n return transaction;\n }\n\n static fromData(data: ClaimRewardsIntentionData) {\n console.log('ClaimRewardsIntention.fromData', data);\n return new ClaimRewardsIntention(data);\n }\n}\n","import { TransactionType } from '@msafe/sui3-utils';\nimport { Transaction } from '@mysten/sui/transactions';\n\nimport { TransactionSubType } from '../types';\nimport { SuilendBaseIntention } from './suilendBaseIntention';\nimport { IntentionInput } from '../helper';\n\nexport interface DepositIntentionData {\n coinType: string;\n value: string;\n}\n\nexport class DepositIntention extends SuilendBaseIntention<DepositIntentionData> {\n txType: TransactionType.Other;\n\n txSubType: TransactionSubType.DEPOSIT;\n\n constructor(public readonly data: DepositIntentionData) {\n super(data);\n }\n\n async build(input: IntentionInput): Promise<Transaction> {\n const { suiClient, account, suilendClient, obligationOwnerCaps } = input;\n console.log('DepositIntention.build', suiClient, account, suilendClient, obligationOwnerCaps);\n\n const transaction = new Transaction();\n await suilendClient.depositIntoObligation(\n account.address,\n this.data.coinType,\n this.data.value,\n transaction as any,\n obligationOwnerCaps[0]?.id,\n );\n\n return transaction;\n }\n\n static fromData(data: DepositIntentionData) {\n console.log('DepositIntention.fromData', data);\n return new DepositIntention(data);\n }\n}\n","import { TransactionType } from '@msafe/sui3-utils';\nimport { Transaction } from '@mysten/sui/transactions';\n\nimport { TransactionSubType } from '../types';\nimport { SuilendBaseIntention } from './suilendBaseIntention';\nimport { IntentionInput } from '../helper';\n\nexport interface RepayIntentionData {\n coinType: string;\n value: string;\n}\n\nexport class RepayIntention extends SuilendBaseIntention<RepayIntentionData> {\n txType: TransactionType.Other;\n\n txSubType: TransactionSubType.REPAY;\n\n constructor(public readonly data: RepayIntentionData) {\n super(data);\n }\n\n async build(input: IntentionInput): Promise<Transaction> {\n const { suiClient, account, suilendClient, obligationOwnerCaps, obligations } = input;\n console.log('RepayIntention.build', suiClient, account, suilendClient, obligationOwnerCaps, obligations);\n\n const transaction = new Transaction();\n await suilendClient.repayIntoObligation(\n account.address,\n obligations[0].id,\n this.data.coinType,\n this.data.value,\n transaction as any,\n );\n\n return transaction;\n }\n\n static fromData(data: RepayIntentionData) {\n console.log('RepayIntention.fromData', data);\n return new RepayIntention(data);\n }\n}\n","import { TransactionType } from '@msafe/sui3-utils';\nimport { Transaction } from '@mysten/sui/transactions';\n\nimport { TransactionSubType } from '../types';\nimport { SuilendBaseIntention } from './suilendBaseIntention';\nimport { IntentionInput } from '../helper';\n\nexport interface WithdrawIntentionData {\n coinType: string;\n value: string;\n}\n\nexport class WithdrawIntention extends SuilendBaseIntention<WithdrawIntentionData> {\n txType: TransactionType.Other;\n\n txSubType: TransactionSubType.WITHDRAW;\n\n constructor(public readonly data: WithdrawIntentionData) {\n super(data);\n }\n\n async build(input: IntentionInput): Promise<Transaction> {\n const { suiClient, account, suilendClient, obligationOwnerCaps, obligations } = input;\n console.log('WithdrawIntention.build', suiClient, account, suilendClient, obligationOwnerCaps, obligations);\n\n const transaction = new Transaction();\n await suilendClient.withdrawFromObligation(\n account.address,\n obligationOwnerCaps[0].id,\n obligations[0].id,\n this.data.coinType,\n this.data.value,\n transaction as any,\n );\n\n return transaction;\n }\n\n static fromData(data: WithdrawIntentionData) {\n console.log('WithdrawIntention.fromData', data);\n return new WithdrawIntention(data);\n }\n}\n","import { TransactionType } from '@msafe/sui3-utils';\nimport { SuiClient } from '@mysten/sui.js/client';\nimport { TransactionBlock } from '@mysten/sui.js/transactions';\nimport { SuiSignTransactionBlockInput, WalletAccount } from '@mysten/wallet-standard';\nimport { Network, TurbosSdk } from 'turbos-clmm-sdk';\n\n// eslint-disable-next-line import/no-cycle\nimport { IAppHelperInternalLegacy } from '@/apps/interface/sui-js';\n\nimport { Decoder } from './decoder';\nimport { AddLiquidityIntention, AddLiquidityIntentionData } from './intentions/add-liquidity';\nimport { BurnIntention, BurnIntentionData } from './intentions/burn';\nimport { CollectFeeIntention, CollectFeeIntentionData } from './intentions/collect-fee';\nimport { CollectRewardIntention, CollectRewardIntentionData } from './intentions/collect-reward';\nimport { CreatePoolIntention, CreatePoolIntentionData } from './intentions/create-pool';\nimport { DecreaseLiquidityIntention, DecreaseLiquidityIntentionData } from './intentions/decrease-liquidity';\nimport { IncreaseLiquidityIntention, IncreaseLiquidityIntentionData } from './intentions/increase-liquidity';\nimport { PrixClaimIntention, PrixClaimIntentionData } from './intentions/prix-claim';\nimport { PrixJoinIntention, PrixJoinIntentionData } from './intentions/prix-join';\nimport { RemoveLiquidityIntention, RemoveLiquidityIntentionData } from './intentions/remove-liquidity';\nimport { SwapIntention, SwapIntentionData } from './intentions/swap';\nimport {\n SwapExactBaseForQuoteIntention,\n SwapExactBaseForQuoteIntentionData,\n} from './intentions/swap-exact-base-for-quote';\nimport {\n SwapExactQuoteForBaseIntention,\n SwapExactQuoteForBaseIntentionData,\n} from './intentions/swap-exact-quote-for-base';\nimport { SuiNetworks, TransactionSubType } from './types';\n\nexport type TURBOSIntention =\n | CreatePoolIntention\n | AddLiquidityIntention\n | IncreaseLiquidityIntention\n | DecreaseLiquidityIntention\n | CollectFeeIntention\n | CollectRewardIntention\n | RemoveLiquidityIntention\n | BurnIntention\n | SwapIntention\n | PrixClaimIntention\n | PrixJoinIntention\n | SwapExactQuoteForBaseIntention\n | SwapExactBaseForQuoteIntention;\n\nexport type TURBOSIntentionData =\n | CreatePoolIntentionData\n | AddLiquidityIntentionData\n | IncreaseLiquidityIntentionData\n | DecreaseLiquidityIntentionData\n | CollectFeeIntentionData\n | CollectRewardIntentionData\n | RemoveLiquidityIntentionData\n | BurnIntentionData\n | SwapIntentionData\n | PrixJoinIntentionData\n | PrixClaimIntentionData\n | SwapExactQuoteForBaseIntentionData\n | SwapExactBaseForQuoteIntentionData;\n\nexport class TURBOSAppHelper implements IAppHelperInternalLegacy<TURBOSIntentionData> {\n application = 'turbos';\n\n supportSDK = '@mysten/sui.js' as const;\n\n async deserialize(\n input: SuiSignTransactionBlockInput & { network: SuiNetworks; suiClient: SuiClient; account: WalletAccount } & {\n action?: string;\n txbParams?: any;\n },\n ): Promise<{\n txType: TransactionType;\n txSubType: TransactionSubType;\n intentionData: TURBOSIntentionData;\n }> {\n const turbosSdk = new TurbosSdk(input.network.replace('sui:', '') as Network, input.suiClient);\n const contract = await turbosSdk.contract.getConfig();\n const { transactionBlock, account } = input;\n console.log(input, 'input');\n const decoder = new Decoder(transactionBlock, turbosSdk, contract);\n const result = await decoder.decode(account.address);\n return {\n txType: TransactionType.Other,\n txSubType: result.type,\n intentionData: result.intentionData,\n };\n }\n\n async build(input: {\n intentionData: TURBOSIntentionData;\n txType: TransactionType;\n txSubType: string;\n suiClient: SuiClient;\n account: WalletAccount;\n network: SuiNetworks;\n }): Promise<TransactionBlock> {\n const { suiClient, account, network } = input;\n let intention: TURBOSIntention;\n console.log(input.intentionData, 'intentionData');\n switch (input.txSubType) {\n case TransactionSubType.CreatePool:\n intention = CreatePoolIntention.fromData(input.intentionData as CreatePoolIntentionData);\n break;\n case TransactionSubType.AddLiquidity:\n intention = AddLiquidityIntention.fromData(input.intentionData as AddLiquidityIntentionData);\n break;\n case TransactionSubType.IncreaseLiquidity:\n intention = IncreaseLiquidityIntention.fromData(input.intentionData as IncreaseLiquidityIntentionData);\n break;\n case TransactionSubType.DecreaseLiquidity:\n intention = DecreaseLiquidityIntention.fromData(input.intentionData as DecreaseLiquidityIntentionData);\n break;\n case TransactionSubType.RemoveLiquidity:\n intention = RemoveLiquidityIntention.fromData(input.intentionData as RemoveLiquidityIntentionData);\n break;\n case TransactionSubType.CollectFee:\n intention = CollectFeeIntention.fromData(input.intentionData as CollectFeeIntentionData);\n break;\n case TransactionSubType.CollectReward:\n intention = CollectRewardIntention.fromData(input.intentionData as CollectRewardIntentionData);\n break;\n case TransactionSubType.Burn:\n intention = BurnIntention.fromData(input.intentionData as BurnIntentionData);\n break;\n case TransactionSubType.Swap:\n intention = SwapIntention.fromData(input.intentionData as SwapIntentionData);\n break;\n case TransactionSubType.PrixJoin:\n intention = PrixJoinIntention.fromData(input.intentionData as PrixJoinIntentionData);\n break;\n case TransactionSubType.PrixClaim:\n intention = PrixClaimIntention.fromData(input.intentionData as PrixClaimIntentionData);\n break;\n case TransactionSubType.SwapExactBaseForQuote:\n intention = SwapExactBaseForQuoteIntention.fromData(input.intentionData as SwapExactBaseForQuoteIntentionData);\n break;\n case TransactionSubType.SwapExactQuoteForBase:\n intention = SwapExactQuoteForBaseIntention.fromData(input.intentionData as SwapExactQuoteForBaseIntentionData);\n break;\n default:\n throw new Error('not implemented');\n }\n return intention.build({ suiClient, account, network });\n }\n}\n","import { TransactionType } from '@msafe/sui3-utils';\nimport { bcs } from '@mysten/sui.js/bcs';\nimport { MoveCallTransaction } from '@mysten/sui.js/dist/cjs/transactions';\nimport { TransactionBlock, TransactionBlockInput } from '@mysten/sui.js/transactions';\nimport { normalizeStructTag, normalizeSuiAddress } from '@mysten/sui.js/utils';\nimport { BN, Contract, TurbosSdk } from 'turbos-clmm-sdk';\n\nimport { deepbookConfig, prixConfig } from './config';\n// eslint-disable-next-line import/no-cycle\nimport { TURBOSIntentionData } from './helper';\nimport { TransactionSubType } from './types';\n\ntype DecodeResult = {\n txType: TransactionType;\n type: TransactionSubType;\n intentionData: TURBOSIntentionData;\n};\n\nconst getAtoB = (layer: 0 | 1, target: string, swap1Layer: string[], swap2Layer: string[]): boolean[] => {\n if (layer === 1) {\n const index = swap2Layer.findIndex((item) => item === target);\n switch (index) {\n case 0:\n return [true, true];\n case 1:\n return [true, false];\n case 2:\n return [false, true];\n case 3:\n return [false, false];\n default:\n throw new Error(`not target: ${target}`);\n }\n }\n const index = swap1Layer.findIndex((item) => item === target);\n switch (index) {\n case 0:\n return [true];\n case 1:\n return [false];\n default:\n throw new Error(`not target: ${target}`);\n }\n};\n\nexport class Decoder {\n constructor(\n public readonly txb: TransactionBlock,\n public readonly turbosSdk: TurbosSdk,\n public readonly config: Contract.Config,\n ) {}\n\n private get transactions() {\n return this.txb.blockData.transactions;\n }\n\n private get swap1Layer() {\n return [`${this.config.PackageId}::swap_router::swap_a_b`, `${this.config.PackageId}::swap_router::swap_b_a`];\n }\n\n private get swap2Layer() {\n return [\n `${this.config.PackageId}::swap_router::swap_a_b_b_c`,\n `${this.config.PackageId}::swap_router::swap_a_b_c_b`,\n `${this.config.PackageId}::swap_router::swap_b_a_b_c`,\n `${this.config.PackageId}::swap_router::swap_b_a_c_b`,\n ];\n }\n\n async decode(address: string) {\n if (this.isSwapTransaction()) {\n return await this.decodeSwap();\n }\n\n if (this.isAddLiquidityTransaction()) {\n return this.decodeAddLiquidity();\n }\n\n if (this.isIncreaseLiquidityTransaction()) {\n return this.decodeIncreaseLiquidity(address);\n }\n\n if (this.isRemoveLiquidityTransaction()) {\n return this.decodeRemoveLiquidity(address);\n }\n\n if (this.isDecreaseLiquidityTransaction()) {\n return this.decodeDecreaseLiquidity(address);\n }\n\n if (this.isCollectFeeTransaction()) {\n return this.decodeCollectFee();\n }\n\n if (this.isCollectRewardTransaction()) {\n return this.decodeCollectReward();\n }\n\n if (this.isBurnTransaction()) {\n return this.decodeBurn();\n }\n\n if (this.isPrixClaimTransaction()) {\n return this.decodePrixClaim();\n }\n\n if (this.isPrixJoinTransaction()) {\n return this.decodePrixJoin();\n }\n\n if (this.isSwapExactBaseForQuoteTransaction()) {\n return this.decodeSwapExactBaseForQuote();\n }\n\n if (this.isSwapExactQuoteForBaseTransaction()) {\n return this.decodeSwapExactQuoteForBase();\n }\n\n throw new Error(`Unknown transaction type`);\n }\n\n private getMoveCallTransaction(target: string) {\n return this.transactions.find((trans) => trans.kind === 'MoveCall' && trans.target === target);\n }\n\n private getMoveCallsTransaction(targets: string[]) {\n return targets.every((target) =>\n this.transactions.find((trans) => trans.kind === 'MoveCall' && trans.target === target),\n );\n }\n\n private getSwapMoveCallTransaction(targets: string[]) {\n return this.transactions.find((trans) => trans.kind === 'MoveCall' && targets.includes(trans.target));\n }\n\n private isSwapTransaction() {\n return !!this.getSwapMoveCallTransaction([...this.swap1Layer, ...this.swap2Layer]);\n }\n\n private isAddLiquidityTransaction() {\n return !!this.getMoveCallTransaction(`${this.config.PackageId}::position_manager::mint`);\n }\n\n private isIncreaseLiquidityTransaction() {\n return !!this.getMoveCallTransaction(`${this.config.PackageId}::position_manager::increase_liquidity`);\n }\n\n private isDecreaseLiquidityTransaction() {\n return !!this.getMoveCallTransaction(`${this.config.PackageId}::position_manager::decrease_liquidity`);\n }\n\n private isCollectFeeTransaction() {\n return !!this.getMoveCallTransaction(`${this.config.PackageId}::position_manager::collect`);\n }\n\n private isCollectRewardTransaction() {\n return !!this.getMoveCallTransaction(`${this.config.PackageId}::position_manager::collect_reward`);\n }\n\n private isBurnTransaction() {\n return !!this.getMoveCallTransaction(`${this.config.PackageId}::position_manager::burn`);\n }\n\n private isPrixJoinTransaction() {\n return !!this.getMoveCallTransaction(`${prixConfig.PackageId}::claim::join`);\n }\n\n private isPrixClaimTransaction() {\n return !!this.getMoveCallTransaction(`${prixConfig.PackageId}::claim::claim`);\n }\n\n private isRemoveLiquidityTransaction() {\n return !!this.getMoveCallsTransaction([\n `${this.config.PackageId}::position_manager::decrease_liquidity`,\n `${this.config.PackageId}::position_manager::burn`,\n ]);\n }\n\n private isSwapExactBaseForQuoteTransaction() {\n return !!this.getMoveCallTransaction(`${deepbookConfig.PackageId}::clob_v2::swap_exact_base_for_quote`);\n }\n\n private isSwapExactQuoteForBaseTransaction() {\n return !!this.getMoveCallTransaction(`${deepbookConfig.PackageId}::clob_v2::swap_exact_quote_for_base`);\n }\n\n private async decodeSwap(): Promise<DecodeResult> {\n const moveCall = this.transactions.find((trans) => trans.kind === 'MoveCall') as MoveCallTransaction;\n let layer: 0 | 1 = 0;\n if (this.swap2Layer.includes(moveCall.target)) {\n layer = 1;\n }\n\n const atob = getAtoB(layer, moveCall.target, this.swap1Layer, this.swap2Layer);\n\n const routes = atob.map((item, index) => {\n const pool = this.helper.decodeSharedObjectId(index);\n const sqrtPrice = this.helper.decodeInputU128(4 + index + layer);\n const nextTickIndex = this.turbosSdk.math.sqrtPriceX64ToTickIndex(new BN(sqrtPrice.toString()));\n\n return {\n pool,\n a2b: item,\n nextTickIndex,\n };\n });\n\n const coinTypeA = atob[0]\n ? moveCall.typeArguments[0]\n : layer === 1\n ? moveCall.typeArguments[0]\n : moveCall.typeArguments[1];\n const coinTypeB =\n layer === 1 ? moveCall.typeArguments[4] : atob[0] ? moveCall.typeArguments[1] : moveCall.typeArguments[0];\n\n const address = this.helper.decodeInputAddress(6 + 2 * layer);\n const deadline = this.helper.decodeInputU64(7 + 2 * layer);\n const amountSpecifiedIsInput = this.helper.decodeInputBool(5 + 2 * layer);\n const amountA = this.helper.decodeInputU64(2 + layer);\n const amountB = this.helper.decodeInputU64(3 + layer);\n\n const result = await this.turbosSdk.trade.computeSwapResultV2({\n pools: [{ pool: routes[0].pool, a2b: routes[0].a2b, amountSpecified: amountA }],\n address,\n amountSpecifiedIsInput,\n });\n\n return {\n txType: TransactionType.Other,\n type: TransactionSubType.Swap,\n intentionData: {\n routes,\n coinTypeA,\n coinTypeB,\n address,\n amountA: amountSpecifiedIsInput ? amountA : amountB,\n amountB: amountSpecifiedIsInput ? amountB : amountA,\n amountSpecifiedIsInput,\n slippage: '0.1',\n deadline,\n },\n };\n }\n\n private decodeAddLiquidity(): DecodeResult {\n console.log(this.helper, 'decodeAddLiquidity this.helper');\n const pool = this.helper.decodeSharedObjectId(0);\n const address = this.helper.decodeInputAddress(12);\n\n const amountA = this.helper.decodeInputU64(8);\n const amountB = this.helper.decodeInputU64(9);\n const tickLower = this.helper.decodeInputU32(4);\n const tickLowerIsNeg = this.helper.decodeInputBool(5);\n const tickUpper = this.helper.decodeInputU32(6);\n const tickUpperIsNeg = this.helper.decodeInputBool(7);\n\n const deadline = this.helper.decodeInputU64(13);\n\n return {\n txType: TransactionType.Other,\n type: TransactionSubType.AddLiquidity,\n intentionData: {\n pool,\n slippage: 10,\n address,\n amountA,\n amountB,\n tickLower: tickLowerIsNeg ? -tickLower : tickLower,\n tickUpper: tickUpperIsNeg ? -tickUpper : tickUpper,\n deadline,\n },\n };\n }\n\n private decodeIncreaseLiquidity(address: string): DecodeResult {\n console.log(this.helper, 'decodeIncreaseLiquidity this.helper');\n\n const pool = this.helper.decodeSharedObjectId(0);\n const nft = this.helper.decodeSharedObjectId(4);\n const amountA = this.helper.decodeInputU64(5);\n const amountB = this.helper.decodeInputU64(6);\n\n const deadline = this.helper.decodeInputU64(9);\n\n return {\n txType: TransactionType.Other,\n type: TransactionSubType.IncreaseLiquidity,\n intentionData: {\n pool,\n slippage: 10,\n address,\n amountA,\n amountB,\n nft,\n deadline,\n },\n };\n }\n\n private decodeDecreaseLiquidity(address: string): DecodeResult {\n console.log(this.helper, 'decodeDecreaseLiquidity this.helper');\n const pool = this.helper.decodeSharedObjectId(0);\n const nft = this.helper.decodeSharedObjectId(2);\n const decreaseLiquidity = this.helper.decodeInputU64(3);\n const amountA = this.helper.decodeInputU64(4);\n const amountB = this.helper.decodeInputU64(5);\n\n const deadline = this.helper.decodeInputU64(6);\n\n return {\n txType: TransactionType.Other,\n type: TransactionSubType.DecreaseLiquidity,\n intentionData: {\n pool,\n decreaseLiquidity,\n nft,\n amountA,\n amountB,\n slippage: 10, // DO NOT use slippage by user setting for now.\n address,\n deadline,\n },\n };\n }\n\n private decodeCollectFee(): DecodeResult {\n console.log(this.helper, 'decodeCollectFee this.helper');\n const pool = this.helper.decodeSharedObjectId(0);\n const nft = this.helper.decodeSharedObjectId(2);\n const address = this.helper.decodeInputAddress(5);\n const collectAmountA = this.helper.decodeInputU64(3);\n const collectAmountB = this.helper.decodeInputU64(4);\n\n const deadline = this.helper.decodeInputU64(6);\n\n return {\n txType: TransactionType.Other,\n type: TransactionSubType.CollectFee,\n intentionData: {\n pool,\n address,\n collectAmountA,\n collectAmountB,\n nft,\n deadline,\n },\n };\n }\n\n private decodeCollectReward(): DecodeResult {\n console.log(this.helper, 'decodeCollectReward this.helper');\n const pool = this.helper.decodeSharedObjectId(0);\n const nft = this.helper.decodeSharedObjectId(2);\n const address = this.helper.decodeInputAddress(6);\n const rewardAmounts = this.collectRewardHelper.map((helper) => helper.decodeInputU64(5));\n\n const deadline = this.helper.decodeInputU64(7);\n\n return {\n txType: TransactionType.Other,\n type: TransactionSubType.CollectReward,\n intentionData: {\n pool,\n address,\n rewardAmounts,\n nft,\n deadline,\n },\n };\n }\n\n private decodeBurn(): DecodeResult {\n console.log(this.helper, 'decodeBurn this.helper');\n const pool = this.helper.decodeSharedObjectId(0);\n const nft = this.helper.decodeSharedObjectId(2);\n\n return {\n txType: TransactionType.Other,\n type: TransactionSubType.Burn,\n intentionData: {\n pool,\n nft,\n },\n };\n }\n\n private decodeRemoveLiquidity(address: string): DecodeResult {\n console.log(this.helper, 'decodeRemoveLiquidity this.helper');\n const pool = this.decreaseLiquidityHelper.decodeSharedObjectId(0);\n const nft = this.decreaseLiquidityHelper.decodeSharedObjectId(2);\n const decreaseLiquidity = this.decreaseLiquidityHelper.decodeInputU64(3);\n const amountA = this.decreaseLiquidityHelper.decodeInputU64(4);\n const amountB = this.decreaseLiquidityHelper.decodeInputU64(5);\n\n const deadline = this.decreaseLiquidityHelper.decodeInputU64(6);\n const rewardAmounts = this.collectRewardHelper.map((helper) => helper.decodeInputU64(5));\n\n const collectAmountA = this.collectFeeHelper.decodeInputU64(3) || 0;\n const collectAmountB = this.collectFeeHelper.decodeInputU64(4) || 0;\n\n return {\n txType: TransactionType.Other,\n type: TransactionSubType.RemoveLiquidity,\n intentionData: {\n pool,\n decreaseLiquidity,\n nft,\n amountA,\n amountB,\n slippage: 10,\n address,\n collectAmountA,\n collectAmountB,\n rewardAmounts,\n deadline,\n },\n };\n }\n\n private decodePrixClaim(): DecodeResult {\n return {\n txType: TransactionType.Other,\n type: TransactionSubType.PrixClaim,\n intentionData: {},\n };\n }\n\n private decodePrixJoin(): DecodeResult {\n return {\n txType: TransactionType.Other,\n type: TransactionSubType.PrixJoin,\n intentionData: {},\n };\n }\n\n private decodeSwapExactBaseForQuote(): DecodeResult {\n const poolId = this.swapExactBaseForQuoteHelper.decodeSharedObjectId(0);\n const amountIn = this.swapExactBaseForQuoteHelper.decodeInputU64(3);\n const token1 = this.swapExactBaseForQuoteHelper.shortTypeArg(0);\n const token2 = this.swapExactBaseForQuoteHelper.shortTypeArg(1);\n return {\n txType: TransactionType.Other,\n type: TransactionSubType.SwapExactBaseForQuote,\n intentionData: {\n poolId,\n amountIn,\n token1,\n token2,\n },\n };\n }\n\n private decodeSwapExactQuoteForBase(): DecodeResult {\n const poolId = this.swapExactQuoteForBaseHelper.decodeSharedObjectId(0);\n const amountIn = this.swapExactQuoteForBaseHelper.decodeInputU64(3);\n const token1 = this.swapExactQuoteForBaseHelper.shortTypeArg(0);\n const token2 = this.swapExactQuoteForBaseHelper.shortTypeArg(1);\n\n return {\n txType: TransactionType.Other,\n type: TransactionSubType.SwapExactQuoteForBase,\n intentionData: {\n poolId,\n amountIn,\n token1,\n token2,\n },\n };\n }\n\n private get helper() {\n const moveCall = this.transactions.find(\n (trans) =>\n trans.kind === 'MoveCall' &&\n trans.target !== '0x2::coin::zero' &&\n trans.target !== '0x0000000000000000000000000000000000000000000000000000000000000002::coin::zero',\n ) as MoveCallTransaction;\n return new MoveCallHelper(moveCall, this.txb);\n }\n\n private get collectRewardHelper() {\n const moveCalls = this.transactions.filter(\n (trans) =>\n trans.kind === 'MoveCall' && trans.target === `${this.config.PackageId}::position_manager::collect_reward`,\n ) as MoveCallTransaction[];\n return moveCalls.map((moveCall) => new MoveCallHelper(moveCall, this.txb));\n }\n\n private get collectFeeHelper() {\n const moveCall = this.transactions.find(\n (trans) => trans.kind === 'MoveCall' && trans.target === `${this.config.PackageId}::position_manager::collect`,\n ) as MoveCallTransaction;\n return new MoveCallHelper(moveCall, this.txb);\n }\n\n private get decreaseLiquidityHelper() {\n const moveCall = this.transactions.find(\n (trans) =>\n trans.kind === 'MoveCall' && trans.target === `${this.config.PackageId}::position_manager::decrease_liquidity`,\n ) as MoveCallTransaction;\n return new MoveCallHelper(moveCall, this.txb);\n }\n\n private get swapExactBaseForQuoteHelper() {\n const moveCall = this.transactions.find(\n (trans) =>\n trans.kind === 'MoveCall' && trans.target === `${deepbookConfig.PackageId}::clob_v2::swap_exact_base_for_quote`,\n ) as MoveCallTransaction;\n return new MoveCallHelper(moveCall, this.txb);\n }\n\n private get swapExactQuoteForBaseHelper() {\n const moveCall = this.transactions.find(\n (trans) =>\n trans.kind === 'MoveCall' && trans.target === `${deepbookConfig.PackageId}::clob_v2::swap_exact_quote_for_base`,\n ) as MoveCallTransaction;\n return new MoveCallHelper(moveCall, this.txb);\n }\n}\n\nexport class MoveCallHelper {\n constructor(\n public readonly moveCall: MoveCallTransaction,\n public readonly txb: TransactionBlock,\n ) {}\n\n decodeSharedObjectId(argIndex: number) {\n const input = this.getInputParam(argIndex);\n return MoveCallHelper.getSharedObjectId(input);\n }\n\n decodeOwnedObjectId(argIndex: number) {\n const input = this.getInputParam(argIndex);\n return MoveCallHelper.getOwnedObjectId(input);\n }\n\n decodeInputU128(argIndex: number) {\n const strVal = this.decodePureArg<string>(argIndex, 'u128');\n return Number(strVal);\n }\n\n decodeInputU64(argIndex: number) {\n const strVal = this.decodePureArg<string>(argIndex, 'u64');\n return Number(strVal);\n }\n\n decodeInputU32(argIndex: number) {\n const strVal = this.decodePureArg<string>(argIndex, 'u32');\n return Number(strVal);\n }\n\n decodeInputU8(argIndex: number) {\n const strVal = this.decodePureArg<string>(argIndex, 'u8');\n return Number(strVal);\n }\n\n decodeInputAddress(argIndex: number) {\n const input = this.decodePureArg<string>(argIndex, 'address');\n return normalizeSuiAddress(input);\n }\n\n decodeInputString(argIndex: number) {\n return this.decodePureArg<string>(argIndex, 'string');\n }\n\n decodeInputBool(argIndex: number) {\n return this.decodePureArg<boolean>(argIndex, 'bool');\n }\n\n decodePureArg<T>(argIndex: number, bcsType: string) {\n const input = this.getInputParam(argIndex);\n return MoveCallHelper.getPureInputValue<T>(input, bcsType);\n }\n\n getInputParam(argIndex: number) {\n const arg = this.moveCall.arguments[argIndex];\n if (arg.kind !== 'Input') {\n throw new Error('not input type');\n }\n return this.txb.blockData.inputs[arg.index];\n }\n\n static getPureInputValue<T>(input: TransactionBlockInput, bcsType: string) {\n if (input.type !== 'pure') {\n throw new Error('not pure argument');\n }\n if (typeof input.value === 'object' && 'Pure' in input.value) {\n const bcsNums = input.value.Pure;\n return bcs.de(bcsType, new Uint8Array(bcsNums)) as T;\n }\n return input.value as T;\n }\n\n static getOwnedObjectId(input: TransactionBlockInput) {\n if (input.type !== 'object') {\n throw new Error(`not object argument: ${JSON.stringify(input)}`);\n }\n if (typeof input.value === 'object') {\n if (!('Object' in input.value) || !('ImmOrOwned' in input.value.Object)) {\n throw new Error('not ImmOrOwned');\n }\n return normalizeSuiAddress(input.value.Object.ImmOrOwned.objectId as string);\n }\n return normalizeSuiAddress(input.value as string);\n }\n\n static getSharedObjectId(input: TransactionBlockInput) {\n if (input.type !== 'object') {\n throw new Error(`not object argument: ${JSON.stringify(input)}`);\n }\n if (typeof input.value !== 'object') {\n return normalizeSuiAddress(input.value as string);\n }\n if (!('Object' in input.value) || !('Shared' in input.value.Object)) {\n throw new Error('not Shared');\n }\n return normalizeSuiAddress(input.value.Object.Shared.objectId as string);\n }\n\n static getPureInput<T>(input: TransactionBlockInput, bcsType: string) {\n if (input.type !== 'pure') {\n throw new Error('not pure argument');\n }\n if (typeof input.value !== 'object') {\n return input.value as T;\n }\n if (!('Pure' in input.value)) {\n throw new Error('Pure not in value');\n }\n const bcsVal = input.value.Pure;\n return bcs.de(bcsType, new Uint8Array(bcsVal)) as T;\n }\n\n typeArg(index: number) {\n return normalizeStructTag(this.moveCall.typeArguments[index]);\n }\n\n shortTypeArg(index: number) {\n return this.moveCall.typeArguments[index];\n }\n\n txArg(index: number) {\n return this.moveCall.arguments[index];\n }\n}\n","export const prixConfig = {\n PackageId: '0x02fe4933f4521250e55a15441096d1d4a38a7311195b0bca126fc0138c1f5a97',\n Claim: '0x0c822cec42f7ca703696b4232f1c47b348330c23580172a29aab465bc071d894',\n turbosCoinType: '0x5d1f47ea69bb0de31c313d7acf89b890dbb8991ea8e03c6c355171f84bb1ba4a::turbos::TURBOS',\n};\n\nexport const deepbookConfig = {\n PackageId: '0xdee9',\n};\n","import { TransactionType } from '@msafe/sui3-utils';\nimport { SuiClient } from '@mysten/sui.js/client';\nimport { TransactionBlock } from '@mysten/sui.js/transactions';\nimport { WalletAccount } from '@mysten/wallet-standard';\nimport { Pool, TurbosSdk, Network } from 'turbos-clmm-sdk';\n\nimport { BaseIntentionLegacy } from '@/apps/interface/sui-js';\n\nimport { SuiNetworks, TransactionSubType } from '../types';\n\nexport type AddLiquidityIntentionData = Pool.AddLiquidityOptions;\n\nexport class AddLiquidityIntention extends BaseIntentionLegacy<AddLiquidityIntentionData> {\n txType!: TransactionType.Other;\n\n txSubType!: TransactionSubType.AddLiquidity;\n\n constructor(public override readonly data: AddLiquidityIntentionData) {\n super(data);\n }\n\n async build(input: {\n suiClient: SuiClient;\n account: WalletAccount;\n network: SuiNetworks;\n }): Promise<TransactionBlock> {\n const turbosSdk = new TurbosSdk(input.network.replace('sui:', '') as Network, input.suiClient);\n const { pool, address, amountA, amountB, slippage, tickLower, tickUpper, deadline, txb } = this.data;\n\n return turbosSdk.pool.addLiquidity({\n pool,\n slippage,\n address,\n amountA,\n amountB,\n tickLower,\n tickUpper,\n deadline,\n txb,\n });\n }\n\n static fromData(data: AddLiquidityIntentionData) {\n return new AddLiquidityIntention(data);\n }\n}\n","import { TransactionType } from '@msafe/sui3-utils';\nimport { SuiClient } from '@mysten/sui.js/client';\nimport { TransactionBlock } from '@mysten/sui.js/transactions';\nimport { WalletAccount } from '@mysten/wallet-standard';\nimport { NFT, TurbosSdk, Network } from 'turbos-clmm-sdk';\n\nimport { BaseIntentionLegacy } from '@/apps/interface/sui-js';\n\nimport { SuiNetworks, TransactionSubType } from '../types';\n\nexport type BurnIntentionData = NFT.BurnOptions;\n\nexport class BurnIntention extends BaseIntentionLegacy<BurnIntentionData> {\n txType!: TransactionType.Other;\n\n txSubType!: TransactionSubType.AddLiquidity;\n\n constructor(public override readonly data: BurnIntentionData) {\n super(data);\n }\n\n async build(input: {\n suiClient: SuiClient;\n account: WalletAccount;\n network: SuiNetworks;\n }): Promise<TransactionBlock> {\n const turbosSdk = new TurbosSdk(input.network.replace('sui:', '') as Network, input.suiClient);\n const { pool, nft, txb } = this.data;\n\n return turbosSdk.nft.burn({\n pool,\n nft,\n txb,\n });\n }\n\n static fromData(data: BurnIntentionData) {\n return new BurnIntention(data);\n }\n}\n","import { TransactionType } from '@msafe/sui3-utils';\nimport { SuiClient } from '@mysten/sui.js/client';\nimport { TransactionBlock } from '@mysten/sui.js/transactions';\nimport { WalletAccount } from '@mysten/wallet-standard';\nimport { Network, Pool, TurbosSdk } from 'turbos-clmm-sdk';\n\nimport { BaseIntentionLegacy } from '@/apps/interface/sui-js';\n\nimport { SuiNetworks, TransactionSubType } from '../types';\n\nexport type CollectFeeIntentionData = Pool.CollectFeeOptions;\n\nexport class CollectFeeIntention extends BaseIntentionLegacy<CollectFeeIntentionData> {\n txType!: TransactionType.Other;\n\n txSubType!: TransactionSubType.AddLiquidity;\n\n constructor(public override readonly data: CollectFeeIntentionData) {\n super(data);\n }\n\n async build(input: {\n suiClient: SuiClient;\n account: WalletAccount;\n network: SuiNetworks;\n }): Promise<TransactionBlock> {\n const turbosSdk = new TurbosSdk(input.network.replace('sui:', '') as Network, input.suiClient);\n const { pool, address, nft, collectAmountA, collectAmountB, deadline, txb } = this.data;\n\n return turbosSdk.pool.collectFee({\n pool,\n address,\n collectAmountA,\n collectAmountB,\n nft,\n deadline,\n txb,\n });\n }\n\n static fromData(data: CollectFeeIntentionData) {\n return new CollectFeeIntention(data);\n }\n}\n","import { TransactionType } from '@msafe/sui3-utils';\nimport { SuiClient } from '@mysten/sui.js/client';\nimport { TransactionBlock } from '@mysten/sui.js/transactions';\nimport { WalletAccount } from '@mysten/wallet-standard';\nimport { Network, Pool, TurbosSdk } from 'turbos-clmm-sdk';\n\nimport { BaseIntentionLegacy } from '@/apps/interface/sui-js';\n\nimport { SuiNetworks, TransactionSubType } from '../types';\n\nexport type CollectRewardIntentionData = Pool.CollectRewardOptions;\n\nexport class CollectRewardIntention extends BaseIntentionLegacy<CollectRewardIntentionData> {\n txType!: TransactionType.Other;\n\n txSubType!: TransactionSubType.AddLiquidity;\n\n constructor(public override readonly data: CollectRewardIntentionData) {\n super(data);\n }\n\n async build(input: {\n suiClient: SuiClient;\n account: WalletAccount;\n network: SuiNetworks;\n }): Promise<TransactionBlock> {\n const turbosSdk = new TurbosSdk(input.network.replace('sui:', '') as Network, input.suiClient);\n const { pool, address, nft, rewardAmounts, deadline, txb } = this.data;\n\n return turbosSdk.pool.collectReward({\n pool,\n address,\n rewardAmounts,\n nft,\n deadline,\n txb,\n });\n }\n\n static fromData(data: CollectRewardIntentionData) {\n return new CollectRewardIntention(data);\n }\n}\n","import { TransactionType } from '@msafe/sui3-utils';\nimport { SuiClient } from '@mysten/sui.js/client';\nimport { TransactionBlock } from '@mysten/sui.js/transactions';\nimport { WalletAccount } from '@mysten/wallet-standard';\nimport { Network, Pool, TurbosSdk } from 'turbos-clmm-sdk';\n\nimport { BaseIntentionLegacy } from '@/apps/interface/sui-js';\n\nimport { SuiNetworks, TransactionSubType } from '../types';\n\nexport type CreatePoolIntentionData = Pool.CreatePoolOptions;\n\nexport class CreatePoolIntention extends BaseIntentionLegacy<CreatePoolIntentionData> {\n txType!: TransactionType.Other;\n\n txSubType!: TransactionSubType.AddLiquidity;\n\n constructor(public override readonly data: CreatePoolIntentionData) {\n super(data);\n }\n\n async build(input: {\n suiClient: SuiClient;\n account: WalletAccount;\n network: SuiNetworks;\n }): Promise<TransactionBlock> {\n const turbosSdk = new TurbosSdk(input.network.replace('sui:', '') as Network, input.suiClient);\n const {\n fee,\n address,\n tickLower,\n tickUpper,\n sqrtPrice,\n slippage,\n coinTypeA,\n coinTypeB,\n amountA,\n amountB,\n deadline,\n txb,\n } = this.data;\n\n return turbosSdk.pool.createPool({\n fee,\n amountA,\n amountB,\n address,\n tickLower,\n tickUpper,\n sqrtPrice,\n slippage,\n coinTypeA,\n coinTypeB,\n deadline,\n txb,\n });\n }\n\n static fromData(data: CreatePoolIntentionData) {\n return new CreatePoolIntention(data);\n }\n}\n","import { TransactionType } from '@msafe/sui3-utils';\nimport { SuiClient } from '@mysten/sui.js/client';\nimport { TransactionBlock } from '@mysten/sui.js/transactions';\nimport { WalletAccount } from '@mysten/wallet-standard';\nimport { Pool, TurbosSdk, Network } from 'turbos-clmm-sdk';\n\nimport { BaseIntentionLegacy } from '@/apps/interface/sui-js';\n\nimport { SuiNetworks, TransactionSubType } from '../types';\n\nexport type DecreaseLiquidityIntentionData = Pool.DecreaseLiquidityOptions;\n\nexport class DecreaseLiquidityIntention extends BaseIntentionLegacy<DecreaseLiquidityIntentionData> {\n txType!: TransactionType.Other;\n\n txSubType!: TransactionSubType.AddLiquidity;\n\n constructor(public override readonly data: DecreaseLiquidityIntentionData) {\n super(data);\n }\n\n async build(input: {\n suiClient: SuiClient;\n account: WalletAccount;\n network: SuiNetworks;\n }): Promise<TransactionBlock> {\n const turbosSdk = new TurbosSdk(input.network.replace('sui:', '') as Network, input.suiClient);\n const { pool, address, amountA, amountB, slippage, nft, decreaseLiquidity, deadline, txb } = this.data;\n\n return turbosSdk.pool.decreaseLiquidity({\n pool,\n slippage,\n address,\n amountA,\n amountB,\n nft,\n decreaseLiquidity,\n deadline,\n txb,\n });\n }\n\n static fromData(data: DecreaseLiquidityIntentionData) {\n return new DecreaseLiquidityIntention(data);\n }\n}\n","import { TransactionType } from '@msafe/sui3-utils';\nimport { SuiClient } from '@mysten/sui.js/client';\nimport { TransactionBlock } from '@mysten/sui.js/transactions';\nimport { WalletAccount } from '@mysten/wallet-standard';\nimport { Pool, TurbosSdk, Network } from 'turbos-clmm-sdk';\n\nimport { BaseIntentionLegacy } from '@/apps/interface/sui-js';\n\nimport { SuiNetworks, TransactionSubType } from '../types';\n\nexport type IncreaseLiquidityIntentionData = Pool.IncreaseLiquidityOptions;\n\nexport class IncreaseLiquidityIntention extends BaseIntentionLegacy<IncreaseLiquidityIntentionData> {\n txType!: TransactionType.Other;\n\n txSubType!: TransactionSubType.AddLiquidity;\n\n constructor(public override readonly data: IncreaseLiquidityIntentionData) {\n super(data);\n }\n\n async build(input: {\n suiClient: SuiClient;\n account: WalletAccount;\n network: SuiNetworks;\n }): Promise<TransactionBlock> {\n const turbosSdk = new TurbosSdk(input.network.replace('sui:', '') as Network, input.suiClient);\n const { pool, address, amountA, amountB, slippage, nft, deadline, txb } = this.data;\n\n return turbosSdk.pool.increaseLiquidity({\n pool,\n slippage,\n address,\n amountA,\n amountB,\n nft,\n deadline,\n txb,\n });\n }\n\n static fromData(data: IncreaseLiquidityIntentionData) {\n return new IncreaseLiquidityIntention(data);\n }\n}\n","import { TransactionType } from '@msafe/sui3-utils';\nimport { SuiClient } from '@mysten/sui.js/client';\nimport { TransactionBlock } from '@mysten/sui.js/transactions';\nimport { SUI_CLOCK_OBJECT_ID } from '@mysten/sui.js/utils';\nimport { WalletAccount } from '@mysten/wallet-standard';\n\nimport { BaseIntentionLegacy } from '@/apps/interface/sui-js';\n\nimport { prixConfig } from '../config';\nimport { SuiNetworks, TransactionSubType } from '../types';\n\nexport interface PrixClaimIntentionData {}\n\nexport class PrixClaimIntention extends BaseIntentionLegacy<PrixClaimIntentionData> {\n txType!: TransactionType.Other;\n\n txSubType!: TransactionSubType.PrixClaim;\n\n constructor(public override readonly data: PrixClaimIntentionData) {\n super(data);\n }\n\n async build(input: {\n suiClient: SuiClient;\n account: WalletAccount;\n network: SuiNetworks;\n }): Promise<TransactionBlock> {\n const txb = new TransactionBlock();\n txb.moveCall({\n target: `${prixConfig.PackageId}::claim::claim`,\n typeArguments: [prixConfig.turbosCoinType],\n arguments: [txb.object(prixConfig.Claim), txb.object(SUI_CLOCK_OBJECT_ID)],\n });\n return txb;\n }\n\n static fromData(data: PrixClaimIntentionData) {\n return new PrixClaimIntention(data);\n }\n}\n","import { TransactionType } from '@msafe/sui3-utils';\nimport { SuiClient } from '@mysten/sui.js/client';\nimport { TransactionBlock } from '@mysten/sui.js/transactions';\nimport { WalletAccount } from '@mysten/wallet-standard';\n\nimport { BaseIntentionLegacy } from '@/apps/interface/sui-js';\n\nimport { prixConfig } from '../config';\nimport { SuiNetworks, TransactionSubType } from '../types';\n\nexport interface PrixJoinIntentionData {}\n\nexport class PrixJoinIntention extends BaseIntentionLegacy<PrixJoinIntentionData> {\n txType!: TransactionType.Other;\n\n txSubType!: TransactionSubType.PrixJoin;\n\n constructor(public override readonly data: PrixJoinIntentionData) {\n super(data);\n }\n\n async build(input: {\n suiClient: SuiClient;\n account: WalletAccount;\n network: SuiNetworks;\n }): Promise<TransactionBlock> {\n const txb = new TransactionBlock();\n txb.moveCall({\n target: `${prixConfig.PackageId}::claim::join`,\n typeArguments: [prixConfig.turbosCoinType],\n arguments: [txb.object(prixConfig.Claim)],\n });\n return txb;\n }\n\n static fromData(data: PrixJoinIntentionData) {\n return new PrixJoinIntention(data);\n }\n}\n","import { TransactionType } from '@msafe/sui3-utils';\nimport { SuiClient } from '@mysten/sui.js/client';\nimport { TransactionBlock } from '@mysten/sui.js/transactions';\nimport { WalletAccount } from '@mysten/wallet-standard';\nimport { Pool, TurbosSdk, Network } from 'turbos-clmm-sdk';\n\nimport { BaseIntentionLegacy } from '@/apps/interface/sui-js';\n\nimport { SuiNetworks, TransactionSubType } from '../types';\n\nexport type RemoveLiquidityIntentionData = Pool.RemoveLiquidityOptions;\n\nexport class RemoveLiquidityIntention extends BaseIntentionLegacy<RemoveLiquidityIntentionData> {\n txType!: TransactionType.Other;\n\n txSubType!: TransactionSubType.AddLiquidity;\n\n constructor(public override readonly data: RemoveLiquidityIntentionData) {\n super(data);\n }\n\n async build(input: {\n suiClient: SuiClient;\n account: WalletAccount;\n network: SuiNetworks;\n }): Promise<TransactionBlock> {\n const turbosSdk = new TurbosSdk(input.network.replace('sui:', '') as Network, input.suiClient);\n let txb = new TransactionBlock();\n txb = await turbosSdk.pool.collectFee({ txb, ...this.data });\n txb = await turbosSdk.pool.collectReward({ txb, ...this.data });\n txb = await turbosSdk.pool.decreaseLiquidity({ txb, ...this.data });\n txb = await turbosSdk.nft.burn({ txb, nft: this.data.nft, pool: this.data.pool });\n return txb;\n }\n\n static fromData(data: RemoveLiquidityIntentionData) {\n return new RemoveLiquidityIntention(data);\n }\n}\n","import { TransactionType } from '@msafe/sui3-utils';\nimport { SuiClient } from '@mysten/sui.js/client';\nimport { TransactionBlock } from '@mysten/sui.js/transactions';\nimport { WalletAccount } from '@mysten/wallet-standard';\nimport { Trade, TurbosSdk, Network } from 'turbos-clmm-sdk';\n\nimport { BaseIntentionLegacy } from '@/apps/interface/sui-js';\n\nimport { SuiNetworks, TransactionSubType } from '../types';\n\nexport type SwapIntentionData = Trade.SwapOptions;\n\nexport class SwapIntention extends BaseIntentionLegacy<SwapIntentionData> {\n txType!: TransactionType.Other;\n\n txSubType!: TransactionSubType.AddLiquidity;\n\n constructor(public override readonly data: SwapIntentionData) {\n super(data);\n }\n\n async build(input: {\n suiClient: SuiClient;\n account: WalletAccount;\n network: SuiNetworks;\n }): Promise<TransactionBlock> {\n console.log(this.data, 'this.data');\n const turbosSdk = new TurbosSdk(input.network.replace('sui:', '') as Network, input.suiClient);\n const { routes, coinTypeA, coinTypeB, address, amountA, amountB, slippage, amountSpecifiedIsInput, deadline, txb } =\n this.data;\n return turbosSdk.trade.swap({\n routes,\n coinTypeA,\n coinTypeB,\n address,\n amountA,\n amountB,\n amountSpecifiedIsInput,\n slippage,\n deadline,\n txb,\n });\n }\n\n static fromData(data: SwapIntentionData) {\n return new SwapIntention(data);\n }\n}\n","import { TransactionType } from '@msafe/sui3-utils';\nimport { SuiClient } from '@mysten/sui.js/client';\nimport { TransactionBlock } from '@mysten/sui.js/transactions';\nimport { WalletAccount } from '@mysten/wallet-standard';\nimport { TurbosSdk, Network } from 'turbos-clmm-sdk';\n\nimport { BaseIntentionLegacy } from '@/apps/interface/sui-js';\n\nimport { swap_exact_base_for_quote } from '../api/deepbook';\nimport { SuiNetworks, TransactionSubType } from '../types';\n\nexport interface SwapExactBaseForQuoteIntentionData {\n token1: string;\n token2: string;\n poolId: string;\n amountIn: number;\n}\n\nexport class SwapExactBaseForQuoteIntention extends BaseIntentionLegacy<SwapExactBaseForQuoteIntentionData> {\n txType!: TransactionType.Other;\n\n txSubType!: TransactionSubType.SwapExactBaseForQuote;\n\n constructor(public override readonly data: SwapExactBaseForQuoteIntentionData) {\n super(data);\n }\n\n async build(input: {\n suiClient: SuiClient;\n account: WalletAccount;\n network: SuiNetworks;\n }): Promise<TransactionBlock> {\n const turbosSdk = new TurbosSdk(input.network.replace('sui:', '') as Network, input.suiClient);\n const txb = await swap_exact_base_for_quote({ ...this.data, turbosSdk, currentAddress: input.account.address });\n return txb;\n }\n\n static fromData(data: SwapExactBaseForQuoteIntentionData) {\n return new SwapExactBaseForQuoteIntention(data);\n }\n}\n","import { normalizeSuiObjectId } from '@mysten/sui.js/utils';\nimport { TransactionBlock, TransactionObjectArgument } from '@mysten/sui.js/transactions';\nimport { deepbookConfig } from '../config';\nimport { TurbosSdk } from 'turbos-clmm-sdk';\nimport { SuiKit } from '../utils/sui-kit';\n\nconst client_order_id = 89;\nconst gasBudget = 1_000_000;\n\ninterface SwapExactOptions {\n token1: string;\n token2: string;\n poolId: string;\n amountIn: number;\n turbosSdk: TurbosSdk;\n currentAddress: string;\n}\n\nexport const swap_exact_quote_for_base = async (options: SwapExactOptions) => {\n const { token1, token2, poolId, amountIn, currentAddress, turbosSdk } = options;\n let txb = new TransactionBlock();\n\n const suiKit = new SuiKit(turbosSdk);\n // get token objectId\n const coinsData = await suiKit.getCoinsData(currentAddress, token2, amountIn);\n const [sendCoin, mergeCoin] = suiKit.splitAndMergeCoin(coinsData, amountIn, txb);\n if (!sendCoin) {\n throw new Error(`Not enough balance: ${token2}`);\n }\n\n // get accountCap id\n const currentAccountCap = await suiKit.IsAccountCap(currentAddress);\n const accountCap = !currentAccountCap ? suiKit.createAccount(txb) : txb.object(currentAccountCap);\n\n const [base_coin_ret, quote_coin_ret, _amount] = txb.moveCall({\n typeArguments: [token1, token2],\n target: `${deepbookConfig.PackageId}::clob_v2::swap_exact_quote_for_base`,\n arguments: [\n txb.object(String(poolId)),\n txb.pure(client_order_id),\n accountCap,\n txb.pure(amountIn),\n txb.object(normalizeSuiObjectId('0x6')),\n sendCoin,\n ],\n });\n\n if (mergeCoin) {\n txb.transferObjects([mergeCoin], txb.pure(currentAddress));\n }\n\n txb.transferObjects([base_coin_ret!], txb.pure(currentAddress));\n txb.transferObjects([quote_coin_ret!], txb.pure(currentAddress));\n\n if (!currentAccountCap) {\n txb.transferObjects([accountCap], txb.pure(currentAddress));\n }\n\n txb.setSenderIfNotSet(currentAddress);\n txb.setGasBudget(gasBudget);\n\n return txb;\n};\n\nexport const swap_exact_base_for_quote = async (options: SwapExactOptions) => {\n const { token1, token2, poolId, amountIn, currentAddress, turbosSdk } = options;\n let txb = new TransactionBlock();\n\n const suiKit = new SuiKit(turbosSdk);\n // get token objectId\n const coinsData = await suiKit.getCoinsData(currentAddress, token1, amountIn);\n const [sendCoin, mergeCoin] = suiKit.splitAndMergeCoin(coinsData, amountIn, txb);\n\n if (!sendCoin) {\n throw new Error(`Not enough balance: ${token1}`);\n }\n\n // get accountCap id\n const currentAccountCap = await suiKit.IsAccountCap(currentAddress);\n const accountCap = !currentAccountCap ? suiKit.createAccount(txb) : txb.object(currentAccountCap);\n\n const zero = suiKit.zero(token2, txb);\n\n const [base_coin_ret, quote_coin_ret, _amount] = txb.moveCall({\n typeArguments: [token1, token2],\n target: `${deepbookConfig.PackageId}::clob_v2::swap_exact_base_for_quote`,\n arguments: [\n txb.object(String(poolId)),\n txb.pure(client_order_id),\n accountCap,\n txb.pure(amountIn),\n sendCoin,\n zero,\n txb.object(normalizeSuiObjectId('0x6')),\n ],\n });\n if (mergeCoin) {\n txb.transferObjects([mergeCoin], txb.pure(currentAddress));\n }\n\n txb.transferObjects([base_coin_ret!], txb.pure(currentAddress));\n txb.transferObjects([quote_coin_ret!], txb.pure(currentAddress));\n\n if (!currentAccountCap) {\n txb.transferObjects([accountCap], txb.pure(currentAddress));\n }\n\n txb.setSenderIfNotSet(currentAddress);\n txb.setGasBudget(gasBudget);\n\n return txb;\n};\n","import { PaginatedCoins } from '@mysten/sui.js/client';\nimport { TransactionBlock, TransactionObjectArgument } from '@mysten/sui.js/transactions';\nimport { TurbosSdk, unstable_getObjectId } from 'turbos-clmm-sdk';\nimport { deepbookConfig } from '../config';\n\ntype CoinData = PaginatedCoins['data'];\n\nexport class SuiKit {\n constructor(public readonly turbosSdk: TurbosSdk) {}\n\n async getCoinsData(currentAddress: string, type: string, amount: number): Promise<CoinData> {\n const coinObjects: CoinData = [];\n let coinFields: PaginatedCoins | undefined;\n do {\n coinFields = await this.turbosSdk.provider.getCoins({\n owner: currentAddress,\n coinType: type,\n cursor: coinFields?.nextCursor,\n });\n coinObjects.push(...coinFields.data);\n } while (coinFields.hasNextPage);\n\n const resultCoinObjects: CoinData = [];\n let currentBalance = 0;\n coinObjects\n .sort((coinA, coinB) => Number(coinB.balance) - Number(coinA.balance))\n .some((object) => {\n if (currentBalance >= amount) {\n return true;\n } else {\n currentBalance += Number(object.balance);\n resultCoinObjects.push(object);\n return false;\n }\n });\n return resultCoinObjects;\n }\n\n splitAndMergeCoin(\n coins: CoinData | undefined,\n amount: number,\n txb: TransactionBlock,\n ): [TransactionObjectArgument | undefined, TransactionObjectArgument | undefined] {\n if (!coins || coins.length < 1) {\n return [undefined, undefined];\n }\n\n if (this.isSuiCoinAddress(coins[0]!.coinType)) {\n const [sendCoin] = txb.splitCoins(txb.gas, [txb.pure(amount)]);\n return [sendCoin, undefined];\n }\n\n const mergeCoin = txb.object(coins[0]!.coinObjectId);\n if (coins.length > 1) {\n txb.mergeCoins(\n mergeCoin,\n coins.slice(1).map((coin) => txb.object(coin.coinObjectId)),\n );\n }\n\n const [sendCoin] = txb.splitCoins(mergeCoin, [txb.pure(amount)]);\n return [sendCoin, mergeCoin];\n }\n\n isSuiCoinAddress(type: string) {\n return type.toLocaleLowerCase() === '0x2::sui::sui';\n }\n\n async IsAccountCap(currentAddress: string): Promise<string | undefined> {\n const dynamicFields = await this.turbosSdk.provider.getOwnedObjects({\n owner: currentAddress,\n options: { showContent: true, showType: true, showOwner: true },\n filter: {\n StructType: `${deepbookConfig.PackageId}::custodian_v2::AccountCap`,\n },\n });\n return dynamicFields.data[0]?.data ? unstable_getObjectId(dynamicFields.data[0].data) : undefined;\n }\n\n createAccount(txb: TransactionBlock): TransactionObjectArgument {\n let [cap] = txb.moveCall({\n typeArguments: [],\n target: `${deepbookConfig.PackageId}::clob_v2::create_account`,\n arguments: [],\n });\n return cap;\n }\n\n zero(token: string, txb: TransactionBlock): TransactionObjectArgument {\n return txb.moveCall({\n typeArguments: [token],\n target: `0x2::coin::zero`,\n arguments: [],\n });\n }\n}\n","import { TransactionType } from '@msafe/sui3-utils';\nimport { SuiClient } from '@mysten/sui.js/client';\nimport { TransactionBlock } from '@mysten/sui.js/transactions';\nimport { WalletAccount } from '@mysten/wallet-standard';\nimport { TurbosSdk, Network } from 'turbos-clmm-sdk';\n\nimport { BaseIntentionLegacy } from '@/apps/interface/sui-js';\n\nimport { swap_exact_quote_for_base } from '../api/deepbook';\nimport { SuiNetworks, TransactionSubType } from '../types';\n\nexport interface SwapExactQuoteForBaseIntentionData {\n token1: string;\n token2: string;\n poolId: string;\n amountIn: number;\n}\n\nexport class SwapExactQuoteForBaseIntention extends BaseIntentionLegacy<SwapExactQuoteForBaseIntentionData> {\n txType!: TransactionType.Other;\n\n txSubType!: TransactionSubType.SwapExactQuoteForBase;\n\n constructor(public override readonly data: SwapExactQuoteForBaseIntentionData) {\n super(data);\n }\n\n async build(input: {\n suiClient: SuiClient;\n account: WalletAccount;\n network: SuiNetworks;\n }): Promise<TransactionBlock> {\n const turbosSdk = new TurbosSdk(input.network.replace('sui:', '') as Network, input.suiClient);\n const txb = await swap_exact_quote_for_base({ ...this.data, turbosSdk, currentAddress: input.account.address });\n return txb;\n }\n\n static fromData(data: SwapExactQuoteForBaseIntentionData) {\n return new SwapExactQuoteForBaseIntention(data);\n }\n}\n","import { TransactionType } from '@msafe/sui3-utils';\nimport { SuiClient } from '@mysten/sui.js/client';\nimport { TransactionBlock } from '@mysten/sui.js/transactions';\nimport { SuiSignTransactionBlockInput, WalletAccount } from '@mysten/wallet-standard';\n\nimport { IAppHelperInternalLegacy } from '@/apps/interface/sui-js';\nimport { SuiNetworks } from '@/types';\n\nimport { Decoder } from './decoder';\nimport { ClaimTicketIntention, ClaimTicketIntentionData } from './intentions/claimTicket';\nimport { StakeIntention, StakeIntentionData } from './intentions/stake';\nimport { UnStakeIntention, UnStakeIntentionData } from './intentions/unStake';\nimport { TransactionSubType } from './types';\n\nexport type VoloIntention = StakeIntention | UnStakeIntention | ClaimTicketIntention;\n\nexport type VoloIntentionData = StakeIntentionData | UnStakeIntentionData | ClaimTicketIntentionData;\n\nexport class VoloAppHelper implements IAppHelperInternalLegacy<VoloIntentionData> {\n application = 'volo';\n\n supportSDK = '@mysten/sui.js' as const;\n\n async deserialize(\n input: SuiSignTransactionBlockInput & { network: SuiNetworks; suiClient: SuiClient; account: WalletAccount },\n ): Promise<{ txType: TransactionType; txSubType: TransactionSubType; intentionData: VoloIntentionData }> {\n const { transactionBlock } = input;\n const decoder = new Decoder(transactionBlock);\n const result = decoder.decode();\n return {\n txType: TransactionType.Other,\n txSubType: result.type,\n intentionData: result.intentionData,\n };\n }\n\n async build(input: {\n intentionData: VoloIntentionData;\n txType: TransactionType;\n txSubType: string;\n suiClient: SuiClient;\n account: WalletAccount;\n }): Promise<TransactionBlock> {\n const { suiClient, account } = input;\n let intention: VoloIntention;\n switch (input.txSubType) {\n case TransactionSubType.Stake:\n intention = StakeIntention.fromData(input.intentionData as StakeIntentionData);\n break;\n case TransactionSubType.UnStake:\n intention = UnStakeIntention.fromData(input.intentionData as UnStakeIntentionData);\n break;\n case TransactionSubType.ClaimTicket:\n intention = ClaimTicketIntention.fromData(input.intentionData as ClaimTicketIntentionData);\n break;\n default:\n throw new Error('not implemented');\n }\n return intention.build({ suiClient, account });\n }\n}\n","import { TransactionType } from '@msafe/sui3-utils';\nimport { bcs } from '@mysten/sui.js/bcs';\nimport { MoveCallTransaction } from '@mysten/sui.js/dist/cjs/transactions';\nimport { TransactionBlock, TransactionBlockInput } from '@mysten/sui.js/transactions';\nimport { normalizeStructTag, normalizeSuiAddress } from '@mysten/sui.js/utils';\n\nimport config from './config';\nimport { TransactionSubType } from './types';\n\nexport function isSameCoinType(type1: string, type2: string) {\n return normalizeStructTag(type1) === normalizeStructTag(type2);\n}\n\nexport function isSameTarget(target1: string, target2: string): boolean {\n return normalizeStructTag(target1) === normalizeStructTag(target2);\n}\n\ntype DecodeResult = {\n txType: TransactionType;\n type: TransactionSubType;\n intentionData: any;\n};\n\nexport class Decoder {\n constructor(public readonly txb: TransactionBlock) {}\n\n decode() {\n console.log('txb', this.txb);\n if (this.isStakeTransaction()) {\n return this.decodeStake();\n }\n\n if (this.isUnStakeTransaction()) {\n return this.decodeUnStake();\n }\n\n if (this.isClaimTicketTransaction()) {\n return this.decodeClaimTicket();\n }\n\n throw new Error(`Unknown transaction type`);\n }\n\n private get transactions() {\n return this.txb.blockData.transactions;\n }\n\n private getMoveCallTransaction(target: string) {\n return this.transactions.find((trans) => trans.kind === 'MoveCall' && trans.target === target);\n }\n\n private isStakeTransaction() {\n return !!this.getMoveCallTransaction(`${config.packageId}::native_pool::stake`);\n }\n\n private isUnStakeTransaction() {\n return !!this.getMoveCallTransaction(`${config.packageId}::native_pool::unstake`);\n }\n\n private isClaimTicketTransaction() {\n return !!this.getMoveCallTransaction(`${config.packageId}::native_pool::burn_ticket`);\n }\n\n private decodeStake(): DecodeResult {\n const amount = (this.transactions[0] as any).amounts[0].value.toNumber() as number;\n return {\n txType: TransactionType.Other,\n type: TransactionSubType.Stake,\n intentionData: {\n amount,\n },\n };\n }\n\n private decodeUnStake(): DecodeResult {\n const splitCoinTrans = this.transactions.find((trans) => trans.kind === 'SplitCoins') as any;\n const amount = splitCoinTrans.amounts[0].value.toNumber() as number;\n return {\n txType: TransactionType.Other,\n type: TransactionSubType.UnStake,\n intentionData: {\n amount,\n },\n };\n }\n\n private decodeClaimTicket(): DecodeResult {\n const ticketId = this.helper.decodeOwnedObjectId(2);\n console.log(ticketId);\n return {\n txType: TransactionType.Other,\n type: TransactionSubType.ClaimTicket,\n intentionData: {\n ticketId,\n },\n };\n }\n\n private get helper() {\n const moveCall = this.transactions.find(\n (trans) => trans.kind === 'MoveCall' && trans.target.startsWith(config.packageId),\n ) as MoveCallTransaction;\n return new MoveCallHelper(moveCall, this.txb);\n }\n}\n\nexport class MoveCallHelper {\n constructor(\n public readonly moveCall: MoveCallTransaction,\n public readonly txb: TransactionBlock,\n ) {}\n\n decodeSharedObjectId(argIndex: number) {\n const input = this.getInputParam(argIndex);\n return MoveCallHelper.getSharedObjectId(input);\n }\n\n decodeOwnedObjectId(argIndex: number) {\n const input = this.getInputParam(argIndex);\n return MoveCallHelper.getOwnedObjectId(input);\n }\n\n decodeInputU64(argIndex: number) {\n const strVal = this.decodePureArg<string>(argIndex, 'u64');\n return Number(strVal);\n }\n\n decodeInputU8(argIndex: number) {\n const strVal = this.decodePureArg<string>(argIndex, 'u8');\n return Number(strVal);\n }\n\n decodeInputAddress(argIndex: number) {\n const input = this.decodePureArg<string>(argIndex, 'address');\n return normalizeSuiAddress(input);\n }\n\n decodeInputString(argIndex: number) {\n return this.decodePureArg<string>(argIndex, 'string');\n }\n\n decodeInputBool(argIndex: number) {\n return this.decodePureArg<boolean>(argIndex, 'bool');\n }\n\n decodePureArg<T>(argIndex: number, bcsType: string) {\n const input = this.getInputParam(argIndex);\n return MoveCallHelper.getPureInputValue<T>(input, bcsType);\n }\n\n getInputParam(argIndex: number) {\n const arg = this.moveCall.arguments[argIndex];\n if (arg.kind !== 'Input') {\n throw new Error('not input type');\n }\n return this.txb.blockData.inputs[arg.index];\n }\n\n static getPureInputValue<T>(input: TransactionBlockInput, bcsType: string) {\n if (input.type !== 'pure') {\n throw new Error('not pure argument');\n }\n if (typeof input.value === 'object' && 'Pure' in input.value) {\n const bcsNums = input.value.Pure;\n return bcs.de(bcsType, new Uint8Array(bcsNums)) as T;\n }\n return input.value as T;\n }\n\n static getOwnedObjectId(input: TransactionBlockInput) {\n if (input.type !== 'object') {\n throw new Error(`not object argument: ${JSON.stringify(input)}`);\n }\n if (typeof input.value === 'object') {\n if (!('Object' in input.value) || !('ImmOrOwned' in input.value.Object)) {\n throw new Error('not ImmOrOwned');\n }\n return normalizeSuiAddress(input.value.Object.ImmOrOwned.objectId as string);\n }\n return normalizeSuiAddress(input.value as string);\n }\n\n static getSharedObjectId(input: TransactionBlockInput) {\n if (input.type !== 'object') {\n throw new Error(`not object argument: ${JSON.stringify(input)}`);\n }\n if (typeof input.value !== 'object') {\n return normalizeSuiAddress(input.value as string);\n }\n if (!('Object' in input.value) || !('Shared' in input.value.Object)) {\n throw new Error('not Shared');\n }\n return normalizeSuiAddress(input.value.Object.Shared.objectId as string);\n }\n\n static getPureInput<T>(input: TransactionBlockInput, bcsType: string) {\n if (input.type !== 'pure') {\n throw new Error('not pure argument');\n }\n if (typeof input.value !== 'object') {\n return input.value as T;\n }\n if (!('Pure' in input.value)) {\n throw new Error('Pure not in value');\n }\n const bcsVal = input.value.Pure;\n return bcs.de(bcsType, new Uint8Array(bcsVal)) as T;\n }\n\n typeArg(index: number) {\n return normalizeStructTag(this.moveCall.typeArguments[index]);\n }\n\n txArg(index: number) {\n return this.moveCall.arguments[index];\n }\n}\n","const config = {\n packageId: '0x549e8b69270defbfafd4f94e17ec44cdbdd99820b33bda2278dea3b9a32d3f55',\n poolObjectId: '0x7fa2faa111b8c65bea48a23049bfd81ca8f971a262d981dcd9a17c3825cb5baf',\n metadataObjectId: '0x680cd26af32b2bde8d3361e804c53ec1d1cfe24c7f039eb7f549e8dfde389a60',\n systemStateObjectId: '0x0000000000000000000000000000000000000000000000000000000000000005',\n certType: '0x549e8b69270defbfafd4f94e17ec44cdbdd99820b33bda2278dea3b9a32d3f55::cert::CERT',\n gasBudget: 50_000_000,\n};\n\nexport default config;\n","import { TransactionType } from '@msafe/sui3-utils';\nimport { SuiClient } from '@mysten/sui.js/client';\nimport { TransactionBlock } from '@mysten/sui.js/transactions';\nimport { WalletAccount } from '@mysten/wallet-standard';\n\nimport { BaseIntentionLegacy } from '@/apps/interface/sui-js';\n\nimport config from '../config';\nimport { TransactionSubType } from '../types';\n\nexport interface ClaimTicketIntentionData {\n ticketId: string;\n}\n\nexport class ClaimTicketIntention extends BaseIntentionLegacy<ClaimTicketIntentionData> {\n txType: TransactionType.Other;\n\n txSubType: TransactionSubType.Stake;\n\n constructor(public readonly data: ClaimTicketIntentionData) {\n super(data);\n }\n\n async build(input: { suiClient: SuiClient; account: WalletAccount }): Promise<TransactionBlock> {\n console.log(input);\n const tx = new TransactionBlock();\n const { ticketId } = this.data;\n tx.moveCall({\n target: `${config.packageId}::native_pool::burn_ticket`,\n arguments: [tx.object(config.poolObjectId), tx.object(config.systemStateObjectId), tx.object(ticketId)],\n });\n return tx;\n }\n\n static fromData(data: ClaimTicketIntentionData) {\n return new ClaimTicketIntention(data);\n }\n}\n","import { TransactionType } from '@msafe/sui3-utils';\nimport { SuiClient } from '@mysten/sui.js/client';\nimport { TransactionBlock } from '@mysten/sui.js/transactions';\nimport { WalletAccount } from '@mysten/wallet-standard';\n\nimport { BaseIntentionLegacy } from '@/apps/interface/sui-js';\n\nimport config from '../config';\nimport { TransactionSubType } from '../types';\n\nexport interface StakeIntentionData {\n amount: number;\n}\n\nexport class StakeIntention extends BaseIntentionLegacy<StakeIntentionData> {\n txType: TransactionType.Other;\n\n txSubType: TransactionSubType.Stake;\n\n constructor(public readonly data: StakeIntentionData) {\n super(data);\n }\n\n async build(input: { suiClient: SuiClient; account: WalletAccount }): Promise<TransactionBlock> {\n console.log(input);\n const tx = new TransactionBlock();\n const { amount } = this.data;\n const [coin] = tx.splitCoins(tx.gas, [tx.pure(amount)]);\n tx.moveCall({\n target: `${config.packageId}::native_pool::stake`,\n arguments: [\n tx.object(config.poolObjectId),\n tx.object(config.metadataObjectId),\n tx.object(config.systemStateObjectId),\n coin,\n ],\n });\n return tx;\n }\n\n static fromData(data: StakeIntentionData) {\n return new StakeIntention(data);\n }\n}\n","import { TransactionType } from '@msafe/sui3-utils';\nimport { SuiClient } from '@mysten/sui.js/client';\nimport { TransactionBlock } from '@mysten/sui.js/transactions';\nimport { WalletAccount } from '@mysten/wallet-standard';\n\nimport { BaseIntentionLegacy } from '@/apps/interface/sui-js';\n\nimport config from '../config';\nimport { TransactionSubType } from '../types';\n\nexport interface UnStakeIntentionData {\n amount: number;\n}\n\nexport class UnStakeIntention extends BaseIntentionLegacy<UnStakeIntentionData> {\n txType: TransactionType.Other;\n\n txSubType: TransactionSubType.Stake;\n\n constructor(public readonly data: UnStakeIntentionData) {\n super(data);\n }\n\n async build(input: { suiClient: SuiClient; account: WalletAccount }): Promise<TransactionBlock> {\n console.log(input);\n const tx = new TransactionBlock();\n const { amount } = this.data;\n const coins = (\n await input.suiClient.getAllCoins({\n owner: input.account.address,\n limit: 100,\n })\n ).data;\n const [primaryCoin, ...mergeCoins] = coins.filter(\n (coin) => coin.coinType.split('::')[0] === config.certType.split('::')[0],\n );\n\n const primaryCoinInput = tx.object(primaryCoin.coinObjectId);\n if (mergeCoins.length) {\n tx.mergeCoins(\n primaryCoinInput,\n mergeCoins.map((coin) => tx.object(coin.coinObjectId)),\n );\n }\n const coin = tx.splitCoins(tx.object(primaryCoin.coinObjectId), [tx.pure(amount)]);\n\n tx.moveCall({\n target: `${config.packageId}::native_pool::unstake`,\n arguments: [\n tx.object(config.poolObjectId),\n tx.object(config.metadataObjectId),\n tx.object(config.systemStateObjectId),\n coin,\n ],\n });\n return tx;\n }\n\n static fromData(data: UnStakeIntentionData) {\n return new UnStakeIntention(data);\n }\n}\n","import { BucketHelper } from '@/apps/bucket/helper';\nimport { CetusHelper } from '@/apps/cetus/helper';\nimport { MPayAppHelper } from '@/apps/mpay/helper';\nimport { CoreHelper } from '@/apps/msafe-core/helper';\nimport { NAVIAppHelper } from '@/apps/navi/helper';\nimport { PlainTransactionHelper } from '@/apps/plain-transaction/helper';\nimport { MSafeApps } from '@/apps/registry';\nimport { ScallopAppHelper } from '@/apps/scallop/helper';\nimport { SuilendAppHelper } from '@/apps/suilend/helper';\nimport { TURBOSAppHelper } from '@/apps/turbos/helper';\nimport { VoloAppHelper } from '@/apps/volo/helper';\n\nexport const appHelpers = MSafeApps.fromHelpers([\n new CoreHelper(),\n new NAVIAppHelper(),\n new MPayAppHelper(),\n new PlainTransactionHelper(),\n new CetusHelper(),\n new TURBOSAppHelper(),\n // new KRIYAAppHelper(),\n new Scall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,CACvG,GAAM,CAAE,iBAAAC,CAAiB,EAAID,EAEvBE,EADU,IAAIC,GAAQF,CAAgB,EACrB,OAAO,EAC9B,MAAO,CACL,OAAQG,GAAgB,MACxB,UAAWF,EAAO,KAClB,cAAeA,EAAO,aACxB,CACF,CAEA,MAAM,MAAMF,EAMkB,CAC5B,GAAM,CAAE,UAAAK,EAAW,QAAAC,CAAQ,EAAIN,EAC3BO,EACJ,OAAQP,EAAM,UAAW,CACvB,YACEO,EAAYC,GAAe,SAASR,EAAM,aAAmC,EAC7E,MACF,cACEO,EAAYE,GAAiB,SAAST,EAAM,aAAqC,EACjF,MACF,kBACEO,EAAYG,GAAqB,SAASV,EAAM,aAAyC,EACzF,MACF,QACE,MAAM,IAAI,MAAM,iBAAiB,CACrC,CACA,OAAOO,EAAU,MAAM,CAAE,UAAAF,EAAW,QAAAC,CAAQ,CAAC,CAC/C,CACF,EMhDO,IAAMK,GAAaC,GAAU,YAAY,CAC9C,IAAIC,GACJ,IAAIC,GACJ,IAAIC,GACJ,IAAIC,GACJ,IAAIC,GACJ,IAAIC,GAEJ,IAAIC,GACJ,IAAIC,GACJ,IAAIC,GACJ,IAAIC,EACN,CAAC","names":["TransactionType","TransactionType","sortKeys","BaseIntention","data","Transaction","BucketClient","getBucketClient","network","account","config","getPsmTx","txbParams","account","network","coin","amount","isIn","tx","Transaction","getBucketClient","PsmIntention","_PsmIntention","BaseIntention","data","TransactionType","input","account","network","txbParams","getPsmTx","BucketHelper","input","txbParams","action","TransactionType","suiClient","account","network","intention","PsmIntention","TransactionType","TransactionType","AggregatorClient","Env","CetusPeripherySDK","CetusClmmSDK","SuiClient","clmmConfig","peripheryConfig","clmmConfigTestnet","peripheryConfigTestnet","getClmmSdk","network","account","config","clmmSdk","getPeripherySdk","aggregatorURL","getAggregatorSdk","suiClient","getAddLiquidityTxb","txbParams","account","network","getClmmSdk","getIncreaseLiquidityTxb","getRemoveLiquidityTxb","getDecreaseLiquidityTxb","getClaimFeeAndMiningTxb","AddLiquidityIntention","_AddLiquidityIntention","BaseIntention","data","TransactionType","input","account","network","txbParams","getAddLiquidityTxb","TransactionType","ClaimFeeAndMiningIntention","_ClaimFeeAndMiningIntention","BaseIntention","data","TransactionType","input","account","network","txbParams","getClaimFeeAndMiningTxb","TransactionType","DecreaseLiquidityIntention","_DecreaseLiquidityIntention","BaseIntention","data","TransactionType","input","account","network","txbParams","getDecreaseLiquidityTxb","TransactionType","getFarmingAddLiquidityTxb","txbParams","account","network","getPeripherySdk","getFarmingIncreaseLiquidityTxb","getFarmingDecreaseLiquidityTxb","getFarmingRemoveLiquidityTxb","getFarmingClaimFeeAndRewardTxb","getFarmingHarvest","getFarmingBatchHarvest","peripherySdk","params","getFarmingStake","getFarmingUnstake","FarmingAddLiquidityIntention","_FarmingAddLiquidityIntention","BaseIntention","data","TransactionType","input","account","network","txbParams","getFarmingAddLiquidityTxb","TransactionType","FarmingBatchHarvestIntention","_FarmingBatchHarvestIntention","BaseIntention","data","TransactionType","input","account","network","txbParams","getFarmingBatchHarvest","TransactionType","FarmingClaimFeeAndRewardIntention","_FarmingClaimFeeAndRewardIntention","BaseIntention","data","TransactionType","input","account","network","txbParams","getFarmingClaimFeeAndRewardTxb","TransactionType","FarmingDecreaseLiquidityIntention","_FarmingDecreaseLiquidityIntention","BaseIntention","data","TransactionType","input","account","network","txbParams","getFarmingDecreaseLiquidityTxb","TransactionType","FarmingHarvestIntention","_FarmingHarvestIntention","BaseIntention","data","TransactionType","input","account","network","txbParams","getFarmingHarvest","TransactionType","FarmingIncreaseLiquidityIntention","_FarmingIncreaseLiquidityIntention","BaseIntention","data","TransactionType","input","account","network","txbParams","getFarmingIncreaseLiquidityTxb","TransactionType","FarmingRemoveLiquidityIntention","_FarmingRemoveLiquidityIntention","BaseIntention","data","TransactionType","input","account","network","txbParams","getFarmingRemoveLiquidityTxb","TransactionType","FarmingStakeIntention","_FarmingStakeIntention","BaseIntention","data","TransactionType","input","account","network","txbParams","getFarmingStake","TransactionType","FarmingUnstakeIntention","_FarmingUnstakeIntention","BaseIntention","data","TransactionType","input","account","network","txbParams","getFarmingUnstake","TransactionType","IncreaseLiquidityIntention","_IncreaseLiquidityIntention","BaseIntention","data","TransactionType","input","account","network","txbParams","getIncreaseLiquidityTxb","TransactionType","RemoveLiquidityIntention","_RemoveLiquidityIntention","BaseIntention","data","TransactionType","input","account","network","txbParams","getRemoveLiquidityTxb","TransactionType","restituteMsafeFastRouterSwapParams","Transaction","getSwapRouterTxb","txbParams","account","network","aggregatorSdk","getAggregatorSdk","txb","Transaction","restituteMsafeFastRouterSwapParams","SwapIntention","_SwapIntention","BaseIntention","data","TransactionType","input","account","network","txbParams","getSwapRouterTxb","TransactionType","Transaction","VestingConfing","getVestingRedeemTxb","txbParams","account","network","pool","nftId","periods","CLOCK_ADDRESS","txb","period","VestingRedeemIntention","_VestingRedeemIntention","BaseIntention","data","TransactionType","input","account","network","txbParams","getVestingRedeemTxb","TransactionType","Transaction","getXcetusConvertTxb","txbParams","account","network","peripherySdk","getPeripherySdk","tx","Transaction","getXcetusRedeemLockTxb","getXcetusClaimingStakeRewardsTxb","getXcetusCancelRedeemTxb","getXcetusRedeemTxb","XcetusCancelIntention","_XcetusCancelIntention","BaseIntention","data","TransactionType","input","account","network","txbParams","getXcetusCancelRedeemTxb","TransactionType","XcetusClaimingStakeRewardsIntention","_XcetusClaimingStakeRewardsIntention","BaseIntention","data","TransactionType","input","account","network","txbParams","getXcetusClaimingStakeRewardsTxb","TransactionType","XcetusConvertIntention","_XcetusConvertIntention","BaseIntention","data","TransactionType","input","account","network","txbParams","getXcetusConvertTxb","TransactionType","XcetusRedeemIntention","_XcetusRedeemIntention","BaseIntention","data","TransactionType","input","account","network","txbParams","getXcetusRedeemTxb","TransactionType","XcetusRedeemLockIntention","_XcetusRedeemLockIntention","BaseIntention","data","TransactionType","input","account","network","txbParams","getXcetusRedeemLockTxb","CetusHelper","input","txbParams","action","TransactionType","suiClient","account","network","intention","AddLiquidityIntention","IncreaseLiquidityIntention","DecreaseLiquidityIntention","RemoveLiquidityIntention","ClaimFeeAndMiningIntention","FarmingAddLiquidityIntention","FarmingIncreaseLiquidityIntention","FarmingDecreaseLiquidityIntention","FarmingRemoveLiquidityIntention","FarmingClaimFeeAndRewardIntention","FarmingHarvestIntention","FarmingBatchHarvestIntention","FarmingStakeIntention","FarmingUnstakeIntention","XcetusConvertIntention","XcetusRedeemLockIntention","XcetusClaimingStakeRewardsIntention","XcetusCancelIntention","XcetusRedeemIntention","VestingRedeemIntention","SwapIntention","TransactionType","sortKeys","BaseIntentionLegacy","data","getFullnodeUrl","dev_exports","__export","contractId","dev_default","feeObjId","roleObjId","status","transaction","upgradeCapObjId","vaultObjId","prod_exports","__export","contractId","prod_default","feeObjId","roleObjId","status","transaction","upgradeCapObjId","vaultObjId","DEV_RPC_ENDPOINT","getFullnodeUrl","STG_RPC_ENDPOINT","PREV_RPC_ENDPOINT","PROD_RPC_ENDPOINT","DEV_BE_API","STG_BE_API","PREV_BE_API","PROD_BE_API","CONTRACT_DEV","dev_exports","CONTRACT_PROD","prod_exports","ENV_CONFIG","getConfig","env","options","ec","SuiClient","MPayError","mpayErrorCode","msg","options","cause","context","NoBackendError","MPayError","WalletNotConnectedError","MPayError","axios","AxiosError","BackendError","MPayError","msg","context","Backend","_Backend","apiURL","response","AxiosError","BackendError","recipient","options","res","axios","sender","query","paginatedData","event","formalizedEvent","address","Globals","_Globals","envConfig","SuiClient","Backend","env","options","ec","getConfig","NoBackendError","b","wallet","WalletNotConnectedError","SUI_TYPE_ARG","normalizeStructTag","normalizeSuiAddress","TransactionBlock","TransactionBlock","SUI_TYPE_ARG","normalizeStructTag","FEE_NUMERATOR","FEE_DENOMINATOR","CLAIM_FEE_NUMERATOR","FLAT_FEE_SUI","MoveObject","object","txb","ObjectVector","objects","o","ResultRef","_ResultRef","result","target","property","nestedResultFor","resultIndex","Buffer","normalizeSuiAddress","InvalidRpcResultError","MPayError","msg","ctx","InspectViewer","results","index","returned","callIndex","returnIndex","callResult","value","type","InvalidRpcResultError","normalizeSuiAddress","Buffer","bcs","InvalidInputError","MPayError","msg","fieldKey","fieldValue","metadataBcsType","MAX_NAME_SIZE","encodeMetadata","metadata","validateMetadata","bcs","decodeMetadata","metaStr","isAsciiString","InvalidInputError","str","normalizeStructTag","isSameCoinType","type1","type2","isSameTarget","target1","target2","GAS_OBJECT_SPEC","nanoid","generateGroupId","CreateStreamHelper","_CreateStreamHelper","globals","feeContract","streamContract","info","encodeMetadata","generateGroupId","normalizeStructTag","recipient","txb","TransactionBlock","paymentWithFee","coinReqs","coinResp","paymentMergedObject","flatFeeMergedObject","i","paymentAmount","feeAmount","paymentCoin","flatFeeCoin","ResultRef","createInfo","infoInternal","FEE_NUMERATOR","FEE_DENOMINATOR","CLAIM_FEE_NUMERATOR","FLAT_FEE_SUI","coins","mergedCoin","coinId","GAS_OBJECT_SPEC","payment","streamCoinType","isSameCoinType","SUI_TYPE_ARG","streamPayment","sum","totalAmount","fee","numEpoch","streamAmount","res","InspectViewer","Transactions","CLOCK_ID","BaseContract","moduleName","config","globals","txb","input","target","Transactions","arg","ObjectVector","MoveObject","ResultRef","callArgs","typeArgs","object","CLOCK_ID","FeeContract","_FeeContract","BaseContract","config","globals","txb","createFeeNumerator","roleObject","feeObject","flatFee","claimFee","amount","StreamContract","_StreamContract","BaseContract","config","globals","txb","input","feeObject","vaultObject","paymentCoinObject","flatFeeObject","clockObject","streamObject","MPayBuilder","globals","config","FeeContract","StreamContract","info","infoInternal","CreateStreamHelper","streamId","enabled","coinType","txb","TransactionBlock","SanityError","MPayError","msg","options","getAllFromIterator","it","res","val","PagedIterator","requester","EntryIterator","NotEnoughBalanceError","MPayError","coinType","requestAmount","gotAmount","DEF_REQ_PAGE_SIZE","getCoinsWithAmount","suiClient","owner","requestAmount","coinType","pageSize","it","OwnedCoinIterator","totalAmount","res","val","NotEnoughBalanceError","OwnedCoinIterator","EntryIterator","suiClient","owner","coinType","reqPageSize","OwnedCoinRequester","SanityError","res","TransactionBlock","normalizeStructTag","parseStructTag","DateTime","NotCreatorError","MPayError","NotRecipientError","MPayError","RpcError","MPayError","msg","context","StreamNotFoundError","MPayError","streamId","DateTime","Duration","MAX_U64","TIME_ROUND_UNIT","roundDateTime","date","dateMs","roundMs","roundDuration","duration","durationMs","Stream","_Stream","globals","streamId","rawData","StreamContract","data","SanityError","pagination","NotCreatorError","txb","TransactionBlock","NotRecipientError","enabled","normalizeStructTag","roundDuration","metadata","decodeMetadata","roundDateTime","rawConfig","duration","rawStatus","MAX_U64","timeNowMs","DateTime","timeStartMs","epoch","res","StreamNotFoundError","RpcError","content","typeParams","parseStructTag","coinType","dataFields","config","status","normalizeStructTag","SUI_TYPE_ARG","Duration","TransactionFailedError","MPayError","status","msg","MIN_INTERVAL_MS","MPayHelper","globals","CoinMetaHelper","MPayBuilder","res","TransactionFailedError","change","info","input","InvalidInputError","cliffFraction","cliffAmount","amountPerStep","timeEnd","intervalMilli","Duration","address","coinType","balance","coinMeta","normalizeStructTag","allBalance","coinMetas","bal","i","txb","val","originTotalAmount","suiClient","normalized","SUI_TYPE_ARG","meta","normalizeStructTag","normalizeSuiAddress","DateTime","InvalidStreamGroupError","MPayError","msg","context","REQUEST_PAGE_SIZE","getObjectsById","suiClient","ids","options","oidIter","ListOidIterator","iter","ObjectBatchIterator","getAllFromIterator","EntryIterator","idIter","ObjectBatchRequester","stringIter","requestPage","objId","res","filtered","filter","StreamGroup","_StreamGroup","globals","streams","InvalidStreamGroupError","gids","st","InvalidInputError","ids","streamObjs","getObjectsById","obj","SanityError","responses","commonInfos","stream","expInfo","isEqual","info","isEqualStreamGroupCommonInfo","i","sum","pagination","Stream","info1","info2","PagedStreamListIterator","_PagedStreamListIterator","it","pageSize","input","StreamListIterator","res","_StreamListIterator","requester","StreamListRequester","SanityError","_StreamListRequester","globals","recipient","groupRefs","query","oidIter","ListOidIterator","ref","ObjectBatchIterator","backendQuery","convertToIncomingBackendQuery","filtered","normalizeSuiAddress","groupedRefs","groupAndSortRefs","convertToOutgoingBackendQuery","sender","refs","stRefs","stream","getStreamFromIterator","isStreamOfQuery","sg","getStreamGroupFromIterator","isStreamGroupOfQuery","m","groupList","gl1","gl2","DateTime","isStatus","isStreamOfStatus","isClaimable","filter","streamId","data","getStreamObjectResponseFromIter","Stream","streamIds","objResponses","StreamGroup","convertStreamStatus","normalizeCoinTypeFilter","normalizeAddressFilter","status","st","sts","convertStreamStatusSingle","InvalidInputError","coinType","ct","normalizeStructTag","address","addr","MSafeAccountAdapter","msafe","reqs","MSafeSingleWallet","account","SingleWalletAdapter","singleWallet","suiClient","req","isSameCoinType","SUI_TYPE_ARG","GAS_OBJECT_SPEC","InvalidInputError","coins","getCoinsWithAmount","SanityError","coin","MPayClient","env","options","Globals","MPayHelper","wallet","adapter","info","streamId","Stream","query","pageSize","PagedStreamListIterator","address","coinType","normalizeStructTag","recipient","normalizeSuiAddress","creator","MPayBuilder","StreamIntention","BaseIntentionLegacy","network","account","mpayClient","MPayClient","MSafeSingleWallet","CancelStreamIntention","StreamIntention","data","TransactionType","input","network","account","TransactionType","ClaimByProxyStreamIntention","StreamIntention","data","TransactionType","input","network","account","TransactionType","ClaimStreamIntention","StreamIntention","data","TransactionType","input","network","account","TransactionType","CreateStreamIntention","StreamIntention","data","TransactionType","input","network","account","bcs","normalizeStructTag","normalizeSuiAddress","MoveCallHelper","_MoveCallHelper","moveCall","txb","argIndex","input","strVal","bcsType","arg","bcsNums","bcsVal","index","CreateStreamDecodeHelper","globals","txb","streamInfo","fees","infos","moveCall","txs","tx","isSameTarget","SanityError","MoveCallHelper","metadata","name","groupId","decodeMetadata","recipient","timeStart","cliff","epochInterval","totalEpoch","amountPerEpoch","cancelable","coinType","info","InvalidInputError","recipients","StreamContract","FeeContract","CreateStreamHelper","arg","DecodeHelper","globals","txb","StreamContract","tx","isSameTarget","CreateStreamDecodeHelper","streamId","enabled","moveCall","MoveCallHelper","TransactionType","SetAutoClaimStreamIntention","StreamIntention","data","TransactionType","input","network","account","MPayAppHelper","input","network","transactionBlock","globals","Globals","result","DecodeHelper","intention","CreateStreamIntention","SetAutoClaimStreamIntention","ClaimStreamIntention","ClaimByProxyStreamIntention","CancelStreamIntention","intentionData","TransactionDefaultApplication","TransactionSubTypes","buildCoinTransferTxb","CoinTransferIntention","_CoinTransferIntention","BaseIntentionLegacy","data","input","suiClient","account","buildCoinTransferTxb","buildObjectTransferTxb","ObjectTransferIntention","_ObjectTransferIntention","BaseIntentionLegacy","data","input","suiClient","account","buildObjectTransferTxb","isSameAddress","TransactionBlock","PlainPayloadIntention","_PlainPayloadIntention","BaseIntentionLegacy","data","input","account","tb","TransactionBlock","isSameAddress","CoreHelper","TransactionDefaultApplication","input","suiClient","account","intention","TransactionSubTypes","CoinTransferIntention","ObjectTransferIntention","PlainPayloadIntention","TransactionType","updated","config","updatePackageId","data","res","packageId","borrowFee","borrowFeeAddress","pool","e","config_default","TransactionType","bcs","normalizeStructTag","normalizeSuiAddress","Decoder","txb","target","trans","config_default","assetId","findPool","pool","claims","helper","MoveCallHelper","optionId","poolId","typeArguments","TransactionType","amount","moveCall","_MoveCallHelper","argIndex","input","strVal","normalizeSuiAddress","bcsType","arg","bcsNums","bcs","bcsVal","index","normalizeStructTag","TransactionBlock","depositToken","txb","pool","coinObject","amount","config_default","withdrawToken","borrowToken","tx","userAddress","borrowBalance","borrowCoin","borrowFeeCoin","repayToken","claimReward","assetId","poolId","option","typeArguments","ClaimRewardIntention","_ClaimRewardIntention","BaseIntentionLegacy","data","claims","tx","TransactionBlock","claim","assetId","poolId","option","typeArguments","claimReward","TransactionBlock","EntryBorrowIntention","_EntryBorrowIntention","BaseIntentionLegacy","data","input","coinType","amount","tx","TransactionBlock","pool","config_default","borrowToken","TransactionBlock","getTokenObjs","client","sender","coinType","result","EntryDepositIntention","_EntryDepositIntention","BaseIntentionLegacy","data","input","suiClient","account","coinType","amount","tx","TransactionBlock","toDeposit","depositToken","config_default","pool","tokenInfo","getTokenObjs","coinObj","i","TransactionBlock","EntryRepayIntention","_EntryRepayIntention","BaseIntentionLegacy","data","input","suiClient","account","coinType","amount","tx","TransactionBlock","toDeposit","repayToken","config_default","pool","tokenInfo","getTokenObjs","coinObj","i","TransactionBlock","EntryWithdrawIntention","_EntryWithdrawIntention","BaseIntentionLegacy","data","coinType","amount","tx","TransactionBlock","pool","config_default","withdrawToken","NAVIAppHelper","input","updatePackageId","transactionBlock","result","Decoder","TransactionType","suiClient","account","intention","EntryDepositIntention","EntryBorrowIntention","EntryRepayIntention","EntryWithdrawIntention","ClaimRewardIntention","TransactionSubTypes","TransactionType","fromHEX","toHEX","Transaction","sortKeys","PlainTransactionApplication","PlainTransactionType","PlainTransactionIntention","_PlainTransactionIntention","data","input","PlainTransactionHelper","transaction","content","account","tx","inspectResult","SuiClient","Transaction","SuiClientLegacy","TransactionBlock","MSafeApps","_MSafeApps","apps","mApps","i","app","SuiJsSdkAdapter","SuiSdkAdapter","appName","helper","input","client","clientLegacy","build","tx","bytes","TransactionType","TransactionType","Decoder","txb","scallop","target","trans","API_BASE_URL","ADDRESSES_ID","PROTOCOL_OBJECT_ID","SCA_COIN_TYPE","OLD_BORROW_INCENTIVE_PROTOCOL_ID","SUPPORT_POOLS","SUPPORT_COLLATERALS","SUPPORT_SPOOLS","SUPPORT_SCOIN","SUPPORT_SPOOLS_REWARDS","SUPPORT_BORROW_INCENTIVE_POOLS","coinDecimals","spoolRewardCoins","borrowIncentiveRewardCoins","coinIds","wormholeCoinIds","voloCoinIds","sCoinIds","bcs","normalizeStructTag","normalizeSuiAddress","MoveCallHelper","_MoveCallHelper","moveCall","txb","argIndex","input","strVal","bcsType","arg","bcsNums","bcsVal","index","bcs","SplitCoinHelper","splitCoin","txb","input","MoveCallHelper","bcsType","bcsNums","bcs","DecoderLending","Decoder","supplyMoveCall","stakeMoveCall","unstakeMoveCall","withdrawMoveCall","redeem","burnScoin","borrowMoveCall","repayMoveCall","lendingIncentive","borrowIncentiveV2","oldBorrowIncentive","OLD_BORROW_INCENTIVE_PROTOCOL_ID","stakeWithVeSca","stakeWithoutVesca","trans","MoveCallHelper","moveCall","TransactionType","veScaKey","obligationKey","obligationId","rewardCoinName","coinName","amount","amountFromSplitCoin","SplitCoinHelper","a","b","stakeSpoolAccount","coinType","stakeAccountWithAmount","tx","stakeAccountId","slippage","validSwapAmount","lendingReward","borrowRewardV2","borrowReward","stakeMarketCoinName","TransactionType","DecoderReferral","Decoder","trans","MoveCallHelper","moveCall","TransactionType","veScaKey","coins","helper","TransactionType","DecoderVesca","Decoder","extendPeriod","stakeMoreSca","moveCall","trans","MoveCallHelper","OLD_BORROW_INCENTIVE_PROTOCOL_ID","veScaKey","TransactionType","lockSca","unlockTime","amountFromSplitCoin","SplitCoinHelper","a","b","isHaveRedeem","oldUnstakeObligation","unstakeObligation","stakeObligation","isObligationLocked","isOldBorrowIncentive","obligationId","obligationKey","operations","i","sortKeys","ScallopCoreBaseIntention","data","BorrowIntention","_BorrowIntention","ScallopCoreBaseIntention","data","input","BorrowWithBoostIntention","_BorrowWithBoostIntention","ScallopCoreBaseIntention","data","input","BorrowWithReferralIntention","_BorrowWithReferralIntention","ScallopCoreBaseIntention","data","input","ClaimIncentiveRewardIntention","_ClaimIncentiveRewardIntention","ScallopCoreBaseIntention","data","input","DepositCollateralIntention","_DepositCollateralIntention","ScallopCoreBaseIntention","data","input","MigrateAndClaimIntention","_MigrateAndClaimIntention","ScallopCoreBaseIntention","data","input","MigrateScoinIntention","_MigrateScoinIntention","ScallopCoreBaseIntention","data","input","MigrateWusdcToUsdcIntention","_MigrateWusdcToUsdcIntention","ScallopCoreBaseIntention","data","input","OpenObligationIntention","_OpenObligationIntention","ScallopCoreBaseIntention","data","input","RepayIntention","_RepayIntention","ScallopCoreBaseIntention","data","input","RepayWithBoostIntention","_RepayWithBoostIntention","ScallopCoreBaseIntention","data","input","StakeSpoolIntention","_StakeSpoolIntention","ScallopCoreBaseIntention","data","input","SupplyLendingIntention","_SupplyLendingIntention","ScallopCoreBaseIntention","data","input","UnstakeSpoolIntention","_UnstakeSpoolIntention","ScallopCoreBaseIntention","data","input","WithdrawAndUnstakeLendingIntention","_WithdrawAndUnstakeLendingIntention","ScallopCoreBaseIntention","data","input","WithdrawCollateralIntention","_WithdrawCollateralIntention","ScallopCoreBaseIntention","data","input","WithdrawLendingIntention","_WithdrawLendingIntention","ScallopCoreBaseIntention","data","input","BindReferralIntention","_BindReferralIntention","ScallopCoreBaseIntention","data","input","ClaimRevenueReferralIntention","_ClaimRevenueReferralIntention","ScallopCoreBaseIntention","data","input","CreateReferralLinkIntention","_CreateReferralLinkIntention","ScallopCoreBaseIntention","data","input","ExtendPeriodAndStakeMoreIntention","_ExtendPeriodAndStakeMoreIntention","ScallopCoreBaseIntention","data","input","ExtendStakePeriodIntention","_ExtendStakePeriodIntention","ScallopCoreBaseIntention","data","input","RedeemScaIntention","_RedeemScaIntention","ScallopCoreBaseIntention","data","input","RenewExpStakePeriodIntention","_RenewExpStakePeriodIntention","ScallopCoreBaseIntention","data","input","StakeScaIntention","_StakeScaIntention","ScallopCoreBaseIntention","data","input","SupplyAndStakeLendingIntention","_SupplyAndStakeLendingIntention","ScallopCoreBaseIntention","data","input","WithdrawStakedScaIntention","_WithdrawStakedScaIntention","ScallopCoreBaseIntention","data","input","ScallopAddress","params","id","path","nestedAddressObj","key","options","response","API_BASE_URL","responseData","TransactionBlock","BigNumber","TransactionBlock","ScallopBuilder","params","instance","address","query","utils","txBlock","assetCoinName","amount","sender","coinType","coins","takeCoin","leftCoin","marketCoinName","marketCoinType","totalAmount","prev","coin","coinIds","value","sCoinName","sCoinType","TransactionBlock","BigNumber","getObligations","query","ownerAddress","owner","protocolObjectId","PROTOCOL_OBJECT_ID","keyObjectsResponse","hasNextPage","nextCursor","paginatedKeyObjectsResponse","keyObjectIds","ref","id","keyObjects","obligations","i","keyId","content","fields","obligationId","locked","getObligationLocked","obligationObjectResponse","obligationLocked","getCoinAmounts","assetCoinNames","updatedAssetCoinNames","SUPPORT_POOLS","coinObjectsResponse","paginatedCoinObjectsResponse","assetCoinName","coinAmounts","response","object","coinObject","type","poolCoinName","BigNumber","getCoinAmount","coinType","coinAmount","getMarketCoinAmounts","marketCoinNames","updatedMarketCoinNames","marketCoinObjectsResponse","paginatedMarketCoinObjectsResponse","marketCoinName","marketCoinAmounts","marketCoinObject","getMarketCoinAmount","marketCoinType","marketCoinAmount","queryObligation","queryTarget","txBlock","TransactionBlock","normalizeStructTag","getStakeAccounts","query","ownerAddress","owner","spoolObjectId","stakeAccountType","stakeObjectsResponse","hasNextPage","nextCursor","paginatedStakeObjectsResponse","stakeAccounts","stakeMarketCoinTypes","types","stakeMarketCoinName","stakeCoinName","marketCoinType","updateTypes","newType","stakeObjectIds","ref","id","stakeObject","type","fields","stakePoolId","stakeType","staked","index","points","totalPoints","getStakePool","marketCoinName","poolId","stakePool","stakePoolObjectResponse","stakePoolObject","maxPoint","distributedPoint","pointPerPeriod","period","maxStake","totalStaked","createdAt","lastUpdate","getStakeRewardPool","stakeRewardPool","stakeRewardPoolObjectResponse","stakeRewardPoolObject","rewardPoolFields","ratioNumerator","ratioDenominator","rewards","claimedRewards","TransactionBlock","normalizeStructTag","BigNumber","requireSender","txBlock","sender","checkLockSca","scaAmountOrCoin","lockPeriodInDays","newUnlockAtInSecondTimestamp","prevUnlockAtInSecondTimestamp","isInitialLock","isLockExpired","checkVesca","checkExtendLockPeriod","checkExtendLockAmount","scaAmount","checkRenewExpiredVeSca","normalizeStructTag","parseStructTag","BigNumber","parseOriginBorrowIncentiveAccountPoolPointData","originBorrowIncentiveAccountPoolPointData","normalizeStructTag","parseOriginBorrowIncentiveAccountData","originBorrowIncentiveAccountData","acc","point","parsed","name","parseStructTag","isMarketCoin","coinName","assetCoinName","SUPPORT_POOLS","SUPPORT_COLLATERALS","SUPPORT_SPOOLS_REWARDS","parseAssetSymbol","findClosestUnlockRound","unlockAtInSecondTimestamp","unlockDate","closestTwelveAM","now","queryBorrowIncentiveAccounts","query","obligationId","sender","borrowIncentiveCoinNames","coinName","SUPPORT_BORROW_INCENTIVE_POOLS","queryPkgId","incentiveAccountsId","queryTarget","txBlock","TransactionBlock","borrowIncentiveAccountsQueryData","borrowIncentiveAccounts","accountData","parsedBorrowIncentiveAccount","parseOriginBorrowIncentiveAccountData","poolType","parsedCoinName","getBindedVeScaKey","address","client","obligationId","borrowIncentiveObjectId","incentiveAccountsId","corePkg","incentiveAccountsObject","incentiveAccountsTableId","bindedIncentiveAcc","getPythPrice","query","assetCoinName","pythFeedObjectId","priceFeedObjectResponse","priceFeedPoolObject","fields","expoMagnitude","expoNegative","priceMagnitude","priceNegative","BigNumber","getVescaKeys","query","ownerAddress","owner","veScaKeyType","keyObjectsResponse","hasNextPage","nextCursor","paginatedKeyObjectsResponse","objResponse","data","getVeScas","keyObjectId","veScas","i","veSca","getVeSca","veScaKeyId","tableId","veScaKeyIdValue","vesca","veScaDynamicFieldObject","dynamicFields","ScallopQuery","params","instance","address","utils","ownerAddress","getObligations","assetCoinNames","getCoinAmounts","assetCoinName","getCoinAmount","marketCoinNames","getMarketCoinAmounts","marketCoinName","getMarketCoinAmount","getPythPrice","getStakeAccounts","stakeMarketCoinName","stakeMarketCoinNames","SUPPORT_SPOOLS","stakePools","i","stakePool","getStakePool","stakeRewardPools","stakeRewardPool","getStakeRewardPool","obligationId","walletAddress","coinNames","queryBorrowIncentiveAccounts","obligation","queryObligation","collateralCoinTypes","collateral","debtCoinTypes","debt","coinType","SUI_TYPE_ARG","normalizeStructTag","ScallopUtils","params","address","coinName","isMarketCoin","assetCoinName","parseAssetSymbol","validCoinName","coinPackageId","coinIds","wormholeCoinIds","voloCoinIds","protocolObjectId","PROTOCOL_OBJECT_ID","coinType","type","normalizeStructTag","coinTypeRegex","coinTypeMatch","isMarketCoinType","wormHoleCoinTypeMap","voloCoinTypeMap","marketCoinName","stakeMarketCoinName","spoolRewardCoins","borrowIncentiveCoinName","borrowIncentiveRewardCoins","coinDecimals","sCoinName","sCoinIds","amount","SUI_TYPE_ARG","ownerAddress","selectedCoins","totalAmount","hasNext","nextCursor","coins","a","b","i","coin","apr","compoundFrequency","apy","txBlock","coinObjectId","coinObjects","objectId","mergedCoin","sendCoin","extendLockPeriodInDay","unlockAtInSecondTimestamp","now","remainingLockPeriod","newUnlockAtInSecondTimestamp","lockPeriod","findClosestUnlockRound","SUPPORT_SCOIN","SUI_CLOCK_OBJECT_ID","SUI_TYPE_ARG","requireVeSca","params","builder","txBlock","veScaKey","veSca","getVeSca","sender","requireSender","veScas","getVeScas","requireObligationInfo","params","builder","txBlock","obligationId","obligationKey","obligationLocked","getObligationLocked","sender","requireSender","obligations","getObligations","selectedObligation","obligation","generateBorrowIncentiveNormalMethod","borrowIncentiveIds","OldBorrowIncentiveContract","veScaIds","SUI_CLOCK_OBJECT_ID","veScaKey","SUI_TYPE_ARG","rewardCoinName","rewardType","generateBorrowIncentiveQuickMethod","normalMethod","obligationArg","obligationtKeyArg","unstakeObligationBeforeStake","txn","OLD_BORROW_INCENTIVE_PROTOCOL_ID","bindedVeScaKey","getBindedVeScaKey","SUI_CLOCK_OBJECT_ID","SUI_CLOCK_OBJECT_ID","axios","PYTH_ENDPOINTS","bcs","SUI_CLOCK_OBJECT_ID","MAX_ARGUMENT_SIZE","PythClient","provider","pythStateId","wormholeStateId","result","objectId","state","vaas","tx","wormholePackageId","verifiedVaas","vaa","verifiedVaa","updates","feedIds","packageId","priceUpdatesHotPotato","priceInfoObjects","baseUpdateFee","coins","coinId","i","priceInfoObjectId","feedId","normalizedFeedId","tableId","fieldType","type","accumulatorMessage","vaaSizeOffset","vaaSize","vaaOffset","getLatestVaas","endpoint","priceIds","axios","vaa","updateOracles","builder","txBlock","assetCoinNames","coinNames","SUPPORT_POOLS","SUPPORT_COLLATERALS","rules","pythClient","PythClient","assetCoinName","endpoints","PYTH_ENDPOINTS","priceUpdateData","e","updateAssetCoinNames","updateOracle","coinType","updatePrice","xOraclePackageId","xOracleId","pythPackageId","pythRegistryId","pythStateId","pythFeedObjectId","switchboardPackageId","switchboardRegistryId","switchboardAggregatorId","supraPackageId","supraRegistryId","supraHolderId","request","priceUpdateRequest","updatePythPrice","updateSwitchboardPrice","updateSupraPrice","confirmPriceUpdateRequest","packageId","validXOracleId","target","typeArgs","SUI_CLOCK_OBJECT_ID","holderId","registryId","validHolderId","validRegistryId","aggregatorId","validAggregatorId","stateId","feedObjectId","validRequest","validStateId","validFeedObjectId","generateSCoinNormalMethod","builder","txBlock","sCoinPkgIds","treasuryIds","SUPPORT_SCOIN","sCoinName","treasuryId","marketCoinName","marketCoin","sCoin","requireObligationInfo","params","txBlock","builder","obligationId","obligationKey","sender","requireSender","obligations","getObligations","generateCoreNormalMethod","coreIds","referralWitnessType","obligation","obligationHotPotato","coin","collateralCoinName","coinType","amount","SUI_CLOCK_OBJECT_ID","poolCoinName","marketCoin","borrowReferral","loan","generateCoreQuickMethod","normalMethod","scoinNormalMethod","generateSCoinNormalMethod","obligationArg","suiCoin","leftCoin","takeCoin","obligationInfo","updateCoinNames","updateOracles","walletAddress","marketCoinName","sCoinName","sCoinAmount","txResult","amountLeft","leftMarketCoin","takeMarketCoin","assetCoinNames","SUI_CLOCK_OBJECT_ID","generateReferralNormalMethod","builder","txBlock","referralIds","veScaTable","veScaKeyId","SUI_CLOCK_OBJECT_ID","poolCoinName","coinType","ticket","veScaKey","generateReferralQuickMethod","normalMethod","walletAddress","coinNames","SUPPORT_POOLS","objToTransfer","i","rewardCoin","coins","SlippageContract","SlippageTxBuilder","tx","resultCoin","slippage","expectedAmount","coinType","SUI_CLOCK_OBJECT_ID","stakeHelper","builder","txBlock","stakeAccount","coinName","amount","sender","isSCoin","scoinNormalMethod","generateSCoinNormalMethod","spoolNormalMethod","generateSpoolNormalMethod","takeCoin","leftCoin","totalAmount","marketCoin","requireStakeAccountIds","params","stakeMarketCoinName","stakeAccountId","requireSender","getStakeAccounts","account","requireStakeAccounts","stakeAccounts","spoolIds","stakePoolIds","rewardPoolIds","stakeMarketCoinTypes","SUPPORT_SPOOLS","spoolId","rewardId","marketCoinType","stakePoolId","SUI_CLOCK_OBJECT_ID","coin","rewardPoolId","rewardCoinName","spoolRewardCoins","rewardCoinType","generateSpoolQuickMethod","normalMethod","scoinMethod","amountOrMarketCoin","stakeAccountIds","createdStakeAccount","stakedMarketCoinAmount","returnSCoin","toTransfer","amountUnstake","amountToUnstake","sCoin","mergedCoin","rewardCoins","accountId","rewardCoin","SUI_CLOCK_OBJECT_ID","generateNormalVeScaMethod","builder","txBlock","veScaIds","scaCoin","unlockAtInSecondTimestamp","SUI_CLOCK_OBJECT_ID","veScaKey","newUnlockAtInSecondTimestamp","generateQuickVeScaMethod","normalMethod","amountOrCoin","lockPeriodInDays","autoCheck","sender","requireSender","veSca","requireVeSca","transferObjects","coins","SCA_COIN_TYPE","takeCoin","leftCoin","newUnlockAt","checkLockSca","isInitialLock","isLockExpired","unlockedSca","checkExtendLockPeriod","scaAmount","checkExtendLockAmount","scaCoins","checkRenewExpiredVeSca","checkVesca","sca","normalizeStructTag","SUI_CLOCK_OBJECT_ID","DeepBookPools","DeepBookContract","DeepBookHelperContract","DeepBookModuleAndMethod","SUI_CLOCK_OBJECT","SUI_CLOCK_OBJECT_ID","getDeepBookPool","coinAName","coinBName","DeepBookPools","DeepBookTxBuilder","tx","DeepBookContract","DeepBookModuleAndMethod","tokenInObject","baseCoinName","quoteCoinName","clientOrderId","accountCap","scallopUtils","pool","aToB","coinAType","coinBType","parsedAccountCap","DeepBookHelperContract","DeepBookSwap","client","currentAddress","accountCap","scallopUtils","id","tx","accountCapsResponse","normalizeStructTag","DeepBookTxBuilder","tokenObjectIn","baseCoinName","quoteCoinName","ScallopClient","params","address","ScallopUtils","ScallopQuery","ScallopBuilder","DeepBookSwap","ownerAddress","owner","stakeMarketCoinName","walletAddress","txBlock","TransactionBlock","coreQuickMethod","generateCoreQuickMethod","borrowIncentiveMethod","generateBorrowIncentiveQuickMethod","sender","obligationId","obligationKey","hotPotato","collateralCoinName","amount","quickMethod","obligations","specificObligationId","obligation","collateralCoin","poolCoinName","scoinMethod","generateSCoinNormalMethod","marketCoin","parseScoin","SUPPORT_SCOIN","scoin","coin","borrowIncentiveQuickMethod","availableStake","SUPPORT_BORROW_INCENTIVE_POOLS","veScaKey","referralMethod","generateReferralNormalMethod","borrowReferral","marketCoinName","spoolQuickMethod","generateSpoolQuickMethod","stakeAccount","stakeAccountId","SUPPORT_SPOOLS","stakeAccounts","targetStakeAccount","account","unstakeAccount","withdrawCoins","i","wdScoin","wdCoin","returnScoin","marketCoins","lendingIncentive","borrowIncentiveV2","borrowIncentive","borrowIncentiveRewarad","rewardCoins","rewardCoin","rewardCoinName","obligationKeyId","isObligationLocked","isOldBorrowIncentive","lockPeriod","vescaKey","vescaQuickMethod","generateQuickVeScaMethod","coins","SCA_COIN_TYPE","takeCoin","leftCoin","newVescaKey","lockPeriodInDays","isHaveRedeem","redeem","accountPoint","poolPoint","borrowAmount","BigNumber","increasePointRate","vescaMethod","referralTicket","referral","generateReferralQuickMethod","coinsName","scoinNormalMethod","toTransfer","sCoinName","sCoins","toDestroyMarketCoin","mergedMarketCoin","e","sCoin","existSCoins","mergedSCoin","slippage","validSwapAmount","marketCoinType","coinIds","value","coinSwap","coinB","accountCap","SlippageTxBuilder","mintedMarketCoin","Scallop","params","ScallopAddress","ADDRESSES_ID","ScallopClient","builder","query","utils","ScallopAppHelper","input","Scallop","transactionBlock","decoderLending","DecoderLending","decoderReferral","DecoderReferral","decoderVesca","DecoderVesca","result","TransactionType","suiClient","account","network","txSubType","intentionData","intention","SupplyLendingIntention","WithdrawLendingIntention","BorrowIntention","RepayIntention","DepositCollateralIntention","WithdrawCollateralIntention","OpenObligationIntention","StakeSpoolIntention","UnstakeSpoolIntention","ClaimIncentiveRewardIntention","BorrowWithBoostIntention","StakeScaIntention","ExtendStakePeriodIntention","ExtendPeriodAndStakeMoreIntention","RenewExpStakePeriodIntention","WithdrawStakedScaIntention","SupplyAndStakeLendingIntention","WithdrawAndUnstakeLendingIntention","RedeemScaIntention","MigrateAndClaimIntention","BorrowWithReferralIntention","CreateReferralLinkIntention","ClaimRevenueReferralIntention","BindReferralIntention","MigrateScoinIntention","RepayWithBoostIntention","MigrateWusdcToUsdcIntention","TransactionType","LENDING_MARKET_ID","LENDING_MARKET_TYPE","SuilendClient","phantom","LendingMarket","TransactionType","PACKAGE_ID","MODULE","Decoder","transaction","command","fn","indexFilter","index","commands","coinType","value","TransactionType","Transaction","sortKeys","SuilendBaseIntention","data","BorrowIntention","_BorrowIntention","SuilendBaseIntention","data","input","suiClient","account","suilendClient","obligationOwnerCaps","obligations","transaction","Transaction","Transaction","ClaimRewardsIntention","_ClaimRewardsIntention","SuilendBaseIntention","data","input","suiClient","account","suilendClient","obligationOwnerCaps","obligations","Transaction","Transaction","DepositIntention","_DepositIntention","SuilendBaseIntention","data","input","suiClient","account","suilendClient","obligationOwnerCaps","transaction","Transaction","Transaction","RepayIntention","_RepayIntention","SuilendBaseIntention","data","input","suiClient","account","suilendClient","obligationOwnerCaps","obligations","transaction","Transaction","Transaction","WithdrawIntention","_WithdrawIntention","SuilendBaseIntention","data","input","suiClient","account","suilendClient","obligationOwnerCaps","obligations","transaction","Transaction","getSuilendClient","suiClient","SuilendClient","LendingMarket","phantom","LENDING_MARKET_TYPE","LENDING_MARKET_ID","getObligationOwnerCaps","account","suilendClient","getObligations","obligationOwnerCaps","ownerCap","SuilendAppHelper","input","transaction","result","Decoder","TransactionType","network","txSubType","intentionData","intention","DepositIntention","WithdrawIntention","BorrowIntention","RepayIntention","ClaimRewardsIntention","TransactionType","TurbosSdk","TransactionType","bcs","normalizeStructTag","normalizeSuiAddress","BN","prixConfig","deepbookConfig","getAtoB","layer","target","swap1Layer","swap2Layer","item","Decoder","txb","turbosSdk","config","address","trans","targets","prixConfig","deepbookConfig","moveCall","atob","routes","index","pool","sqrtPrice","nextTickIndex","BN","coinTypeA","coinTypeB","deadline","amountSpecifiedIsInput","amountA","amountB","result","TransactionType","tickLower","tickLowerIsNeg","tickUpper","tickUpperIsNeg","nft","decreaseLiquidity","collectAmountA","collectAmountB","rewardAmounts","helper","poolId","amountIn","token1","token2","MoveCallHelper","_MoveCallHelper","argIndex","input","strVal","normalizeSuiAddress","bcsType","arg","bcsNums","bcs","bcsVal","normalizeStructTag","TurbosSdk","AddLiquidityIntention","_AddLiquidityIntention","BaseIntentionLegacy","data","input","turbosSdk","TurbosSdk","pool","address","amountA","amountB","slippage","tickLower","tickUpper","deadline","txb","TurbosSdk","BurnIntention","_BurnIntention","BaseIntentionLegacy","data","input","turbosSdk","TurbosSdk","pool","nft","txb","TurbosSdk","CollectFeeIntention","_CollectFeeIntention","BaseIntentionLegacy","data","input","turbosSdk","TurbosSdk","pool","address","nft","collectAmountA","collectAmountB","deadline","txb","TurbosSdk","CollectRewardIntention","_CollectRewardIntention","BaseIntentionLegacy","data","input","turbosSdk","TurbosSdk","pool","address","nft","rewardAmounts","deadline","txb","TurbosSdk","CreatePoolIntention","_CreatePoolIntention","BaseIntentionLegacy","data","input","turbosSdk","TurbosSdk","fee","address","tickLower","tickUpper","sqrtPrice","slippage","coinTypeA","coinTypeB","amountA","amountB","deadline","txb","TurbosSdk","DecreaseLiquidityIntention","_DecreaseLiquidityIntention","BaseIntentionLegacy","data","input","turbosSdk","TurbosSdk","pool","address","amountA","amountB","slippage","nft","decreaseLiquidity","deadline","txb","TurbosSdk","IncreaseLiquidityIntention","_IncreaseLiquidityIntention","BaseIntentionLegacy","data","input","turbosSdk","TurbosSdk","pool","address","amountA","amountB","slippage","nft","deadline","txb","TransactionBlock","SUI_CLOCK_OBJECT_ID","PrixClaimIntention","_PrixClaimIntention","BaseIntentionLegacy","data","input","txb","TransactionBlock","prixConfig","SUI_CLOCK_OBJECT_ID","TransactionBlock","PrixJoinIntention","_PrixJoinIntention","BaseIntentionLegacy","data","input","txb","TransactionBlock","prixConfig","TransactionBlock","TurbosSdk","RemoveLiquidityIntention","_RemoveLiquidityIntention","BaseIntentionLegacy","data","input","turbosSdk","TurbosSdk","txb","TransactionBlock","TurbosSdk","SwapIntention","_SwapIntention","BaseIntentionLegacy","data","input","turbosSdk","TurbosSdk","routes","coinTypeA","coinTypeB","address","amountA","amountB","slippage","amountSpecifiedIsInput","deadline","txb","TurbosSdk","normalizeSuiObjectId","TransactionBlock","unstable_getObjectId","SuiKit","turbosSdk","currentAddress","type","amount","coinObjects","coinFields","resultCoinObjects","currentBalance","coinA","coinB","object","coins","txb","sendCoin","mergeCoin","coin","dynamicFields","deepbookConfig","unstable_getObjectId","cap","token","client_order_id","gasBudget","swap_exact_quote_for_base","options","token1","token2","poolId","amountIn","currentAddress","turbosSdk","txb","TransactionBlock","suiKit","SuiKit","coinsData","sendCoin","mergeCoin","currentAccountCap","accountCap","base_coin_ret","quote_coin_ret","_amount","deepbookConfig","normalizeSuiObjectId","swap_exact_base_for_quote","zero","SwapExactBaseForQuoteIntention","_SwapExactBaseForQuoteIntention","BaseIntentionLegacy","data","input","turbosSdk","TurbosSdk","swap_exact_base_for_quote","TurbosSdk","SwapExactQuoteForBaseIntention","_SwapExactQuoteForBaseIntention","BaseIntentionLegacy","data","input","turbosSdk","TurbosSdk","swap_exact_quote_for_base","TURBOSAppHelper","input","turbosSdk","TurbosSdk","contract","transactionBlock","account","result","Decoder","TransactionType","suiClient","network","intention","CreatePoolIntention","AddLiquidityIntention","IncreaseLiquidityIntention","DecreaseLiquidityIntention","RemoveLiquidityIntention","CollectFeeIntention","CollectRewardIntention","BurnIntention","SwapIntention","PrixJoinIntention","PrixClaimIntention","SwapExactBaseForQuoteIntention","SwapExactQuoteForBaseIntention","TransactionType","TransactionType","bcs","normalizeStructTag","normalizeSuiAddress","config","config_default","Decoder","txb","target","trans","config_default","amount","TransactionType","ticketId","moveCall","MoveCallHelper","_MoveCallHelper","argIndex","input","strVal","normalizeSuiAddress","bcsType","arg","bcsNums","bcs","bcsVal","index","normalizeStructTag","TransactionBlock","ClaimTicketIntention","_ClaimTicketIntention","BaseIntentionLegacy","data","input","tx","TransactionBlock","ticketId","config_default","TransactionBlock","StakeIntention","_StakeIntention","BaseIntentionLegacy","data","input","tx","TransactionBlock","amount","coin","config_default","TransactionBlock","UnStakeIntention","_UnStakeIntention","BaseIntentionLegacy","data","input","tx","TransactionBlock","amount","coins","primaryCoin","mergeCoins","coin","config_default","primaryCoinInput","VoloAppHelper","input","transactionBlock","result","Decoder","TransactionType","suiClient","account","intention","StakeIntention","UnStakeIntention","ClaimTicketIntention","appHelpers","MSafeApps","CoreHelper","NAVIAppHelper","MPayAppHelper","PlainTransactionHelper","CetusHelper","TURBOSAppHelper","ScallopAppHelper","VoloAppHelper","BucketHelper","SuilendAppHelper"]}