UNPKG

goosefx-amm-sdk

Version:

SDK for the GooseFx AMM

1 lines 381 kB
{"version":3,"sources":["../../../src/gfx/account/account.ts","../../../src/common/logger.ts","../../../src/common/utility.ts","../../../src/module/amount.ts","../../../src/common/number.ts","../../../src/module/formatter.ts","../../../src/module/fraction.ts","../../../src/gfx/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/bignumber.ts","../../../node_modules/decimal.js/decimal.mjs","../../../src/common/txTool/txTool.ts","../../../src/common/txTool/txType.ts","../../../src/common/txTool/txUtils.ts","../../../src/common/txTool/lookupTable.ts","../../../src/common/accountInfo.ts","../../../src/common/lodash.ts","../../../src/common/programId.ts","../../../src/common/pda.ts","../../../src/common/transfer.ts","../../../src/gfx/moduleBase.ts","../../../src/gfx/account/instruction.ts","../../../src/gfx/account/util.ts","../../../src/gfx/account/layout.ts","../../../node_modules/@noble/hashes/src/utils.ts","../../../node_modules/@noble/hashes/src/_md.ts","../../../node_modules/@noble/hashes/src/sha2.ts","../../../node_modules/@noble/hashes/src/sha256.ts"],"sourcesContent":["import {\n createAssociatedTokenAccountInstruction,\n TOKEN_PROGRAM_ID,\n AccountLayout,\n TOKEN_2022_PROGRAM_ID,\n} from \"@solana/spl-token\";\nimport { Commitment, PublicKey, SystemProgram, TransactionInstruction } from \"@solana/web3.js\";\nimport { getATAAddress, BigNumberish, InstructionType, WSOLMint } from \"@/common\";\nimport { AddInstructionParam } from \"@/common/txTool/txTool\";\n\nimport ModuleBase, { ModuleBaseProps } from \"../moduleBase\";\nimport {\n closeAccountInstruction,\n createWSolAccountInstructions,\n makeTransferInstruction,\n initTokenAccountInstruction,\n} from \"./instruction\";\nimport { HandleTokenAccountParams, TokenAccount, TokenAccountRaw, GetOrCreateTokenAccountParams } from \"./types\";\nimport { parseTokenAccountResp, generatePubKey } from \"./util\";\nimport BN from \"bn.js\";\n\nexport interface TokenAccountDataProp {\n tokenAccounts?: TokenAccount[];\n tokenAccountRawInfos?: TokenAccountRaw[];\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 _accountFetchTime = 0;\n\n constructor(params: TokenAccountDataProp & ModuleBaseProps) {\n super(params);\n const { tokenAccounts, tokenAccountRawInfos } = params;\n this._tokenAccounts = tokenAccounts || [];\n this._tokenAccountRawInfos = tokenAccountRawInfos || [];\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 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 && this._tokenAccounts.length && Date.now() - this._accountFetchTime < 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 this._accountChangeListenerId && this.scope.connection.removeAccountChangeListener(this._accountChangeListenerId);\n this._accountChangeListenerId = this.scope.connection.onAccountChange(\n this.scope.ownerPubKey,\n () => this.fetchWalletTokenAccounts({ forceUpdate: true }),\n config?.commitment,\n );\n\n return { tokenAccounts, tokenAccountRawInfos };\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 } = 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) => (new BN(a.accountInfo.amount.toString()).lt(new BN(b.accountInfo.amount.toString())) ? 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 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(new Uint8Array(ataInfo.data)).mint.equals(mint) &&\n AccountLayout.decode(new Uint8Array(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 {\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) {\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 // if (mint.equals(WSOLMint)) {\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.signers!.push(...(txInstruction.signers || []));\n // newTxInstructions.instructionTypes!.push(...(txInstruction.instructionTypes || []));\n // newTxInstructions.endInstructionTypes!.push(...(txInstruction.endInstructionTypes || []));\n\n // return { account: txInstruction.addresses.newAccount, instructionParams: newTxInstructions };\n // } else {\n const newTokenAccount = generatePubKey({ fromPublicKey: owner, programId: tokenProgram });\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(new Uint8Array(ataInfo.data)).mint.equals(mint) &&\n AccountLayout.decode(new Uint8Array(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 }): Promise<Promise<AddInstructionParam & { tokenAccount?: PublicKey }>> {\n const { mint, programId = TOKEN_PROGRAM_ID, amount, useSOLBalance, handleTokenAccount } = props;\n let tokenAccount: PublicKey | undefined;\n const txBuilder = this.createTxBuilder();\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 { 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: unknown[]): 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: unknown[]): 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: unknown[]): 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: unknown[]): 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: unknown[]): 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 { PublicKey } from \"@solana/web3.js\";\nimport BN from \"bn.js\";\n\nimport { Fraction, Percent, Price, Token, TokenAmount } from \"../module\";\nimport { ReplaceType } from \"../gfx/type\";\n\nimport { tryParsePublicKey } from \"./pubKey\";\n\nexport async function sleep(ms: number): Promise<void> {\n new Promise((resolve) => setTimeout(resolve, ms));\n}\n\nexport function getTimestamp(): number {\n return new Date().getTime();\n}\n\nexport function notInnerObject(v: unknown): v is Record<string, any> {\n return (\n typeof v === \"object\" &&\n v !== null &&\n ![Token, TokenAmount, PublicKey, Fraction, BN, Price, Percent].some((o) => typeof o === \"object\" && v instanceof o)\n );\n}\n\nexport function jsonInfo2PoolKeys<T>(jsonInfo: T): ReplaceType<T, string, PublicKey> {\n return (typeof jsonInfo === \"string\"\n ? tryParsePublicKey(jsonInfo)\n : Array.isArray(jsonInfo)\n ? jsonInfo.map((k) => jsonInfo2PoolKeys(k))\n : notInnerObject(jsonInfo)\n ? Object.fromEntries(Object.entries(jsonInfo).map(([k, v]) => [k, jsonInfo2PoolKeys(v)]))\n : jsonInfo) as any as ReplaceType<T, string, PublicKey>;\n}\n","import _Big from \"big.js\";\nimport BN from \"bn.js\";\n\nimport { BigNumberish, BN_TEN, parseBigNumberish, Rounding } from \"../common/number\";\n\nimport { createLogger, Logger } from \"../common/logger\";\n\nimport toFormat, { WrappedBig } from \"./formatter\";\nimport { Fraction } from \"./fraction\";\nimport { Token } from \"./token\";\nimport { Currency } from \"./currency\";\n\nconst logger = createLogger(\"Gfx_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 BN from \"bn.js\";\nimport { createLogger } from \"./logger\";\n\nexport enum Rounding {\n ROUND_DOWN,\n ROUND_HALF_UP,\n ROUND_UP,\n}\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;\n\nconst MAX_SAFE = 0x1fffffffffffff;\n\nexport function parseBigNumberish(value: BigNumberish): BN {\n const logger = createLogger(\"Gfx_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\nexport function tenExponential(shift: BigNumberish): BN {\n return BN_TEN.pow(parseBigNumberish(shift));\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, parseBigNumberish, Rounding } from \"../common/number\";\n\nimport { createLogger } from \"../common/logger\";\n\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 { TOKEN_PROGRAM_ID } from \"@solana/spl-token\";\nimport { TokenInfo } from \"./type\";\n\nexport const SOL_INFO: TokenInfo = {\n address: \"So11111111111111111111111111111111111111112\",\n programId: TOKEN_PROGRAM_ID.toBase58(),\n decimals: 9,\n symbol: \"SOL\",\n name: \"solana\",\n logoURI: ``,\n tags: [],\n priority: 2,\n type: \"goose-fx\",\n extensions: {\n coingeckoId: \"solana\",\n },\n};\n\nexport const TOKEN_WSOL: TokenInfo = {\n address: \"So11111111111111111111111111111111111111112\",\n programId: TOKEN_PROGRAM_ID.toBase58(),\n decimals: 9,\n symbol: \"WSOL\",\n name: \"Wrapped SOL\",\n logoURI: ``,\n tags: [],\n priority: 2,\n type: \"goose-fx\",\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 \"../gfx/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 && SOLMint.equals(mint))) {\n this.decimals = TOKEN_WSOL.decimals;\n this.symbol = TOKEN_WSOL.symbol;\n this.name = TOKEN_WSOL.name;\n this.mint = new PublicKey(TOKEN_WSOL.address);\n this.isToken2022 = false;\n return;\n }\n\n this.decimals = decimals;\n this.symbol = symbol || mint.toString().substring(0, 6);\n this.name = name || mint.toString().substring(0, 6);\n this.mint = skipMint ? PublicKey.default : validateAndParsePublicKey({ publicKey: mint });\n this.isToken2022 = isToken2022;\n }\n\n public equals(other: Token): boolean {\n // short circuit on reference equality\n if (this === other) {\n return true;\n }\n return this.mint.equals(other.mint);\n }\n}\n","import { TOKEN_PROGRAM_ID } from \"@solana/spl-token\";\nimport { AccountMeta, PublicKey, SystemProgram, SYSVAR_RENT_PUBKEY } from \"@solana/web3.js\";\n\ninterface AccountMetaProps {\n pubkey: PublicKey;\n isSigner?: boolean;\n isWritable?: boolean;\n}\n\nexport function accountMeta({ pubkey, isSigner = false, isWritable = true }: AccountMetaProps): AccountMeta {\n return {\n pubkey,\n isWritable,\n isSigner,\n };\n}\n\nexport const commonSystemAccountMeta = [\n accountMeta({ pubkey: TOKEN_PROGRAM_ID, isWritable: false }),\n accountMeta({ pubkey: SystemProgram.programId, isWritable: false }),\n accountMeta({ pubkey: SYSVAR_RENT_PUBKEY, isWritable: false }),\n];\n\nexport type PublicKeyish = PublicKey | string;\n\nexport function validateAndParsePublicKey({\n publicKey: orgPubKey,\n transformSol,\n}: {\n publicKey: PublicKeyish;\n transformSol?: boolean;\n}): PublicKey {\n const publicKey = tryParsePublicKey(orgPubKey.toString());\n\n if (publicKey instanceof PublicKey) {\n if (transformSol && publicKey.equals(SOLMint)) return WSOLMint;\n return publicKey;\n }\n\n if (transformSol && publicKey.toString() === SOLMint.toBase58()) return WSOLMint;\n\n if (typeof publicKey === \"string\") {\n if (publicKey === PublicKey.default.toBase58()) return PublicKey.default;\n try {\n const key = new PublicKey(publicKey);\n return key;\n } catch {\n throw new Error(\"invalid public key\");\n }\n }\n\n throw new Error(\"invalid public key\");\n}\n\nexport function tryParsePublicKey(v: string): PublicKey | string {\n try {\n return new PublicKey(v);\n } catch (e) {\n return v;\n }\n}\n\nexport const MEMO_PROGRAM_ID = new PublicKey(\"MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr\");\nexport const MEMO_PROGRAM_ID2 = new PublicKey(\"MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr\");\nexport const RENT_PROGRAM_ID = new PublicKey(\"SysvarRent111111111111111111111111111111111\");\nexport const CLOCK_PROGRAM_ID = new PublicKey(\"SysvarC1ock11111111111111111111111111111111\");\nexport const METADATA_PROGRAM_ID = new PublicKey(\"metaqbxxUerdq28cj1RbAWkYQm3ybzjb6a8bt518x1s\");\nexport const INSTRUCTION_PROGRAM_ID = new PublicKey(\"Sysvar1nstructions1111111111111111111111111\");\nexport const SYSTEM_PROGRAM_ID = SystemProgram.programId;\n\nexport const RAYMint = new PublicKey(\"4k3Dyjzvzp8eMZWUXbBCjEvwSkkk59S5iCNLY3QrkX6R\");\nexport const PAIMint = new PublicKey(\"Ea5SjE2Y6yvCeW5dYTn7PYMuW5ikXkvbGdcmSnXeaLjS\");\nexport const SRMMint = new PublicKey(\"SRMuApVNdxXokk5GT7XD5cUUgXMBCoAz2LHeuAoKWRt\");\nexport const USDCMint = new PublicKey(\"EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v\");\nexport const USDTMint = new PublicKey(\"Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB\");\nexport const mSOLMint = new PublicKey(\"mSoLzYCxHdYgdzU16g5QSh3i5K3z3KZK7ytfqcJm7So\");\nexport const stSOLMint = new PublicKey(\"7dHbWXmci3dT8UFYWYZweBLXgycu7Y3iL6trKn1Y7ARj\");\nexport const USDHMint = new PublicKey(\"USDH1SM1ojwWUga67PGrgFWUHibbjqMvuMaDkRJTgkX\");\nexport const NRVMint = new PublicKey(\"NRVwhjBQiUPYtfDT5zRBVJajzFQHaBUNtC7SNVvqRFa\");\nexport const ANAMint = new PublicKey(\"ANAxByE6G2WjFp7A4NqtWYXb3mgruyzZYg3spfxe6Lbo\");\nexport const ETHMint = new PublicKey(\"7vfCXTUXx5WJV5JADk17DUJ4ksgau7utNKj4b963voxs\");\nexport const WSOLMint = new PublicKey(\"So11111111111111111111111111111111111111112\");\nexport const SOLMint = PublicKey.default;\n\nexport function solToWSol(mint: PublicKeyish): PublicKey {\n return validateAndParsePublicKey({ publicKey: mint, transformSol: true });\n}\n","import { SOL_INFO } from \"../gfx/token/constant\";\n\nimport { Token } from \"./token\";\n\ninterface CurrencyProps {\n decimals: number;\n symbol?: string;\n name?: string;\n}\n/**\n * A currency is any fungible financial instrument on Solana, including SOL and all SPL tokens.\n * The only instance of the base class `Currency` is SOL.\n */\nexport class Currency {\n public readonly symbol?: string;\n public readonly name?: string;\n public readonly decimals: number;\n\n /**\n * The only instance of the base class `Currency`.\n */\n public static readonly SOL: Currency = new Currency(SOL_INFO);\n\n /**\n * Constructs an instance of the base class `Currency`. The only instance of the base class `Currency` is `Currency.SOL`.\n * @param decimals - decimals of the currency\n * @param symbol - symbol of the currency\n * @param name - name of the currency\n */\n public constructor({ decimals, symbol = \"UNKNOWN\", name = \"UNKNOWN\" }: CurrencyProps) {\n this.decimals = decimals;\n this.symbol = symbol;\n this.name = name;\n }\n\n public equals(other: Currency): boolean {\n return this === other;\n }\n}\n\n/**\n * Compares two currencies for equality\n */\nexport function currencyEquals(currencyA: Currency, currencyB: Currency): boolean {\n if (currencyA instanceof Token && currencyB instanceof Token) {\n return currencyA.equals(currencyB);\n } else if (currencyA instanceof Token || currencyB instanceof Token) {\n return false;\n } else {\n return currencyA === currencyB;\n }\n}\n","import { Rounding } from \"../common/number\";\nimport BN from \"bn.js\";\nimport { Fraction } from \"./fraction\";\n\nexport const _100_PERCENT = new Fraction(new BN(100));\n\nexport class Percent extends Fraction {\n public toSignificant(significantDigits = 5, format?: object, rounding?: Rounding): string {\n return this.mul(_100_PERCENT).toSignificant(significantDigits, format, rounding);\n }\n\n public toFixed(decimalPlaces = 2, format?: object, rounding?: Rounding): string {\n return this.mul(_100_PERCENT).toFixed(decimalPlaces, format, rounding);\n }\n}\n","import { BigNumberish, Rounding, tenExponential } from \"../common/number\";\nimport { createLogger } from \"../common/logger\";\n\nimport { Fraction } from \"./fraction\";\nimport { Token } from \"./token\";\n\nconst logger = createLogger(\"Ray_price\");\n\ninterface PriceProps {\n baseToken: Token;\n denominator: BigNumberish;\n quoteToken: Token;\n numerator: BigNumberish;\n}\n\nexport class Price extends Fraction {\n public readonly baseToken: Token; // input i.e. denominator\n public readonly quoteToken: Token; // output i.e. numerator\n // used to adjust the raw fraction w/r/t the decimals of the {base,quote}Token\n public readonly scalar: Fraction;\n\n // denominator and numerator _must_ be raw, i.e. in the native representation\n public constructor(params: PriceProps) {\n const { baseToken, quoteToken, numerator, denominator } = params;\n super(numerator, denominator);\n\n this.baseToken = baseToken;\n this.quoteToken = quoteToken;\n this.scalar = new Fraction(tenExponential(baseToken.decimals), tenExponential(quoteToken.decimals));\n }\n\n public get raw(): Fraction {\n return new Fraction(this.numerator, this.denominator);\n }\n\n public get adjusted(): Fraction {\n return super.mul(this.scalar);\n }\n\n public invert(): Price {\n return new Price({\n baseToken: this.quoteToken,\n quoteToken: this.baseToken,\n denominator: this.numerator,\n numerator: this.denominator,\n });\n }\n\n public mul(other: Price): Price {\n if (this.quoteToken !== other.baseToken) logger.logWithError(\"mul token not equals\");\n\n const fraction = super.mul(other);\n return new Price({\n baseToken: this.baseToken,\n quoteToken: other.quoteToken,\n denominator: fraction.denominator,\n numerator: fraction.numerator,\n });\n }\n\n public toSignificant(significantDigits = this.quoteToken.decimals, format?: object, rounding?: Rounding): string {\n return this.adjusted.toSignificant(significantDigits, format, rounding);\n }\n\n public toFixed(decimalPlaces = this.quoteToken.decimals, format?: object, rounding?: Rounding): string {\n return this.adjusted.toFixed(decimalPlaces, format, rounding);\n }\n}\n","import BN from \"bn.js\";\nimport Decimal from \"decimal.js\";\nimport { Token } from \"../module/token\";\nimport { Price } from \"../module/price\";\nimport { Currency } from \"../module/currency\";\nimport { TokenAmount, CurrencyAmount } from \"../module/amount\";\nimport { Fraction } from \"../module/fraction\";\nimport { Percent } from \"../module/percent\";\nimport { SplToken, TokenJson } from \"../gfx/token/type\";\nimport { ReplaceType } from \"../gfx/type\";\nimport { mul } from \"./fractionUtil\";\nimport { notInnerObject } from \"./utility\";\nimport { BigNumberish, BN_ZERO, BN_TEN } from \"./number\";\n\nexport type Numberish = number | string | bigint | Fraction | BN;\n\n/**\n *\n * @exa