@sega-so/sega-sdk
Version:
An SDK for building applications on top of SEGA.
1 lines • 221 kB
Source Map (JSON)
{"version":3,"sources":["../../../src/sega/account/account.ts","../../../src/common/accountInfo.ts","../../../src/common/logger.ts","../../../src/common/bignumber.ts","../../../src/module/amount.ts","../../../src/module/formatter.ts","../../../src/module/fraction.ts","../../../src/common/constant.ts","../../../src/sega/token/constant.ts","../../../src/module/token.ts","../../../src/common/pubKey.ts","../../../src/module/currency.ts","../../../src/module/percent.ts","../../../src/module/price.ts","../../../src/common/utility.ts","../../../src/common/lodash.ts","../../../src/common/pda.ts","../../../src/common/txTool/txUtils.ts","../../../src/common/txTool/txType.ts","../../../src/common/programId.ts","../../../src/common/transfer.ts","../../../src/common/txTool/lookupTable.ts","../../../src/common/txTool/txTool.ts","../../../src/common/network.ts","../../../src/sega/moduleBase.ts","../../../src/sega/account/instruction.ts","../../../src/sega/account/util.ts","../../../src/marshmallow/index.ts","../../../src/marshmallow/buffer-layout.ts","../../../src/sega/account/layout.ts"],"sourcesContent":["import { Commitment, PublicKey, SystemProgram, TransactionInstruction } from \"@solana/web3.js\";\nimport { BigNumberish, getATAAddress, InstructionType, WSOLMint } from \"@/common\";\nimport {\n AccountLayout,\n createAssociatedTokenAccountInstruction,\n TOKEN_PROGRAM_ID,\n TOKEN_2022_PROGRAM_ID,\n} from \"@solana/spl-token\";\nimport { AddInstructionParam } from \"@/common/txTool/txTool\";\n\nimport ModuleBase, { ModuleBaseProps } from \"../moduleBase\";\nimport {\n closeAccountInstruction,\n createWSolAccountInstructions,\n initTokenAccountInstruction,\n makeTransferInstruction,\n} from \"./instruction\";\nimport { GetOrCreateTokenAccountParams, HandleTokenAccountParams, TokenAccount, TokenAccountRaw } from \"./types\";\nimport { generatePubKey, parseTokenAccountResp } from \"./util\";\n\nexport interface TokenAccountDataProp {\n tokenAccounts?: TokenAccount[];\n tokenAccountRawInfos?: TokenAccountRaw[];\n notSubscribeAccountChange?: boolean;\n}\nexport default class Account extends ModuleBase {\n private _tokenAccounts: TokenAccount[] = [];\n private _tokenAccountRawInfos: TokenAccountRaw[] = [];\n private _accountChangeListenerId?: number;\n private _accountListener: ((data: TokenAccountDataProp) => void)[] = [];\n private _clientOwnedToken = false;\n private _notSubscribeAccountChange = false;\n private _accountFetchTime = 0;\n\n constructor(params: TokenAccountDataProp & ModuleBaseProps) {\n super(params);\n const { tokenAccounts, tokenAccountRawInfos, notSubscribeAccountChange } = params;\n this._tokenAccounts = tokenAccounts || [];\n this._tokenAccountRawInfos = tokenAccountRawInfos || [];\n this._notSubscribeAccountChange = notSubscribeAccountChange ?? true;\n this._clientOwnedToken = !!(tokenAccounts || tokenAccountRawInfos);\n }\n\n get tokenAccounts(): TokenAccount[] {\n return this._tokenAccounts;\n }\n get tokenAccountRawInfos(): TokenAccountRaw[] {\n return this._tokenAccountRawInfos;\n }\n\n set notSubscribeAccountChange(subscribe: boolean) {\n this._notSubscribeAccountChange = subscribe;\n }\n\n public updateTokenAccount({ tokenAccounts, tokenAccountRawInfos }: TokenAccountDataProp): Account {\n if (tokenAccounts) this._tokenAccounts = tokenAccounts;\n if (tokenAccountRawInfos) this._tokenAccountRawInfos = tokenAccountRawInfos;\n this._accountChangeListenerId && this.scope.connection.removeAccountChangeListener(this._accountChangeListenerId);\n this._accountChangeListenerId = undefined;\n this._clientOwnedToken = true;\n return this;\n }\n\n public addAccountChangeListener(cbk: (data: TokenAccountDataProp) => void): Account {\n this._accountListener.push(cbk);\n return this;\n }\n\n public removeAccountChangeListener(cbk: (data: TokenAccountDataProp) => void): Account {\n this._accountListener = this._accountListener.filter((listener) => listener !== cbk);\n return this;\n }\n\n public getAssociatedTokenAccount(mint: PublicKey, programId?: PublicKey): PublicKey {\n return getATAAddress(this.scope.ownerPubKey, mint, programId).publicKey;\n }\n\n public resetTokenAccounts(): void {\n if (this._clientOwnedToken) return;\n this._tokenAccounts = [];\n this._tokenAccountRawInfos = [];\n }\n\n public async fetchWalletTokenAccounts(config?: { forceUpdate?: boolean; commitment?: Commitment }): Promise<{\n tokenAccounts: TokenAccount[];\n tokenAccountRawInfos: TokenAccountRaw[];\n }> {\n if (\n this._clientOwnedToken ||\n (!config?.forceUpdate &&\n this._tokenAccounts.length &&\n Date.now() - this._accountFetchTime < (this._notSubscribeAccountChange ? 1000 * 5 : 1000 * 60 * 3))\n ) {\n return {\n tokenAccounts: this._tokenAccounts,\n tokenAccountRawInfos: this._tokenAccountRawInfos,\n };\n }\n this.scope.checkOwner();\n\n const defaultConfig = {};\n const customConfig = { ...defaultConfig, ...config };\n\n const [solAccountResp, ownerTokenAccountResp, ownerToken2022AccountResp] = await Promise.all([\n this.scope.connection.getAccountInfo(this.scope.ownerPubKey, customConfig.commitment),\n this.scope.connection.getTokenAccountsByOwner(\n this.scope.ownerPubKey,\n { programId: TOKEN_PROGRAM_ID },\n customConfig.commitment,\n ),\n this.scope.connection.getTokenAccountsByOwner(\n this.scope.ownerPubKey,\n { programId: TOKEN_2022_PROGRAM_ID },\n customConfig.commitment,\n ),\n ]);\n\n const { tokenAccounts, tokenAccountRawInfos } = parseTokenAccountResp({\n owner: this.scope.ownerPubKey,\n solAccountResp,\n tokenAccountResp: {\n context: ownerTokenAccountResp.context,\n value: [...ownerTokenAccountResp.value, ...ownerToken2022AccountResp.value],\n },\n });\n\n this._tokenAccounts = tokenAccounts;\n this._tokenAccountRawInfos = tokenAccountRawInfos;\n\n this._accountFetchTime = Date.now();\n\n if (!this._notSubscribeAccountChange) {\n this._accountChangeListenerId && this.scope.connection.removeAccountChangeListener(this._accountChangeListenerId);\n this._accountChangeListenerId = this.scope.connection.onAccountChange(\n this.scope.ownerPubKey,\n () => {\n this.fetchWalletTokenAccounts({ forceUpdate: true });\n this._accountListener.forEach((cb) =>\n cb({ tokenAccounts: this._tokenAccounts, tokenAccountRawInfos: this._tokenAccountRawInfos }),\n );\n },\n { commitment: config?.commitment },\n );\n }\n\n return { tokenAccounts, tokenAccountRawInfos };\n }\n\n public clearAccountChangeCkb(): void {\n if (this._accountChangeListenerId !== undefined)\n this.scope.connection.removeAccountChangeListener(this._accountChangeListenerId);\n }\n\n // user token account needed, old _selectTokenAccount\n public async getCreatedTokenAccount({\n mint,\n programId = TOKEN_PROGRAM_ID,\n associatedOnly = true,\n }: {\n mint: PublicKey;\n programId?: PublicKey;\n associatedOnly?: boolean;\n }): Promise<PublicKey | undefined> {\n await this.fetchWalletTokenAccounts();\n const tokenAccounts = this._tokenAccounts\n .filter(({ mint: accountMint }) => accountMint?.equals(mint))\n // sort by balance\n .sort((a, b) => (a.amount.lt(b.amount) ? 1 : -1));\n\n const ata = this.getAssociatedTokenAccount(mint, programId);\n for (const tokenAccount of tokenAccounts) {\n const { publicKey } = tokenAccount;\n if (publicKey) {\n if (!associatedOnly || (associatedOnly && ata.equals(publicKey))) return publicKey;\n }\n }\n }\n\n // old _selectOrCreateTokenAccount\n public async getOrCreateTokenAccount(params: GetOrCreateTokenAccountParams): Promise<{\n account?: PublicKey;\n instructionParams?: AddInstructionParam;\n }> {\n await this.fetchWalletTokenAccounts();\n const {\n mint,\n createInfo,\n associatedOnly,\n owner,\n notUseTokenAccount = false,\n skipCloseAccount = false,\n checkCreateATAOwner = false,\n assignSeed,\n } = params;\n const tokenProgram = new PublicKey(params.tokenProgram || TOKEN_PROGRAM_ID);\n const ata = this.getAssociatedTokenAccount(mint, new PublicKey(tokenProgram));\n const accounts = (notUseTokenAccount ? [] : this.tokenAccountRawInfos)\n .filter((i) => i.accountInfo.mint.equals(mint) && (!associatedOnly || i.pubkey.equals(ata)))\n .sort((a, b) => (a.accountInfo.amount.lt(b.accountInfo.amount) ? 1 : -1));\n // find token or don't need create\n if (createInfo === undefined || accounts.length > 0) {\n return accounts.length > 0 ? { account: accounts[0].pubkey } : {};\n }\n\n const newTxInstructions: AddInstructionParam = {\n instructions: [],\n endInstructions: [],\n signers: [],\n instructionTypes: [],\n endInstructionTypes: [],\n };\n\n if (associatedOnly) {\n const _createATAIns = createAssociatedTokenAccountInstruction(owner, ata, owner, mint, tokenProgram);\n const _ataInTokenAcc = this.tokenAccountRawInfos.find((i) => i.pubkey.equals(ata))\n if (checkCreateATAOwner) {\n const ataInfo = await this.scope.connection.getAccountInfo(ata);\n if (ataInfo === null) {\n newTxInstructions.instructions?.push(_createATAIns);\n newTxInstructions.instructionTypes!.push(InstructionType.CreateATA);\n } else if (\n ataInfo.owner.equals(tokenProgram) &&\n AccountLayout.decode(ataInfo.data).mint.equals(mint) &&\n AccountLayout.decode(ataInfo.data).owner.equals(owner)\n ) {\n /* empty */\n } else {\n throw Error(`create ata check error -> mint: ${mint.toString()}, ata: ${ata.toString()}`);\n }\n } else if (_ataInTokenAcc === undefined) {\n newTxInstructions.instructions!.push(_createATAIns);\n newTxInstructions.instructionTypes!.push(InstructionType.CreateATA);\n }\n if (mint.equals(WSOLMint) && createInfo.amount) {\n const txInstruction = await createWSolAccountInstructions({\n connection: this.scope.connection,\n owner: this.scope.ownerPubKey,\n payer: createInfo.payer || this.scope.ownerPubKey,\n amount: createInfo.amount ?? 0,\n skipCloseAccount,\n });\n newTxInstructions.instructions!.push(...(txInstruction.instructions || []));\n newTxInstructions.endInstructions!.push(...(txInstruction.endInstructions || []));\n newTxInstructions.instructionTypes!.push(...(txInstruction.instructionTypes || []));\n newTxInstructions.endInstructionTypes!.push(...(txInstruction.endInstructionTypes || []));\n\n if (createInfo.amount) {\n newTxInstructions.instructions!.push(\n makeTransferInstruction({\n source: txInstruction.addresses.newAccount,\n destination: ata,\n owner: this.scope.ownerPubKey,\n amount: createInfo.amount,\n tokenProgram: TOKEN_PROGRAM_ID,\n }),\n );\n newTxInstructions.instructionTypes!.push(InstructionType.TransferAmount);\n }\n }\n\n if (!skipCloseAccount && _ataInTokenAcc === undefined) {\n newTxInstructions.endInstructions!.push(\n closeAccountInstruction({\n owner,\n payer: createInfo.payer || owner,\n tokenAccount: ata,\n programId: tokenProgram,\n }),\n );\n newTxInstructions.endInstructionTypes!.push(InstructionType.CloseAccount);\n }\n\n return { account: ata, instructionParams: newTxInstructions };\n } else {\n const newTokenAccount = generatePubKey({ fromPublicKey: owner, programId: tokenProgram, assignSeed });\n const balanceNeeded = await this.scope.connection.getMinimumBalanceForRentExemption(AccountLayout.span);\n\n const createAccountIns = SystemProgram.createAccountWithSeed({\n fromPubkey: owner,\n basePubkey: owner,\n seed: newTokenAccount.seed,\n newAccountPubkey: newTokenAccount.publicKey,\n lamports: balanceNeeded + Number(createInfo.amount?.toString() ?? 0),\n space: AccountLayout.span,\n programId: tokenProgram,\n });\n\n newTxInstructions.instructions!.push(\n createAccountIns,\n initTokenAccountInstruction({\n mint,\n tokenAccount: newTokenAccount.publicKey,\n owner: this.scope.ownerPubKey,\n programId: tokenProgram,\n }),\n );\n newTxInstructions.instructionTypes!.push(InstructionType.CreateAccount);\n newTxInstructions.instructionTypes!.push(InstructionType.InitAccount);\n if (!skipCloseAccount) {\n newTxInstructions.endInstructions!.push(\n closeAccountInstruction({\n owner,\n payer: createInfo.payer || owner,\n tokenAccount: newTokenAccount.publicKey,\n programId: tokenProgram,\n }),\n );\n newTxInstructions.endInstructionTypes!.push(InstructionType.CloseAccount);\n }\n return { account: newTokenAccount.publicKey, instructionParams: newTxInstructions };\n }\n // }\n }\n\n public async checkOrCreateAta({\n mint,\n programId = TOKEN_PROGRAM_ID,\n autoUnwrapWSOLToSOL,\n }: {\n mint: PublicKey;\n programId?: PublicKey;\n autoUnwrapWSOLToSOL?: boolean;\n }): Promise<{ pubKey: PublicKey; newInstructions: AddInstructionParam }> {\n await this.fetchWalletTokenAccounts();\n let tokenAccountAddress = this.scope.account.tokenAccounts.find(\n ({ mint: accountTokenMint }) => accountTokenMint?.toBase58() === mint.toBase58(),\n )?.publicKey;\n\n const owner = this.scope.ownerPubKey;\n const newTxInstructions: AddInstructionParam = {};\n\n if (!tokenAccountAddress) {\n const ataAddress = this.getAssociatedTokenAccount(mint, programId);\n const instruction = await createAssociatedTokenAccountInstruction(owner, ataAddress, owner, mint, programId);\n newTxInstructions.instructions = [instruction];\n newTxInstructions.instructionTypes = [InstructionType.CreateATA];\n tokenAccountAddress = ataAddress;\n }\n if (autoUnwrapWSOLToSOL && WSOLMint.toBase58() === mint.toBase58()) {\n newTxInstructions.endInstructions = [\n closeAccountInstruction({ owner, payer: owner, tokenAccount: tokenAccountAddress, programId }),\n ];\n newTxInstructions.endInstructionTypes = [InstructionType.CloseAccount];\n }\n\n return {\n pubKey: tokenAccountAddress,\n newInstructions: newTxInstructions,\n };\n }\n\n // old _handleTokenAccount\n public async handleTokenAccount(\n params: HandleTokenAccountParams,\n ): Promise<AddInstructionParam & { tokenAccount: PublicKey }> {\n const {\n side,\n amount,\n mint,\n programId = TOKEN_PROGRAM_ID,\n tokenAccount,\n payer = this.scope.ownerPubKey,\n bypassAssociatedCheck,\n skipCloseAccount,\n checkCreateATAOwner,\n } = params;\n\n const ata = this.getAssociatedTokenAccount(mint, programId);\n\n if (new PublicKey(WSOLMint).equals(mint)) {\n const txInstruction = await createWSolAccountInstructions({\n connection: this.scope.connection,\n owner: this.scope.ownerPubKey,\n payer,\n amount,\n skipCloseAccount,\n });\n return { tokenAccount: txInstruction.addresses.newAccount, ...txInstruction };\n } else if (!tokenAccount || (side === \"out\" && !ata.equals(tokenAccount) && !bypassAssociatedCheck)) {\n const instructions: TransactionInstruction[] = [];\n const _createATAIns = createAssociatedTokenAccountInstruction(\n this.scope.ownerPubKey,\n ata,\n this.scope.ownerPubKey,\n mint,\n programId,\n );\n\n if (checkCreateATAOwner) {\n const ataInfo = await this.scope.connection.getAccountInfo(ata);\n if (ataInfo === null) {\n instructions.push(_createATAIns);\n } else if (\n ataInfo.owner.equals(TOKEN_PROGRAM_ID) &&\n AccountLayout.decode(ataInfo.data).mint.equals(mint) &&\n AccountLayout.decode(ataInfo.data).owner.equals(this.scope.ownerPubKey)\n ) {\n /* empty */\n } else {\n throw Error(`create ata check error -> mint: ${mint.toString()}, ata: ${ata.toString()}`);\n }\n } else {\n instructions.push(_createATAIns);\n }\n\n return {\n tokenAccount: ata,\n instructions,\n instructionTypes: [InstructionType.CreateATA],\n };\n }\n\n return { tokenAccount };\n }\n\n public async processTokenAccount(props: {\n mint: PublicKey;\n programId?: PublicKey;\n amount?: BigNumberish;\n useSOLBalance?: boolean;\n handleTokenAccount?: boolean;\n feePayer?: PublicKey;\n }): Promise<Promise<AddInstructionParam & { tokenAccount?: PublicKey }>> {\n const { mint, programId = TOKEN_PROGRAM_ID, amount, useSOLBalance, handleTokenAccount, feePayer } = props;\n let tokenAccount: PublicKey | undefined;\n const txBuilder = this.createTxBuilder(feePayer);\n\n if (mint.equals(new PublicKey(WSOLMint)) && useSOLBalance) {\n // mintA\n const { tokenAccount: _tokenAccount, ...instructions } = await this.handleTokenAccount({\n side: \"in\",\n amount: amount || 0,\n mint,\n bypassAssociatedCheck: true,\n programId,\n });\n tokenAccount = _tokenAccount;\n txBuilder.addInstruction(instructions);\n } else {\n tokenAccount = await this.getCreatedTokenAccount({\n mint,\n associatedOnly: false,\n programId,\n });\n if (!tokenAccount && handleTokenAccount) {\n const { tokenAccount: _tokenAccount, ...instructions } = await this.scope.account.handleTokenAccount({\n side: \"in\",\n amount: 0,\n mint,\n bypassAssociatedCheck: true,\n programId,\n });\n tokenAccount = _tokenAccount;\n txBuilder.addInstruction(instructions);\n }\n }\n\n return { tokenAccount, ...txBuilder.AllTxData };\n }\n}\n","import { AccountInfo, Commitment, Connection, PublicKey } from \"@solana/web3.js\";\nimport { ReturnTypeFetchMultipleMintInfos } from \"@/sega/type\";\nimport { WSOLMint, chunkArray, solToWSol } from \"./\";\nimport { createLogger } from \"./logger\";\nimport { MINT_SIZE, TOKEN_PROGRAM_ID, getTransferFeeConfig, unpackMint } from \"@solana/spl-token\";\n\ninterface MultipleAccountsJsonRpcResponse {\n jsonrpc: string;\n id: string;\n error?: {\n code: number;\n message: string;\n };\n result: {\n context: { slot: number };\n value: { data: Array<string>; executable: boolean; lamports: number; owner: string; rentEpoch: number }[];\n };\n}\n\nexport interface GetMultipleAccountsInfoConfig {\n batchRequest?: boolean;\n commitment?: Commitment;\n chunkCount?: number;\n}\n\nconst logger = createLogger(\"Sega_accountInfo_util\");\n\nexport async function getMultipleAccountsInfo(\n connection: Connection,\n publicKeys: PublicKey[],\n config?: GetMultipleAccountsInfoConfig,\n): Promise<(AccountInfo<Buffer> | null)[]> {\n const {\n batchRequest,\n commitment = \"confirmed\",\n chunkCount = 100,\n } = {\n batchRequest: false,\n ...config,\n };\n\n const chunkedKeys = chunkArray(publicKeys, chunkCount);\n let results: (AccountInfo<Buffer> | null)[][] = new Array(chunkedKeys.length).fill([]);\n\n if (batchRequest) {\n const batch = chunkedKeys.map((keys) => {\n const args = connection._buildArgs([keys.map((key) => key.toBase58())], commitment, \"base64\");\n return {\n methodName: \"getMultipleAccounts\",\n args,\n };\n });\n\n const _batch = chunkArray(batch, 10);\n\n const unsafeResponse: MultipleAccountsJsonRpcResponse[] = await (\n await Promise.all(_batch.map(async (i) => await (connection as any)._rpcBatchRequest(i)))\n ).flat();\n results = unsafeResponse.map((unsafeRes: MultipleAccountsJsonRpcResponse) => {\n if (unsafeRes.error)\n logger.logWithError(`failed to get info for multiple accounts, RPC_ERROR, ${unsafeRes.error.message}`);\n\n return unsafeRes.result.value.map((accountInfo) => {\n if (accountInfo) {\n const { data, executable, lamports, owner, rentEpoch } = accountInfo;\n\n if (data.length !== 2 && data[1] !== \"base64\") logger.logWithError(`info must be base64 encoded, RPC_ERROR`);\n\n return {\n data: Buffer.from(data[0], \"base64\"),\n executable,\n lamports,\n owner: new PublicKey(owner),\n rentEpoch,\n };\n }\n return null;\n });\n });\n } else {\n try {\n results = (await Promise.all(\n chunkedKeys.map((keys) => connection.getMultipleAccountsInfo(keys, commitment)),\n )) as (AccountInfo<Buffer> | null)[][];\n } catch (error) {\n if (error instanceof Error) {\n logger.logWithError(`failed to get info for multiple accounts, RPC_ERROR, ${error.message}`);\n }\n }\n }\n\n return results.flat();\n}\n\nexport async function getMultipleAccountsInfoWithCustomFlags<T extends { pubkey: PublicKey }>(\n connection: Connection,\n publicKeysWithCustomFlag: T[],\n config?: GetMultipleAccountsInfoConfig,\n): Promise<({ accountInfo: AccountInfo<Buffer> | null } & T)[]> {\n const multipleAccountsInfo = await getMultipleAccountsInfo(\n connection,\n publicKeysWithCustomFlag.map((o) => o.pubkey),\n config,\n );\n\n return publicKeysWithCustomFlag.map((o, idx) => ({ ...o, accountInfo: multipleAccountsInfo[idx] }));\n}\n\nexport enum AccountType {\n Uninitialized,\n Mint,\n Account,\n}\nexport const ACCOUNT_TYPE_SIZE = 1;\n\nexport async function fetchMultipleMintInfos({\n connection,\n mints,\n config,\n}: {\n connection: Connection;\n mints: PublicKey[];\n config?: { batchRequest?: boolean };\n}): Promise<ReturnTypeFetchMultipleMintInfos> {\n if (mints.length === 0) return {};\n const mintInfos = await getMultipleAccountsInfoWithCustomFlags(\n connection,\n mints.map((i) => ({ pubkey: solToWSol(i) })),\n config,\n );\n\n const mintK: ReturnTypeFetchMultipleMintInfos = {};\n for (const i of mintInfos) {\n if (!i.accountInfo || i.accountInfo.data.length < MINT_SIZE) {\n console.log(\"invalid mint account\", i.pubkey.toBase58());\n continue;\n }\n const t = unpackMint(i.pubkey, i.accountInfo, i.accountInfo?.owner);\n mintK[i.pubkey.toString()] = {\n ...t,\n programId: i.accountInfo?.owner || TOKEN_PROGRAM_ID,\n feeConfig: getTransferFeeConfig(t) ?? undefined,\n };\n }\n mintK[PublicKey.default.toBase58()] = mintK[WSOLMint.toBase58()];\n\n return mintK;\n}\n","import { get, set } from \"lodash\";\n\nexport type ModuleName = \"Common.Api\";\n\nexport enum LogLevel {\n Error,\n Warning,\n Info,\n Debug,\n}\nexport class Logger {\n private logLevel: LogLevel;\n private name: string;\n constructor(params: { name: string; logLevel?: LogLevel }) {\n this.logLevel = params.logLevel !== undefined ? params.logLevel : LogLevel.Error;\n this.name = params.name;\n }\n\n set level(logLevel: LogLevel) {\n this.logLevel = logLevel;\n }\n get time(): string {\n return Date.now().toString();\n }\n get moduleName(): string {\n return this.name;\n }\n\n private isLogLevel(level: LogLevel): boolean {\n return level <= this.logLevel;\n }\n\n public error(...props): Logger {\n if (!this.isLogLevel(LogLevel.Error)) return this;\n console.error(this.time, this.name, \"sdk logger error\", ...props);\n return this;\n }\n\n public logWithError(...props): Logger {\n // this.error(...props)\n const msg = props.map((arg) => (typeof arg === \"object\" ? JSON.stringify(arg) : arg)).join(\", \");\n throw new Error(msg);\n }\n\n public warning(...props): Logger {\n if (!this.isLogLevel(LogLevel.Warning)) return this;\n console.warn(this.time, this.name, \"sdk logger warning\", ...props);\n return this;\n }\n\n public info(...props): Logger {\n if (!this.isLogLevel(LogLevel.Info)) return this;\n console.info(this.time, this.name, \"sdk logger info\", ...props);\n return this;\n }\n\n public debug(...props): Logger {\n if (!this.isLogLevel(LogLevel.Debug)) return this;\n console.debug(this.time, this.name, \"sdk logger debug\", ...props);\n return this;\n }\n}\n\nconst moduleLoggers: { [key in ModuleName]?: Logger } = {};\nconst moduleLevels: { [key in ModuleName]?: LogLevel } = {};\n\nexport function createLogger(moduleName: string): Logger {\n let logger = get(moduleLoggers, moduleName);\n if (!logger) {\n // default level is error\n const logLevel = get(moduleLevels, moduleName);\n\n logger = new Logger({ name: moduleName, logLevel });\n set(moduleLoggers, moduleName, logger);\n }\n\n return logger;\n}\n\nexport function setLoggerLevel(moduleName: string, level: LogLevel): void {\n set(moduleLevels, moduleName, level);\n\n const logger = get(moduleLoggers, moduleName);\n if (logger) logger.level = level;\n}\n","import BN from \"bn.js\";\nimport Decimal from \"decimal.js\";\nimport { CurrencyAmount, TokenAmount } from \"../module/amount\";\nimport { Currency } from \"../module/currency\";\nimport { Fraction } from \"../module/fraction\";\nimport { Percent } from \"../module/percent\";\nimport { Price } from \"../module/price\";\nimport { Token } from \"../module/token\";\nimport { SplToken, TokenJson } from \"@/sega/token/type\";\nimport { ReplaceType } from \"@/sega/type\";\nimport { parseBigNumberish } from \"./constant\";\nimport { mul } from \"./fractionUtil\";\nimport { notInnerObject } from \"./utility\";\n\nexport const BN_ZERO = new BN(0);\nexport const BN_ONE = new BN(1);\nexport const BN_TWO = new BN(2);\nexport const BN_THREE = new BN(3);\nexport const BN_FIVE = new BN(5);\nexport const BN_TEN = new BN(10);\nexport const BN_100 = new BN(100);\nexport const BN_1000 = new BN(1000);\nexport const BN_10000 = new BN(10000);\nexport type BigNumberish = BN | string | number | bigint;\nexport type Numberish = number | string | bigint | Fraction | BN;\n\n\nexport function tenExponential(shift: BigNumberish): BN {\n return BN_TEN.pow(parseBigNumberish(shift));\n}\n\n/**\n *\n * @example\n * getIntInfo(0.34) => { numerator: '34', denominator: '100'}\n * getIntInfo('0.34') //=> { numerator: '34', denominator: '100'}\n */\nexport function parseNumberInfo(n: Numberish | undefined): {\n denominator: string;\n numerator: string;\n sign?: string;\n int?: string;\n dec?: string;\n} {\n if (n === undefined) return { denominator: \"1\", numerator: \"0\" };\n if (n instanceof BN) {\n return { numerator: n.toString(), denominator: \"1\" };\n }\n\n if (n instanceof Fraction) {\n return { denominator: n.denominator.toString(), numerator: n.numerator.toString() };\n }\n\n const s = String(n);\n const [, sign = \"\", int = \"\", dec = \"\"] = s.replace(\",\", \"\").match(/(-?)(\\d*)\\.?(\\d*)/) ?? [];\n const denominator = \"1\" + \"0\".repeat(dec.length);\n const numerator = sign + (int === \"0\" ? \"\" : int) + dec || \"0\";\n return { denominator, numerator, sign, int, dec };\n}\n\n// round up\nexport function divCeil(a: BN, b: BN): BN {\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n const dm = a.divmod(b);\n\n // Fast case - exact division\n if (dm.mod.isZero()) return dm.div;\n\n // Round up\n return dm.div.isNeg() ? dm.div.isubn(1) : dm.div.iaddn(1);\n}\n\nexport function shakeFractionDecimal(n: Fraction): string {\n const [, sign = \"\", int = \"\"] = n.toFixed(2).match(/(-?)(\\d*)\\.?(\\d*)/) ?? [];\n return `${sign}${int}`;\n}\n\nexport function toBN(n: Numberish, decimal: BigNumberish = 0): BN {\n if (n instanceof BN) return n;\n return new BN(shakeFractionDecimal(toFraction(n).mul(BN_TEN.pow(new BN(String(decimal))))));\n}\n\nexport function toFraction(value: Numberish): Fraction {\n // to complete math format(may have decimal), not int\n if (value instanceof Percent) return new Fraction(value.numerator, value.denominator);\n\n if (value instanceof Price) return value.adjusted;\n\n // to complete math format(may have decimal), not BN\n if (value instanceof TokenAmount)\n try {\n return toFraction(value.toExact());\n } catch {\n return new Fraction(BN_ZERO);\n }\n\n // do not ideal with other fraction value\n if (value instanceof Fraction) return value;\n\n // wrap to Fraction\n const n = String(value);\n const details = parseNumberInfo(n);\n return new Fraction(details.numerator, details.denominator);\n}\n\n/**\n * @example\n * toPercent(3.14) // => Percent { 314.00% }\n * toPercent(3.14, { alreadyDecimaled: true }) // => Percent {3.14%}\n */\nexport function toPercent(\n n: Numberish,\n options?: { /* usually used for backend data */ alreadyDecimaled?: boolean },\n): Percent {\n const { numerator, denominator } = parseNumberInfo(n);\n return new Percent(new BN(numerator), new BN(denominator).mul(options?.alreadyDecimaled ? new BN(100) : new BN(1)));\n}\n\nexport function toTokenPrice(params: {\n token: TokenJson | Token | SplToken;\n numberPrice: Numberish;\n decimalDone?: boolean;\n}): Price {\n const { token, numberPrice, decimalDone } = params;\n const usdCurrency = new Token({ mint: \"\", decimals: 6, symbol: \"usd\", name: \"usd\", skipMint: true });\n const { numerator, denominator } = parseNumberInfo(numberPrice);\n const parsedNumerator = decimalDone ? new BN(numerator).mul(BN_TEN.pow(new BN(token.decimals))) : numerator;\n const parsedDenominator = new BN(denominator).mul(BN_TEN.pow(new BN(usdCurrency.decimals)));\n\n return new Price({\n baseToken: usdCurrency,\n denominator: parsedDenominator.toString(),\n quoteToken: new Token({ ...token, skipMint: true, mint: \"\" }),\n numerator: parsedNumerator.toString(),\n });\n}\n\nexport function toUsdCurrency(amount: Numberish): CurrencyAmount {\n const usdCurrency = new Currency({ decimals: 6, symbol: \"usd\", name: \"usd\" });\n const amountBigNumber = toBN(mul(amount, 10 ** usdCurrency.decimals)!);\n return new CurrencyAmount(usdCurrency, amountBigNumber);\n}\n\nexport function toTotalPrice(amount: Numberish | undefined, price: Price | undefined): CurrencyAmount {\n if (!price || !amount) return toUsdCurrency(0);\n return toUsdCurrency(mul(amount, price)!);\n}\n\nexport function decimalToFraction(n: Decimal | undefined): Fraction | undefined {\n if (n == null) return undefined;\n const { numerator, denominator } = parseNumberInfo(n.toString());\n return new Fraction(numerator, denominator);\n}\n\nexport function isDecimal(val: unknown): boolean {\n return val instanceof Decimal;\n}\nexport function recursivelyDecimalToFraction<T>(info: T): ReplaceType<T, Decimal, Fraction> {\n return isDecimal(info)\n ? decimalToFraction(info as any) as ReplaceType<T, Decimal, Fraction>\n : Array.isArray(info)\n ? info.map((k) => recursivelyDecimalToFraction(k)) as ReplaceType<T, Decimal, Fraction>\n : notInnerObject(info)\n ? Object.fromEntries(Object.entries(info as any).map(([k, v]) => [k, recursivelyDecimalToFraction(v)])) as ReplaceType<T, Decimal, Fraction>\n : info as ReplaceType<T, Decimal, Fraction>;\n}\n","import _Big from \"big.js\";\nimport BN from \"bn.js\";\n\nimport { BigNumberish, BN_TEN } from \"../common/bignumber\";\nimport { createLogger, Logger } from \"../common/logger\";\n\nimport { parseBigNumberish, Rounding } from \"../common\";\nimport { Currency } from \"./currency\";\nimport toFormat, { WrappedBig } from \"./formatter\";\nimport { Fraction } from \"./fraction\";\nimport { Token } from \"./token\";\n\nconst logger = createLogger(\"Sega_amount\");\n\nconst Big = toFormat(_Big);\ntype Big = WrappedBig;\n\nexport function splitNumber(num: string, decimals: number): [string, string] {\n let integral = \"0\";\n let fractional = \"0\";\n\n if (num.includes(\".\")) {\n const splited = num.split(\".\");\n if (splited.length === 2) {\n [integral, fractional] = splited;\n fractional = fractional.padEnd(decimals, \"0\");\n } else {\n logger.logWithError(`invalid number string, num: ${num}`);\n }\n } else {\n integral = num;\n }\n\n // fix decimals is 0\n return [integral, fractional.slice(0, decimals) || fractional];\n}\n\nexport class TokenAmount extends Fraction {\n public readonly token: Token;\n protected logger: Logger;\n\n public constructor(token: Token, amount: BigNumberish, isRaw = true, name?: string) {\n let parsedAmount = new BN(0);\n const multiplier = BN_TEN.pow(new BN(token.decimals));\n\n if (isRaw) {\n parsedAmount = parseBigNumberish(amount);\n } else {\n let integralAmount = new BN(0);\n let fractionalAmount = new BN(0);\n\n // parse fractional string\n if (typeof amount === \"string\" || typeof amount === \"number\" || typeof amount === \"bigint\") {\n const [integral, fractional] = splitNumber(amount.toString(), token.decimals);\n integralAmount = parseBigNumberish(integral);\n fractionalAmount = parseBigNumberish(fractional);\n }\n\n integralAmount = integralAmount.mul(multiplier);\n parsedAmount = integralAmount.add(fractionalAmount);\n }\n\n super(parsedAmount, multiplier);\n this.logger = createLogger(name || \"TokenAmount\");\n this.token = token;\n }\n\n public get raw(): BN {\n return this.numerator;\n }\n public isZero(): boolean {\n return this.raw.isZero();\n }\n public gt(other: TokenAmount): boolean {\n if (!this.token.equals(other.token)) this.logger.logWithError(\"gt token not equals\");\n return this.raw.gt(other.raw);\n }\n\n /**\n * a less than b\n */\n public lt(other: TokenAmount): boolean {\n if (!this.token.equals(other.token)) this.logger.logWithError(\"lt token not equals\");\n return this.raw.lt(other.raw);\n }\n\n public add(other: TokenAmount): TokenAmount {\n if (!this.token.equals(other.token)) this.logger.logWithError(\"add token not equals\");\n return new TokenAmount(this.token, this.raw.add(other.raw));\n }\n\n public subtract(other: TokenAmount): TokenAmount {\n if (!this.token.equals(other.token)) this.logger.logWithError(\"sub token not equals\");\n return new TokenAmount(this.token, this.raw.sub(other.raw));\n }\n\n public toSignificant(\n significantDigits = this.token.decimals,\n format?: object,\n rounding: Rounding = Rounding.ROUND_DOWN,\n ): string {\n return super.toSignificant(significantDigits, format, rounding);\n }\n\n /**\n * To fixed\n *\n * @example\n * ```\n * 1 -> 1.000000000\n * 1.234 -> 1.234000000\n * 1.123456789876543 -> 1.123456789\n * ```\n */\n public toFixed(\n decimalPlaces = this.token.decimals,\n format?: object,\n rounding: Rounding = Rounding.ROUND_DOWN,\n ): string {\n if (decimalPlaces > this.token.decimals) this.logger.logWithError(\"decimals overflow\");\n return super.toFixed(decimalPlaces, format, rounding);\n }\n\n /**\n * To exact\n *\n * @example\n * ```\n * 1 -> 1\n * 1.234 -> 1.234\n * 1.123456789876543 -> 1.123456789\n * ```\n */\n public toExact(format: object = { groupSeparator: \"\" }): string {\n Big.DP = this.token.decimals;\n return new Big(this.numerator.toString()).div(this.denominator.toString()).toFormat(format);\n }\n}\n\nexport class CurrencyAmount extends Fraction {\n public readonly currency: Currency;\n protected logger: Logger;\n\n public constructor(currency: Currency, amount: BigNumberish, isRaw = true, name?: string) {\n let parsedAmount = new BN(0);\n const multiplier = BN_TEN.pow(new BN(currency.decimals));\n\n if (isRaw) {\n parsedAmount = parseBigNumberish(amount);\n } else {\n let integralAmount = new BN(0);\n let fractionalAmount = new BN(0);\n\n // parse fractional string\n if (typeof amount === \"string\" || typeof amount === \"number\" || typeof amount === \"bigint\") {\n const [integral, fractional] = splitNumber(amount.toString(), currency.decimals);\n integralAmount = parseBigNumberish(integral);\n fractionalAmount = parseBigNumberish(fractional);\n }\n\n integralAmount = integralAmount.mul(multiplier);\n parsedAmount = integralAmount.add(fractionalAmount);\n }\n\n super(parsedAmount, multiplier);\n this.logger = createLogger(name || \"TokenAmount\");\n this.currency = currency;\n }\n\n public get raw(): BN {\n return this.numerator;\n }\n\n public isZero(): boolean {\n return this.raw.isZero();\n }\n\n /**\n * a greater than b\n */\n public gt(other: CurrencyAmount): boolean {\n if (!this.currency.equals(other.currency)) this.logger.logWithError(\"gt currency not equals\");\n return this.raw.gt(other.raw);\n }\n\n /**\n * a less than b\n */\n public lt(other: CurrencyAmount): boolean {\n if (!this.currency.equals(other.currency)) this.logger.logWithError(\"lt currency not equals\");\n return this.raw.lt(other.raw);\n }\n\n public add(other: CurrencyAmount): CurrencyAmount {\n if (!this.currency.equals(other.currency)) this.logger.logWithError(\"add currency not equals\");\n return new CurrencyAmount(this.currency, this.raw.add(other.raw));\n }\n\n public sub(other: CurrencyAmount): CurrencyAmount {\n if (!this.currency.equals(other.currency)) this.logger.logWithError(\"sub currency not equals\");\n return new CurrencyAmount(this.currency, this.raw.sub(other.raw));\n }\n\n public toSignificant(\n significantDigits = this.currency.decimals,\n format?: object,\n rounding: Rounding = Rounding.ROUND_DOWN,\n ): string {\n return super.toSignificant(significantDigits, format, rounding);\n }\n\n /**\n * To fixed\n *\n * @example\n * ```\n * 1 -> 1.000000000\n * 1.234 -> 1.234000000\n * 1.123456789876543 -> 1.123456789\n * ```\n */\n public toFixed(\n decimalPlaces = this.currency.decimals,\n format?: object,\n rounding: Rounding = Rounding.ROUND_DOWN,\n ): string {\n if (decimalPlaces > this.currency.decimals) this.logger.logWithError(\"decimals overflow\");\n\n return super.toFixed(decimalPlaces, format, rounding);\n }\n\n /**\n * To exact\n *\n * @example\n * ```\n * 1 -> 1\n * 1.234 -> 1.234\n * 1.123456789876543 -> 1.123456789\n * ```\n */\n public toExact(format: object = { groupSeparator: \"\" }): string {\n Big.DP = this.currency.decimals;\n return new Big(this.numerator.toString()).div(this.denominator.toString()).toFormat(format);\n }\n}\n","import Big, { BigConstructor, BigSource, RoundingMode } from \"big.js\";\nimport Decimal, { Config, Numeric } from \"decimal.js-light\";\nimport _toFarmat from \"toformat\";\n\ntype TakeStatic<T> = { [P in keyof T]: T[P] };\ninterface FormatOptions {\n decimalSeparator?: string;\n groupSeparator?: string;\n groupSize?: number;\n fractionGroupSeparator?: string;\n fractionGroupSize?: number;\n}\ninterface WrappedBigConstructor extends TakeStatic<BigConstructor> {\n new (value: BigSource): WrappedBig;\n (value: BigSource): WrappedBig;\n (): WrappedBigConstructor;\n\n format: FormatOptions;\n}\nexport interface WrappedBig extends Big {\n add(n: BigSource): WrappedBig;\n abs(): WrappedBig;\n div(n: BigSource): WrappedBig;\n minus(n: BigSource): WrappedBig;\n mod(n: BigSource): WrappedBig;\n mul(n: BigSource): WrappedBig;\n plus(n: BigSource): WrappedBig;\n pow(exp: number): WrappedBig;\n round(dp?: number, rm?: RoundingMode): WrappedBig;\n sqrt(): WrappedBig;\n sub(n: BigSource): WrappedBig;\n times(n: BigSource): WrappedBig;\n toFormat(): string;\n toFormat(options: FormatOptions): string;\n toFormat(fractionLength: number): string;\n toFormat(fractionLength: number, options: FormatOptions): string;\n toFormat(fractionLength: number, missionUnknown: number): string;\n toFormat(fractionLength: number, missionUnknown: number, options: FormatOptions): string;\n}\n\ntype DecimalConstructor = typeof Decimal;\ninterface WrappedDecimalConstructor extends TakeStatic<DecimalConstructor> {\n new (value: Numeric): WrappedDecimal;\n clone(config?: Config): WrappedDecimalConstructor;\n config(config: Config): WrappedDecimal;\n set(config: Config): WrappedDecimal;\n format: FormatOptions;\n}\nexport interface WrappedDecimal extends Decimal {\n absoluteValue(): WrappedDecimal;\n abs(): WrappedDecimal;\n dividedBy(y: Numeric): WrappedDecimal;\n div(y: Numeric): WrappedDecimal;\n dividedToIntegerBy(y: Numeric): WrappedDecimal;\n idiv(y: Numeric): WrappedDecimal;\n logarithm(base?: Numeric): WrappedDecimal;\n log(base?: Numeric): WrappedDecimal;\n minus(y: Numeric): WrappedDecimal;\n sub(y: Numeric): WrappedDecimal;\n modulo(y: Numeric): WrappedDecimal;\n mod(y: Numeric): WrappedDecimal;\n naturalExponetial(): WrappedDecimal;\n exp(): WrappedDecimal;\n naturalLogarithm(): WrappedDecimal;\n ln(): WrappedDecimal;\n negated(): WrappedDecimal;\n neg(): WrappedDecimal;\n plus(y: Numeric): WrappedDecimal;\n add(y: Numeric): WrappedDecimal;\n squareRoot(): WrappedDecimal;\n sqrt(): WrappedDecimal;\n times(y: Numeric): WrappedDecimal;\n mul(y: Numeric): WrappedDecimal;\n toWrappedDecimalPlaces(dp?: number, rm?: number): WrappedDecimal;\n todp(dp?: number, rm?: number): WrappedDecimal;\n toInteger(): WrappedDecimal;\n toint(): WrappedDecimal;\n toPower(y: Numeric): WrappedDecimal;\n pow(y: Numeric): WrappedDecimal;\n toSignificantDigits(sd?: number, rm?: number): WrappedDecimal;\n tosd(sd?: number, rm?: number): WrappedDecimal;\n toFormat(options: FormatOptions): string;\n toFormat(fractionLength: number): string;\n toFormat(fractionLength: number, options: FormatOptions): string;\n toFormat(fractionLength: number, missionUnknown: number): string;\n toFormat(fractionLength: number, missionUnknown: number, options: FormatOptions): string;\n}\n\nconst toFormat: {\n (fn: BigConstructor): WrappedBigConstructor;\n (fn: DecimalConstructor): WrappedDecimalConstructor;\n} = _toFarmat;\nexport default toFormat;\n","import _Big from \"big.js\";\nimport BN from \"bn.js\";\nimport _Decimal from \"decimal.js-light\";\n\nimport { BigNumberish } from \"../common/bignumber\";\nimport { createLogger } from \"../common/logger\";\n\nimport { parseBigNumberish, Rounding } from \"../common/constant\";\nimport toFormat, { WrappedBig } from \"./formatter\";\n\nconst logger = createLogger(\"module/fraction\");\n\nconst Big = toFormat(_Big);\ntype Big = WrappedBig;\n\nconst Decimal = toFormat(_Decimal);\n\nconst toSignificantRounding = {\n [Rounding.ROUND_DOWN]: Decimal.ROUND_DOWN,\n [Rounding.ROUND_HALF_UP]: Decimal.ROUND_HALF_UP,\n [Rounding.ROUND_UP]: Decimal.ROUND_UP,\n};\n\nconst toFixedRounding = {\n [Rounding.ROUND_DOWN]: _Big.roundDown,\n [Rounding.ROUND_HALF_UP]: _Big.roundHalfUp,\n [Rounding.ROUND_UP]: _Big.roundUp,\n};\n\nexport class Fraction {\n public readonly numerator: BN;\n public readonly denominator: BN;\n\n public constructor(numerator: BigNumberish, denominator: BigNumberish = new BN(1)) {\n this.numerator = parseBigNumberish(numerator);\n this.denominator = parseBigNumberish(denominator);\n }\n\n public get quotient(): BN {\n return this.numerator.div(this.denominator);\n }\n\n public invert(): Fraction {\n return new Fraction(this.denominator, this.numerator);\n }\n\n public add(other: Fraction | BigNumberish): Fraction {\n const otherParsed = other instanceof Fraction ? other : new Fraction(parseBigNumberish(other));\n\n if (this.denominator.eq(otherParsed.denominator)) {\n return new Fraction(this.numerator.add(otherParsed.numerator), this.denominator);\n }\n\n return new Fraction(\n this.numerator.mul(otherParsed.denominator).add(otherParsed.numerator.mul(this.denominator)),\n this.denominator.mul(otherParsed.denominator),\n );\n }\n\n public sub(other: Fraction | BigNumberish): Fraction {\n const otherParsed = other instanceof Fraction ? other : new Fraction(parseBigNumberish(other));\n\n if (this.denominator.eq(otherParsed.denominator)) {\n return new Fraction(this.numerator.sub(otherParsed.numerator), this.denominator);\n }\n\n return new Fraction(\n this.numerator.mul(otherParsed.denominator).sub(otherParsed.numerator.mul(this.denominator)),\n this.denominator.mul(otherParsed.denominator),\n );\n }\n\n public mul(other: Fraction | BigNumberish): Fraction {\n const otherParsed = other instanceof Fraction ? other : new Fraction(parseBigNumberish(other));\n\n return new Fraction(this.numerator.mul(otherParsed.numerator), this.denominator.mul(otherParsed.denominator));\n }\n\n public div(other: Fraction | BigNumberish): Fraction {\n const otherParsed = other instanceof Fraction ? other : new Fraction(parseBigNumberish(other));\n\n return new Fraction(this.numerator.mul(otherParsed.denominator), this.denominator.mul(otherParsed.numerator));\n }\n\n public toSignificant(\n significantDigits: number,\n format: object = { groupSeparator: \"\" },\n rounding: Rounding = Rounding.ROUND_HALF_UP,\n ): string {\n if (!Number.isInteger(significantDigits)) logger.logWithError(`${significantDigits} is not an integer.`);\n if (significantDigits <= 0) logger.logWithError(`${significantDigits} is not positive.`);\n\n Decimal.set({ precision: significantDigits + 1, rounding: toSignificantRounding[rounding] });\n const quotient = new Decimal(this.numerator.toString())\n .div(this.denominator.toString())\n .toSignificantDigits(significantDigits);\n return quotient.toFormat(quotient.decimalPlaces(), format);\n }\n\n public toFixed(\n decimalPlaces: number,\n format: object = { groupSeparator: \"\" },\n rounding: Rounding = Rounding.ROUND_HALF_UP,\n ): string {\n if (!Number.isInteger(decimalPlaces)) logger.logWithError(`${decimalPlaces} is not an integer.`);\n if (decimalPlaces < 0) logger.logWithError(`${decimalPlaces} is negative.`);\n\n Big.DP = decimalPlaces;\n Big.RM = toFixedRounding[rounding] || 1;\n return new Big(this.numerator.toString()).div(this.denominator.toString()).toFormat(decimalPlaces, format);\n }\n\n public isZero(): boolean {\n return this.numerator.isZero();\n }\n}\n","import BN from \"bn.js\";\nimport { BigNumberish } from \"./bignumber\";\nimport { createLogger } from \"./logger\";\n\nexport enum Rounding {\n ROUND_DOWN,\n ROUND_HALF_UP,\n ROUND_UP,\n}\n\nconst MAX_SAFE = 0x1fffffffffffff;\n\nexport function parseBigNumberish(value: BigNumberish): BN {\n const logger = createLogger(\"Sega_parseBigNumberish\");\n // BN\n if (value instanceof BN) {\n return value;\n }\n\n if (typeof value === \"string\") {\n if (value.match(/^-?[0-9]+$/)) {\n return new BN(value);\n }\n logger.logWithError(`invalid BigNumberish string: ${value}`);\n }\n\n if (typeof value === \"number\") {\n if (value % 1) {\n logger.logWithError(`BigNumberish number underflow: ${value}`);\n }\n\n if (value >= MAX_SAFE || value <= -MAX_SAFE) {\n logger.logWithError(`BigNumberish number overflow: ${value}`);\n }\n\n return new BN(String(value));\n }\n\n if (typeof value === \"bigint\") {\n return new BN(value.toString());\n }\n logger.error(`invalid BigNumberish value: ${value}`);\n return new BN(0); // never reach, because logWithError will throw error\n}\n","import { PublicKey } from \"@solana/web3.js\";\nimport { TOKEN_PROGRAM_ID } from \"@solana/spl-token\";\nimport { TokenInfo } from \"./type\";\n\nexport const SOL_INFO: TokenInfo = {\n chainId: 101,\n address: PublicKey.default.toBase58(),\n programId: TOKEN_PROGRAM_ID.toBase58(),\n decimals: 9,\n symbol: \"SOL\",\n name: \"solana\",\n logoURI: `https://img-v1.raydium.io/icon/So11111111111111111111111111111111111111112.png`,\n tags: [],\n priority: 2,\n type: \"sega\",\n extensions: {\n coingeckoId: \"solana\",\n },\n};\n\nexport const TOKEN_WSOL: TokenInfo = {\n chainId: 101,\n address: \"So11111111111111111111111111111111111111112\",\n programId: TOKEN_PROGRAM_ID.toBase58(),\n decimals: 9,\n symbol: \"WSOL\",\n name: \"Wrapped SOL\",\n logoURI: `https://img-v1.raydium.io/icon/So11111111111111111111111111111111111111112.png`,\n tags: [],\n priority: 2,\n type: \"sega\",\n extensions: {\n coingeckoId: \"solana\",\n },\n};\n","import { PublicKey } from \"@solana/web3.js\";\n\nimport { PublicKeyish, SOLMint, validateAndParsePublicKey } from \"../common/pubKey\";\nimport { TOKEN_WSOL } from \"@/sega/token/constant\";\n\n/**\n * A token is any fungible financial instrument on Solana, including SOL and all SPL tokens.\n */\nexport interface TokenProps {\n mint: PublicKeyish;\n decimals: number;\n symbol?: string;\n name?: string;\n skipMint?: boolean;\n isToken2022?: boolean;\n}\n\nexport class Token {\n public readonly symbol?: string;\n public readonly name?: string;\n public readonly decimals: number;\n public readonly isToken2022: boolean;\n\n public readonly mint: PublicKey;\n public static readonly WSOL: Token = new Token({\n ...TOKEN_WSOL,\n mint: TOKEN_WSOL.address,\n });\n\n /**\n *\n * @param mint - pass \"sol\" as mint will auto generate wsol token config\n */\n public constructor({ mint, decimals, symbol, name, skipMint = false, isToken2022 = false }: TokenProps) {\n if (mint === SOLMint.toBase58() || (mint instanceof PublicKey && SOL