@raydium-io/raydium-sdk-v2 0.1.0-alpha → 0.1.2-alpha

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (97) hide show
  1. package/lib/api/api.d.ts +1 -1
  2. package/lib/api/index.d.ts +1 -1
  3. package/lib/api/type.d.ts +1 -1
  4. package/lib/common/accountInfo.d.ts +1 -1
  5. package/lib/common/bignumber.d.ts +1 -1
  6. package/lib/common/fractionUtil.d.ts +1 -1
  7. package/lib/common/index.d.ts +1 -1
  8. package/lib/common/transfer.d.ts +1 -1
  9. package/lib/common/txTool/txTool.d.ts +1 -1
  10. package/lib/common/txTool/txUtils.d.ts +1 -1
  11. package/lib/common/utility.d.ts +1 -1
  12. package/lib/index.d.ts +3 -3
  13. package/lib/index.js +1 -1
  14. package/lib/index.js.map +1 -1
  15. package/lib/index.mjs +1 -1
  16. package/lib/index.mjs.map +1 -1
  17. package/lib/module/amount.d.ts +1 -1
  18. package/lib/module/fraction.d.ts +1 -1
  19. package/lib/module/index.d.ts +1 -1
  20. package/lib/module/percent.d.ts +1 -1
  21. package/lib/module/price.d.ts +1 -1
  22. package/lib/raydium/account/account.d.ts +3 -3
  23. package/lib/raydium/account/account.js +1 -1
  24. package/lib/raydium/account/account.js.map +1 -1
  25. package/lib/raydium/account/account.mjs +1 -1
  26. package/lib/raydium/account/account.mjs.map +1 -1
  27. package/lib/raydium/account/index.d.ts +1 -1
  28. package/lib/raydium/account/instruction.d.ts +1 -1
  29. package/lib/raydium/account/types.d.ts +1 -1
  30. package/lib/raydium/account/util.d.ts +1 -1
  31. package/lib/raydium/clmm/clmm.d.ts +3 -3
  32. package/lib/raydium/clmm/index.d.ts +3 -3
  33. package/lib/raydium/clmm/instrument.d.ts +2 -2
  34. package/lib/raydium/clmm/layout.d.ts +6 -6
  35. package/lib/raydium/clmm/type.d.ts +2 -2
  36. package/lib/raydium/clmm/utils/math.d.ts +2 -2
  37. package/lib/raydium/clmm/utils/pool.d.ts +2 -2
  38. package/lib/raydium/clmm/utils/position.d.ts +2 -2
  39. package/lib/raydium/clmm/utils/tick.d.ts +2 -2
  40. package/lib/raydium/clmm/utils/tickQuery.d.ts +2 -2
  41. package/lib/raydium/clmm/utils/tickarrayBitmap.d.ts +2 -2
  42. package/lib/raydium/cpmm/cpmm.d.ts +3 -3
  43. package/lib/raydium/cpmm/index.d.ts +1 -1
  44. package/lib/raydium/cpmm/layout.d.ts +1 -1
  45. package/lib/raydium/cpmm/type.d.ts +1 -1
  46. package/lib/raydium/farm/config.d.ts +1 -1
  47. package/lib/raydium/farm/farm.d.ts +3 -3
  48. package/lib/raydium/farm/index.d.ts +1 -1
  49. package/lib/raydium/farm/instruction.d.ts +1 -1
  50. package/lib/raydium/farm/layout.d.ts +1 -1
  51. package/lib/raydium/farm/type.d.ts +1 -1
  52. package/lib/raydium/farm/util.d.ts +1 -1
  53. package/lib/raydium/ido/ido.d.ts +3 -3
  54. package/lib/raydium/ido/index.d.ts +3 -3
  55. package/lib/raydium/ido/instruction.d.ts +1 -1
  56. package/lib/raydium/ido/type.d.ts +1 -1
  57. package/lib/raydium/index.d.ts +3 -3
  58. package/lib/raydium/index.js +1 -1
  59. package/lib/raydium/index.js.map +1 -1
  60. package/lib/raydium/index.mjs +1 -1
  61. package/lib/raydium/index.mjs.map +1 -1
  62. package/lib/raydium/liquidity/index.d.ts +1 -1
  63. package/lib/raydium/liquidity/instruction.d.ts +1 -1
  64. package/lib/raydium/liquidity/layout.d.ts +6 -6
  65. package/lib/raydium/liquidity/liquidity.d.ts +3 -3
  66. package/lib/raydium/liquidity/liquidity.js +1 -1
  67. package/lib/raydium/liquidity/liquidity.js.map +1 -1
  68. package/lib/raydium/liquidity/liquidity.mjs +1 -1
  69. package/lib/raydium/liquidity/liquidity.mjs.map +1 -1
  70. package/lib/raydium/liquidity/type.d.ts +1 -1
  71. package/lib/raydium/liquidity/utils.d.ts +1 -1
  72. package/lib/raydium/marketV2/createMarket.d.ts +3 -3
  73. package/lib/raydium/marketV2/index.d.ts +3 -3
  74. package/lib/raydium/moduleBase.d.ts +3 -3
  75. package/lib/raydium/raydium.d.ts +3 -3
  76. package/lib/raydium/raydium.js +1 -1
  77. package/lib/raydium/raydium.js.map +1 -1
  78. package/lib/raydium/raydium.mjs +1 -1
  79. package/lib/raydium/raydium.mjs.map +1 -1
  80. package/lib/raydium/token/constant.d.ts +1 -1
  81. package/lib/raydium/token/index.d.ts +1 -1
  82. package/lib/raydium/token/token.d.ts +3 -3
  83. package/lib/raydium/token/type.d.ts +1 -1
  84. package/lib/raydium/token/utils.d.ts +1 -1
  85. package/lib/raydium/tradeV2/index.d.ts +2 -2
  86. package/lib/raydium/tradeV2/instrument.d.ts +2 -2
  87. package/lib/raydium/tradeV2/trade.d.ts +3 -3
  88. package/lib/raydium/tradeV2/type.d.ts +2 -2
  89. package/lib/raydium/type.d.ts +1 -1
  90. package/lib/raydium/utils1216/index.d.ts +3 -3
  91. package/lib/raydium/utils1216/utils1216.d.ts +3 -3
  92. package/lib/{raydium-50d99e08.d.ts → raydium-e681ad95.d.ts} +3 -3
  93. package/lib/{type-80826393.d.ts → type-389634c9.d.ts} +1 -1
  94. package/lib/{type-8e0c46e7.d.ts → type-9fe71e3c.d.ts} +8 -8
  95. package/package.json +1 -1
  96. package/src/raydium/account/account.ts +1 -1
  97. package/src/raydium/liquidity/liquidity.ts +44 -47
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/raydium/account/account.ts","../../../src/common/logger.ts","../../../src/common/utility.ts","../../../src/module/amount.ts","../../../src/common/bignumber.ts","../../../node_modules/decimal.js/decimal.mjs","../../../src/module/token.ts","../../../src/common/pubKey.ts","../../../src/raydium/token/constant.ts","../../../src/module/fraction.ts","../../../src/module/formatter.ts","../../../src/module/price.ts","../../../src/module/currency.ts","../../../src/module/percent.ts","../../../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/raydium/moduleBase.ts","../../../src/raydium/account/instruction.ts","../../../src/raydium/account/util.ts","../../../src/marshmallow/index.ts","../../../src/marshmallow/buffer-layout.ts","../../../src/raydium/account/layout.ts","../../../node_modules/@noble/hashes/src/_assert.ts","../../../node_modules/@noble/hashes/src/utils.ts","../../../node_modules/@noble/hashes/src/_md.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\";\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\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 async fetchWalletTokenAccounts(config?: { forceUpdate?: boolean; commitment?: Commitment }): Promise<{\n tokenAccounts: TokenAccount[];\n tokenAccountRawInfos: TokenAccountRaw[];\n }> {\n if (this._clientOwnedToken || (!config?.forceUpdate && this._tokenAccounts.length)) {\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._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) => (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 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 {\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,\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 }): 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\";\nimport dayjs from \"dayjs\";\nimport utc from \"dayjs/plugin/utc\";\ndayjs.extend(utc);\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 dayjs().utc().format(\"YYYY/MM/DD HH:mm:ss UTC\");\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 { PublicKey } from \"@solana/web3.js\";\nimport BN from \"bn.js\";\n\nimport { Fraction, Percent, Price, Token, TokenAmount } from \"../module\";\nimport { ReplaceType } from \"../raydium/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 // @ts-expect-error no need type for inner code\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;\n}\n","import _Big from \"big.js\";\nimport BN from \"bn.js\";\n\nimport { BigNumberish, BN_TEN, parseBigNumberish, Rounding } from \"../common/bignumber\";\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(\"Raydium_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 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 \"../raydium/token/type\";\nimport { ReplaceType } from \"../raydium/type\";\nimport { createLogger } from \"./logger\";\nimport { mul } from \"./fractionUtil\";\nimport { notInnerObject } from \"./utility\";\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;\nexport type Numberish = number | string | bigint | Fraction | BN;\n\nconst MAX_SAFE = 0x1fffffffffffff;\n\nexport function parseBigNumberish(value: BigNumberish): BN {\n const logger = createLogger(\"Raydium_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\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}\n\nexport function recursivelyDecimalToFraction<T>(info: T): ReplaceType<T, Decimal, Fraction> {\n // @ts-expect-error no need type for inner code\n return isDecimal(info)\n ? decimalToFraction(info as any)\n : Array.isArray(info)\n ? info.map((k) => recursivelyDecimalToFraction(k))\n : notInnerObject(info)\n ? Object.fromEntries(Object.entries(info as any).map(([k, v]) => [k, recursivelyDecimalToFraction(v)]))\n : info;\n}\n","/*\r\n * decimal.js v10.3.1\r\n * An arbitrary-precision Decimal type for JavaScript.\r\n * https://github.com/MikeMcl/decimal.js\r\n * Copyright (c) 2021 Michael Mclaughlin <M8ch88l@gmail.com>\r\n * MIT Licence\r\n */\r\n\r\n\r\n// ----------------------------------- EDITABLE DEFAULTS ------------------------------------ //\r\n\r\n\r\n // The maximum exponent magnitude.\r\n // The limit on the value of `toExpNeg`, `toExpPos`, `minE` and `maxE`.\r\nvar EXP_LIMIT = 9e15, // 0 to 9e15\r\n\r\n // The limit on the value of `precision`, and on the value of the first argument to\r\n // `toDecimalPlaces`, `toExponential`, `toFixed`, `toPrecision` and `toSignificantDigits`.\r\n MAX_DIGITS = 1e9, // 0 to 1e9\r\n\r\n // Base conversion alphabet.\r\n NUMERALS = '0123456789abcdef',\r\n\r\n // The natural logarithm of 10 (1025 digits).\r\n LN10 = '2.3025850929940456840179914546843642076011014886287729760333279009675726096773524802359972050895982983419677840422862486334095254650828067566662873690987816894829072083255546808437998948262331985283935053089653777326288461633662222876982198867465436674744042432743651550489343149393914796194044002221051017141748003688084012647080685567743216228355220114804663715659121373450747856947683463616792101806445070648000277502684916746550586856935673420670581136429224554405758925724208241314695689016758940256776311356919292033376587141660230105703089634572075440370847469940168269282808481184289314848524948644871927809676271275775397027668605952496716674183485704422507197965004714951050492214776567636938662976979522110718264549734772662425709429322582798502585509785265383207606726317164309505995087807523710333101197857547331541421808427543863591778117054309827482385045648019095610299291824318237525357709750539565187697510374970888692180205189339507238539205144634197265287286965110862571492198849978748873771345686209167058',\r\n\r\n // Pi (1025 digits).\r\n PI = '3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679821480865132823066470938446095505822317253594081284811174502841027019385211055596446229489549303819644288109756659334461284756482337867831652712019091456485669234603486104543266482133936072602491412737245870066063155881748815209209628292540917153643678925903600113305305488204665213841469519415116094330572703657595919530921861173819326117931051185480744623799627495673518857527248912279381830119491298336733624406566430860213949463952247371907021798609437027705392171762931767523846748184676694051320005681271452635608277857713427577896091736371787214684409012249534301465495853710507922796892589235420199561121290219608640344181598136297747713099605187072113499999983729780499510597317328160963185950244594553469083026425223082533446850352619311881710100031378387528865875332083814206171776691473035982534904287554687311595628638823537875937519577818577805321712268066130019278766111959092164201989380952572010654858632789',\r\n\r\n\r\n // The initial configuration properties of the Decimal constructor.\r\n DEFAULTS = {\r\n\r\n // These values must be integers within the stated ranges (inclusive).\r\n // Most of these values can be changed at run-time using the `Decimal.config` method.\r\n\r\n // The maximum number of significant digits of the result of a calculation or base conversion.\r\n // E.g. `Decimal.config({ precision: 20 });`\r\n precision: 20, // 1 to MAX_DIGITS\r\n\r\n // The rounding mode used when rounding to `precision`.\r\n //\r\n // ROUND_UP 0 Away from zero.\r\n // ROUND_DOWN 1 Towards zero.\r\n // ROUND_CEIL 2 Towards +Infinity.\r\n // ROUND_FLOOR 3 Towards -Infinity.\r\n // ROUND_HALF_UP 4 Towards nearest neighbour. If equidistant, up.\r\n // ROUND_HALF_DOWN 5 Towards nearest neighbour. If equidistant, down.\r\n // ROUND_HALF_EVEN 6 Towards nearest neighbour. If equidistant, towards even neighbour.\r\n // ROUND_HALF_CEIL 7 Towards nearest neighbour. If equidistant, towards +Infinity.\r\n // ROUND_HALF_FLOOR 8 Towards nearest neighbour. If equidistant, towards -Infinity.\r\n //\r\n // E.g.\r\n // `Decimal.rounding = 4;`\r\n // `Decimal.rounding = Decimal.ROUND_HALF_UP;`\r\n rounding: 4, // 0 to 8\r\n\r\n // The modulo mode used when calculating the modulus: a mod n.\r\n // The quotient (q = a / n) is calculated according to the corresponding rounding mode.\r\n // The remainder (r) is calculated as: r = a - n * q.\r\n //\r\n // UP 0 The remainder is positive if the dividend is negative, else is negative.\r\n // DOWN 1 The remainder has the same sign as the dividend (JavaScript %).\r\n // FLOOR 3 The remainder has the same sign as the divisor (Python %).\r\n // HALF_EVEN 6 The IEEE 754 remainder function.\r\n // EUCLID 9 Euclidian division. q = sign(n) * floor(a / abs(n)). Always positive.\r\n //\r\n // Truncated division (1), floored division (3), the IEEE 754 remainder (6), and Euclidian\r\n // division (9) are commonly used for the modulus operation. The other rounding modes can also\r\n // be used, but they may not give useful results.\r\n modulo: 1, // 0 to 9\r\n\r\n // The exponent value at and beneath which `toString` returns exponential notation.\r\n // JavaScript numbers: -7\r\n toExpNeg: -7, // 0 to -EXP_LIMIT\r\n\r\n // The exponent value at and above which `toString` returns exponential notation.\r\n // JavaScript numbers: 21\r\n toExpPos: 21, // 0 to EXP_LIMIT\r\n\r\n // The minimum exponent value, beneath which underflow to zero occurs.\r\n // JavaScript numbers: -324 (5e-324)\r\n minE: -EXP_LIMIT, // -1 to -EXP_LIMIT\r\n\r\n // The maximum exponent value, above which overflow to Infinity occurs.\r\n // JavaScript numbers: 308 (1.7976931348623157e+308)\r\n maxE: EXP_LIMIT, // 1 to EXP_LIMIT\r\n\r\n // Whether to use cryptographically-secure random number generation, if available.\r\n crypto: false // true/false\r\n },\r\n\r\n\r\n// ----------------------------------- END OF EDITABLE DEFAULTS ------------------------------- //\r\n\r\n\r\n inexact, quadrant,\r\n external = true,\r\n\r\n decimalError = '[DecimalError] ',\r\n invalidArgument = decimalError + 'Invalid argument: ',\r\n precisionLimitExceeded = decimalError + 'Precision limit exceeded',\r\n cryptoUnavailable = decimalError + 'crypto unavailable',\r\n tag = '[object Decimal]',\r\n\r\n mathfloor = Math.floor,\r\n mathpow = Math.pow,\r\n\r\n isBinary = /^0b([01]+(\\.[01]*)?|\\.[01]+)(p[+-]?\\d+)?$/i,\r\n isHex = /^0x([0-9a-f]+(\\.[0-9a-f]*)?|\\.[0-9a-f]+)(p[+-]?\\d+)?$/i,\r\n isOctal = /^0o([0-7]+(\\.[0-7]*)?|\\.[0-7]+)(p[+-]?\\d+)?$/i,\r\n isDecimal = /^(\\d+(\\.\\d*)?|\\.\\d+)(e[+-]?\\d+)?$/i,\r\n\r\n BASE = 1e7,\r\n LOG_BASE = 7,\r\n MAX_SAFE_INTEGER = 9007199254740991,\r\n\r\n LN10_PRECISION = LN10.length - 1,\r\n PI_PRECISION = PI.length - 1,\r\n\r\n // Decimal.prototype object\r\n P = { toStringTag: tag };\r\n\r\n\r\n// Decimal prototype methods\r\n\r\n\r\n/*\r\n * absoluteValue abs\r\n * ceil\r\n * clampedTo clamp\r\n * comparedTo cmp\r\n * cosine cos\r\n * cubeRoot cbrt\r\n * decimalPlaces dp\r\n * dividedBy div\r\n * dividedToIntegerBy divToInt\r\n * equals eq\r\n * floor\r\n * greaterThan gt\r\n * greaterThanOrEqualTo gte\r\n * hyperbolicCosine cosh\r\n * hyperbolicSine sinh\r\n * hyperbolicTangent tanh\r\n * inverseCosine acos\r\n * inverseHyperbolicCosine acosh\r\n * inverseHyperbolicSine asinh\r\n * inverseHyperbolicTangent atanh\r\n * inverseSine asin\r\n * inverseTangent atan\r\n * isFinite\r\n * isInteger isInt\r\n * isNaN\r\n * isNegative isNeg\r\n * isPositive isPos\r\n * isZero\r\n * lessThan lt\r\n * lessThanOrEqualTo lte\r\n * logarithm log\r\n * [maximum] [max]\r\n * [minimum] [min]\r\n * minus sub\r\n * modulo mod\r\n * naturalExponential exp\r\n * naturalLogarithm ln\r\n * negated neg\r\n * plus add\r\n * precision sd\r\n * round\r\n * sine sin\r\n * squareRoot sqrt\r\n * tangent tan\r\n * times mul\r\n * toBinary\r\n * toDecimalPlaces toDP\r\n * toExponential\r\n * toFixed\r\n * toFraction\r\n * toHexadecimal toHex\r\n * toNearest\r\n * toNumber\r\n * toOctal\r\n * toPower pow\r\n * toPrecision\r\n * toSignificantDigits toSD\r\n * toString\r\n * truncated trunc\r\n * valueOf toJSON\r\n */\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is the absolute value of this Decimal.\r\n *\r\n */\r\nP.absoluteValue = P.abs = function () {\r\n var x = new this.constructor(this);\r\n if (x.s < 0) x.s = 1;\r\n return finalise(x);\r\n};\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is the value of this Decimal rounded to a whole number in the\r\n * direction of positive Infinity.\r\n *\r\n */\r\nP.ceil = function () {\r\n return finalise(new this.constructor(this), this.e + 1, 2);\r\n};\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is the value of this Decimal clamped to the range\r\n * delineated by `min` and `max`.\r\n *\r\n * min {number|string|Decimal}\r\n * max {number|string|Decimal}\r\n *\r\n */\r\nP.clampedTo = P.clamp = function (min, max) {\r\n var k,\r\n x = this,\r\n Ctor = x.constructor;\r\n min = new Ctor(min);\r\n max = new Ctor(max);\r\n if (!min.s || !max.s) return new Ctor(NaN);\r\n if (min.gt(max)) throw Error(invalidArgument + max);\r\n k = x.cmp(min);\r\n return k < 0 ? min : x.cmp(max) > 0 ? max : new Ctor(x);\r\n};\r\n\r\n\r\n/*\r\n * Return\r\n * 1 if the value of this Decimal is greater than the value of `y`,\r\n * -1 if the value of this Decimal is less than the value of `y`,\r\n * 0 if they have the same value,\r\n * NaN if the value of either Decimal is NaN.\r\n *\r\n */\r\nP.comparedTo = P.cmp = function (y) {\r\n var i, j, xdL, ydL,\r\n x = this,\r\n xd = x.d,\r\n yd = (y = new x.constructor(y)).d,\r\n xs = x.s,\r\n ys = y.s;\r\n\r\n // Either NaN or ±Infinity?\r\n if (!xd || !yd) {\r\n return !xs || !ys ? NaN : xs !== ys ? xs : xd === yd ? 0 : !xd ^ xs < 0 ? 1 : -1;\r\n }\r\n\r\n // Either zero?\r\n if (!xd[0] || !yd[0]) return xd[0] ? xs : yd[0] ? -ys : 0;\r\n\r\n // Signs differ?\r\n if (xs !== ys) return xs;\r\n\r\n // Compare exponents.\r\n if (x.e !== y.e) return x.e > y.e ^ xs < 0 ? 1 : -1;\r\n\r\n xdL = xd.length;\r\n ydL = yd.length;\r\n\r\n // Compare digit by digit.\r\n for (i = 0, j = xdL < ydL ? xdL : ydL; i < j; ++i) {\r\n if (xd[i] !== yd[i]) return xd[i] > yd[i] ^ xs < 0 ? 1 : -1;\r\n }\r\n\r\n // Compare lengths.\r\n return xdL === ydL ? 0 : xdL > ydL ^ xs < 0 ? 1 : -1;\r\n};\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is the cosine of the value in radians of this Decimal.\r\n *\r\n * Domain: [-Infinity, Infinity]\r\n * Range: [-1, 1]\r\n *\r\n * cos(0) = 1\r\n * cos(-0) = 1\r\n * cos(Infinity) = NaN\r\n * cos(-Infinity) = NaN\r\n * cos(NaN) = NaN\r\n *\r\n */\r\nP.cosine = P.cos = function () {\r\n var pr, rm,\r\n x = this,\r\n Ctor = x.constructor;\r\n\r\n if (!x.d) return new Ctor(NaN);\r\n\r\n // cos(0) = cos(-0) = 1\r\n if (!x.d[0]) return new Ctor(1);\r\n\r\n pr = Ctor.precision;\r\n rm = Ctor.rounding;\r\n Ctor.precision = pr + Math.max(x.e, x.sd()) + LOG_BASE;\r\n Ctor.rounding = 1;\r\n\r\n x = cosine(Ctor, toLessThanHalfPi(Ctor, x));\r\n\r\n Ctor.precision = pr;\r\n Ctor.rounding = rm;\r\n\r\n return finalise(quadrant == 2 || quadrant == 3 ? x.neg() : x, pr, rm, true);\r\n};\r\n\r\n\r\n/*\r\n *\r\n * Return a new Decimal whose value is the cube root of the value of this Decimal, rounded to\r\n * `precision` significant digits using rounding mode `rounding`.\r\n *\r\n * cbrt(0) = 0\r\n * cbrt(-0) = -0\r\n * cbrt(1) = 1\r\n * cbrt(-1) = -1\r\n * cbrt(N) = N\r\n * cbrt(-I) = -I\r\n * cbrt(I) = I\r\n *\r\n * Math.cbrt(x) = (x < 0 ? -Math.pow(-x, 1/3) : Math.pow(x, 1/3))\r\n *\r\n */\r\nP.cubeRoot = P.cbrt = function () {\r\n var e, m, n, r, rep, s, sd, t, t3, t3plusx,\r\n x = this,\r\n Ctor = x.constructor;\r\n\r\n if (!x.isFinite() || x.isZero()) return new Ctor(x);\r\n external = false;\r\n\r\n // Initial estimate.\r\n s = x.s * mathpow(x.s * x, 1 / 3);\r\n\r\n // Math.cbrt underflow/overflow?\r\n // Pass x to Math.pow as integer, then adjust the exponent of the result.\r\n if (!s || Math.abs(s) == 1 / 0) {\r\n n = digitsToString(x.d);\r\n e = x.e;\r\n\r\n // Adjust n exponent so it is a multiple of 3 away from x exponent.\r\n if (s = (e - n.length + 1) % 3) n += (s == 1 || s == -2 ? '0' : '00');\r\n s = mathpow(n, 1 / 3);\r\n\r\n // Rarely, e may be one less than the result exponent value.\r\n e = mathfloor((e + 1) / 3) - (e % 3 == (e < 0 ? -1 : 2));\r\n\r\n if (s == 1 / 0) {\r\n n = '5e' + e;\r\n } else {\r\n n = s.toExponential();\r\n n = n.slice(0, n.indexOf('e') + 1) + e;\r\n }\r\n\r\n r = new Ctor(n);\r\n r.s = x.s;\r\n } else {\r\n r = new Ctor(s.toString());\r\n }\r\n\r\n sd = (e = Ctor.precision) + 3;\r\n\r\n // Halley's method.\r\n // TODO? Compare Newton's method.\r\n for (;;) {\r\n t = r;\r\n t3 = t.times(t).times(t);\r\n t3plusx = t3.plus(x);\r\n r = divide(t3plusx.plus(x).times(t), t3plusx.plus(t3), sd + 2, 1);\r\n\r\n // TODO? Replace with for-loop and checkRoundingDigits.\r\n if (digitsToString(t.d).slice(0, sd) === (n = digitsToString(r.d)).slice(0, sd)) {\r\n n = n.slice(sd - 3, sd + 1);\r\n\r\n // The 4th rounding digit may be in error by -1 so if the 4 rounding digits are 9999 or 4999\r\n // , i.e. approaching a rounding boundary, continue the iteration.\r\n if (n == '9999' || !rep && n == '4999') {\r\n\r\n // On the first iteration only, check to see if rounding up gives the exact result as the\r\n // nines may infinitely repeat.\r\n if (!rep) {\r\n finalise(t, e + 1, 0);\r\n\r\n if (t.times(t).times(t).eq(x)) {\r\n r = t;\r\n break;\r\n }\r\n }\r\n\r\n sd += 4;\r\n rep = 1;\r\n } else {\r\n\r\n // If the rounding digits are null, 0{0,4} or 50{0,3}, check for an exact result.\r\n // If not, then there are further digits and m will be truthy.\r\n if (!+n || !+n.slice(1) && n.charAt(0) == '5') {\r\n\r\n // Truncate to the first rounding digit.\r\n finalise(r, e + 1, 1);\r\n m = !r.times(r).times(r).eq(x);\r\n }\r\n\r\n break;\r\n }\r\n }\r\n }\r\n\r\n external = true;\r\n\r\n return finalise(r, e, Ctor.rounding, m);\r\n};\r\n\r\n\r\n/*\r\n * Return the number of decimal places of the value of this Decimal.\r\n *\r\n */\r\nP.decimalPlaces = P.dp = function () {\r\n var w,\r\n d = this.d,\r\n n = NaN;\r\n\r\n if (d) {\r\n w = d.length - 1;\r\n n = (w - mathfloor(this.e / LOG_BASE)) * LOG_BASE;\r\n\r\n // Subtract the number of trailing zeros of the last word.\r\n w = d[w];\r\n if (w) for (; w % 10 == 0; w /= 10) n--;\r\n if (n < 0) n = 0;\r\n }\r\n\r\n return n;\r\n};\r\n\r\n\r\n/*\r\n * n / 0 = I\r\n * n / N = N\r\n * n / I = 0\r\n * 0 / n = 0\r\n * 0 / 0 = N\r\n * 0 / N = N\r\n * 0 / I = 0\r\n * N / n = N\r\n * N / 0 = N\r\n * N / N = N\r\n * N / I = N\r\n * I / n = I\r\n * I / 0 = I\r\n * I / N = N\r\n * I / I = N\r\n *\r\n * Return a new Decimal whose value is the value of this Decimal divided by `y`, rounded to\r\n * `precision` significant digits using rounding mode `rounding`.\r\n *\r\n */\r\nP.dividedBy = P.div = function (y) {\r\n return divide(this, new this.constructor(y));\r\n};\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is the integer part of dividing the value of this Decimal\r\n * by the value of `y`, rounded to `precision` significant digits using rounding mode `rounding`.\r\n *\r\n */\r\nP.dividedToIntegerBy = P.divToInt = function (y) {\r\n var x = this,\r\n Ctor = x.constructor;\r\n return finalise(divide(x, new Ctor(y), 0, 1, 1), Ctor.precision, Ctor.rounding);\r\n};\r\n\r\n\r\n/*\r\n * Return true if the value of this Decimal is equal to the value of `y`, otherwise return false.\r\n *\r\n */\r\nP.equals = P.eq = function (y) {\r\n return this.cmp(y) === 0;\r\n};\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is the value of this Decimal rounded to a whole number in the\r\n * direction of negative Infinity.\r\n *\r\n */\r\nP.floor = function () {\r\n return finalise(new this.constructor(this), this.e + 1, 3);\r\n};\r\n\r\n\r\n/*\r\n * Return true if the value of this Decimal is greater than the value of `y`, otherwise return\r\n * false.\r\n *\r\n */\r\nP.greaterThan = P.gt = function (y) {\r\n return this.cmp(y) > 0;\r\n};\r\n\r\n\r\n/*\r\n * Return true if the value of this Decimal is greater than or equal to the value of `y`,\r\n * otherwise return false.\r\n *\r\n */\r\nP.greaterThanOrEqualTo = P.gte = function (y) {\r\n var k = this.cmp(y);\r\n return k == 1 || k === 0;\r\n};\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is the hyperbolic cosine of the value in radians of this\r\n * Decimal.\r\n *\r\n * Domain: [-Infinity, Infinity]\r\n * Range: [1, Infinity]\r\n *\r\n * cosh(x) = 1 + x^2/2! + x^4/4! + x^6/6! + ...\r\n *\r\n * cosh(0) = 1\r\n * cosh(-0) = 1\r\n * cosh(Infinity) = Infinity\r\n * cosh(-Infinity) = Infinity\r\n * cosh(NaN) = NaN\r\n *\r\n * x time taken (ms) result\r\n * 1000 9 9.8503555700852349694e+433\r\n * 10000 25 4.4034091128314607936e+4342\r\n * 100000 171 1.4033316802130615897e+43429\r\n * 1000000 3817 1.5166076984010437725e+434294\r\n * 10000000 abandoned after 2 minute wait\r\n *\r\n * TODO? Compare performance of cosh(x) = 0.5 * (exp(x) + exp(-x))\r\n *\r\n */\r\nP.hyperbolicCosine = P.cosh = function () {\r\n var k, n, pr, rm, len,\r\n x = this,\r\n Ctor = x.constructor,\r\n one = new Ctor(1);\r\n\r\n if (!x.isFinite()) return new Ctor(x.s ? 1 / 0 : NaN);\r\n if (x.isZero()) return one;\r\n\r\n pr = Ctor.precision;\r\n rm = Ctor.rounding;\r\n Ctor.precision = pr + Math.max(x.e, x.sd()) + 4;\r\n Ctor.rounding = 1;\r\n len = x.d.length;\r\n\r\n // Argument reduction: cos(4x) = 1 - 8cos^2(x) + 8cos^4(x) + 1\r\n // i.e. cos(x) = 1 - cos^2(x/4)(8 - 8cos^2(x/4))\r\n\r\n // Estimate the optimum number of times to use the argument reduction.\r\n // TODO? Estimation reused from cosine() and may not be optimal here.\r\n if (len < 32) {\r\n k = Math.ceil(len / 3);\r\n n = (1 / tinyPow(4, k)).toString();\r\n } else {\r\n k = 16;\r\n n = '2.3283064365386962890625e-10';\r\n }\r\n\r\n x = taylorSeries(Ctor, 1, x.times(n), new Ctor(1), true);\r\n\r\n // Reverse argument reduction\r\n var cosh2_x,\r\n i = k,\r\n d8 = new Ctor(8);\r\n for (; i--;) {\r\n cosh2_x = x.times(x);\r\n x = one.minus(cosh2_x.times(d8.minus(cosh2_x.times(d8))));\r\n }\r\n\r\n return finalise(x, Ctor.precision = pr, Ctor.rounding = rm, true);\r\n};\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is the hyperbolic sine of the value in radians of this\r\n * Decimal.\r\n *\r\n * Domain: [-Infinity, Infinity]\r\n * Range: [-Infinity, Infinity]\r\n *\r\n * sinh(x) = x + x^3/3! + x^5/5! + x^7/7! + ...\r\n *\r\n * sinh(0) = 0\r\n * sinh(-0) = -0\r\n * sinh(Infinity) = Infinity\r\n * sinh(-Infinity) = -Infinity\r\n * sinh(NaN) = NaN\r\n *\r\n * x time taken (ms)\r\n * 10 2 ms\r\n * 100 5 ms\r\n * 1000 14 ms\r\n * 10000 82 ms\r\n * 100000 886 ms 1.4033316802130615897e+43429\r\n * 200000 2613 ms\r\n * 300000 5407 ms\r\n * 400000 8824 ms\r\n * 500000 13026 ms 8.7080643612718084129e+217146\r\n * 1000000 48543 ms\r\n *\r\n * TODO? Compare performance of sinh(x) = 0.5 * (exp(x) - exp(-x))\r\n *\r\n */\r\nP.hyperbolicSine = P.sinh = function () {\r\n var k, pr, rm, len,\r\n x = this,\r\n Ctor = x.constructor;\r\n\r\n if (!x.isFinite() || x.isZero()) return new Ctor(x);\r\n\r\n pr = Ctor.precision;\r\n rm = Ctor.rounding;\r\n Ctor.precision = pr + Math.max(x.e, x.sd()) + 4;\r\n Ctor.rounding = 1;\r\n len = x.d.length;\r\n\r\n if (len < 3) {\r\n x = taylorSeries(Ctor, 2, x, x, true);\r\n } else {\r\n\r\n // Alternative argument reduction: sinh(3x) = sinh(x)(3 + 4sinh^2(x))\r\n // i.e. sinh(x) = sinh(x/3)(3 + 4sinh^2(x/3))\r\n // 3 multiplications and 1 addition\r\n\r\n // Argument reduction: sinh(5x) = sinh(x)(5 + sinh^2(x)(20 + 16sinh^2(x)))\r\n // i.e. sinh(x) = sinh(x/5)(5 + sinh^2(x/5)(20 + 16sinh^2(x/5)))\r\n // 4 multiplications and 2 additions\r\n\r\n // Estimate the optimum number of times to use the argument reduction.\r\n k = 1.4 * Math.sqrt(len);\r\n k = k > 16 ? 16 : k | 0;\r\n\r\n x = x.times(1 / tinyPow(5, k));\r\n x = taylorSeries(Ctor, 2, x, x, true);\r\n\r\n // Reverse argument reduction\r\n var sinh2_x,\r\n d5 = new Ctor(5),\r\n d16 = new Ctor(16),\r\n d20 = new Ctor(20);\r\n for (; k--;) {\r\n sinh2_x = x.times(x);\r\n x = x.times(d5.plus(sinh2_x.times(d16.times(sinh2_x).plus(d20))));\r\n }\r\n }\r\n\r\n Ctor.precision = pr;\r\n Ctor.rounding = rm;\r\n\r\n return finalise(x, pr, rm, true);\r\n};\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is the hyperbolic tangent of the value in radians of this\r\n * Decimal.\r\n *\r\n * Domain: [-Infinity, Infinity]\r\n * Range: [-1, 1]\r\n *\r\n * tanh(x) = sinh(x) / cosh(x)\r\n *\r\n * tanh(0) = 0\r\n * tanh(-0) = -0\r\n * tanh(Infinity) = 1\r\n * tanh(-Infinity) = -1\r\n * tanh(NaN) = NaN\r\n *\r\n */\r\nP.hyperbolicTangent = P.tanh = function () {\r\n var pr, rm,\r\n x = this,\r\n Ctor = x.constructor;\r\n\r\n if (!x.isFinite()) return new Ctor(x.s);\r\n if (x.isZero()) return new Ctor(x);\r\n\r\n pr = Ctor.precision;\r\n rm = Ctor.rounding;\r\n Ctor.precision = pr + 7;\r\n Ctor.rounding = 1;\r\n\r\n return divide(x.sinh(), x.cosh(), Ctor.precision = pr, Ctor.rounding = rm);\r\n};\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is the arccosine (inverse cosine) in radians of the value of\r\n * this Decimal.\r\n *\r\n * Domain: [-1, 1]\r\n * Range: [0, pi]\r\n *\r\n * acos(x) = pi/2 - asin(x)\r\n *\r\n * acos(0) = pi/2\r\n * acos(-0) = pi/2\r\n * acos(1) = 0\r\n * acos(-1) = pi\r\n * acos(1/2) = pi/3\r\n * acos(-1/2) = 2*pi/3\r\n * acos(|x| > 1) = NaN\r\n * acos(NaN) = NaN\r\n *\r\n */\r\nP.inverseCosine = P.acos = function () {\r\n var halfPi,\r\n x = this,\r\n Ctor = x.constructor,\r\n k = x.abs().cmp(1),\r\n pr = Ctor.precision,\r\n rm = Ctor.rounding;\r\n\r\n if (k !== -1) {\r\n return k === 0\r\n // |x| is 1\r\n ? x.isNeg() ? getPi(Ctor, pr, rm) : new Ctor(0)\r\n // |x| > 1 or x is NaN\r\n : new Ctor(NaN);\r\n }\r\n\r\n if (x.isZero()) return getPi(Ctor, pr + 4, rm).times(0.5);\r\n\r\n // TODO? Special case acos(0.5) = pi/3 and acos(-0.5) = 2*pi/3\r\n\r\n Ctor.precision = pr + 6;\r\n Ctor.rounding = 1;\r\n\r\n x = x.asin();\r\n halfPi = getPi(Ctor, pr + 4, rm).times(0.5);\r\n\r\n Ctor.precision = pr;\r\n Ctor.rounding = rm;\r\n\r\n return halfPi.minus(x);\r\n};\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is the inverse of the hyperbolic cosine in radians of the\r\n * value of this Decimal.\r\n *\r\n * Domain: [1, Infinity]\r\n * Range: [0, Infinity]\r\n *\r\n * acosh(x) = ln(x + sqrt(x^2 - 1))\r\n *\r\n * acosh(x < 1) = NaN\r\n * acosh(NaN) = NaN\r\n * acosh(Infinity) = Infinity\r\n * acosh(-Infinity) = NaN\r\n * acosh(0) = NaN\r\n * acosh(-0) = NaN\r\n * acosh(1) = 0\r\n * acosh(-1) = NaN\r\n *\r\n */\r\nP.inverseHyperbolicCosine = P.acosh = function () {\r\n var pr, rm,\r\n x = this,\r\n Ctor = x.constructor;\r\n\r\n if (x.lte(1)) return new Ctor(x.eq(1) ? 0 : NaN);\r\n if (!x.isFinite()) return new Ctor(x);\r\n\r\n pr = Ctor.precision;\r\n rm = Ctor.rounding;\r\n Ctor.precision = pr + Math.max(Math.abs(x.e), x.sd()) + 4;\r\n Ctor.rounding = 1;\r\n external = false;\r\n\r\n x = x.times(x).minus(1).sqrt().plus(x);\r\n\r\n external = true;\r\n Ctor.precision = pr;\r\n Ctor.rounding = rm;\r\n\r\n return x.ln();\r\n};\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is the inverse of the hyperbolic sine in radians of the value\r\n * of this Decimal.\r\n *\r\n * Domain: [-Infinity, Infinity]\r\n * Range: [-Infinity, Infinity]\r\n *\r\n * asinh(x) = ln(x + sqrt(x^2 + 1))\r\n *\r\n * asinh(NaN) = NaN\r\n * asinh(Infinity) = Infinity\r\n * asinh(-Infinity) = -Infinity\r\n * asinh(0) = 0\r\n * asinh(-0) = -0\r\n *\r\n */\r\nP.inverseHyperbolicSine = P.asinh = function () {\r\n var pr, rm,\r\n x = this,\r\n Ctor = x.constructor;\r\n\r\n if (!x.isFinite() || x.isZero()) return new Ctor(x);\r\n\r\n pr = Ctor.precision;\r\n rm = Ctor.rounding;\r\n Ctor.precision = pr + 2 * Math.max(Math.abs(x.e), x.sd()) + 6;\r\n Ctor.rounding = 1;\r\n external = false;\r\n\r\n x = x.times(x).plus(1).sqrt().plus(x);\r\n\r\n external = true;\r\n Ctor.precision = pr;\r\n Ctor.rounding = rm;\r\n\r\n return x.ln();\r\n};\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is the inverse of the hyperbolic tangent in radians of the\r\n * value of this Decimal.\r\n *\r\n * Domain: [-1, 1]\r\n * Range: [-Infinity, Infinity]\r\n *\r\n * atanh(x) = 0.5 * ln((1 + x) / (1 - x))\r\n *\r\n * atanh(|x| > 1) = NaN\r\n * atanh(NaN) = NaN\r\n * atanh(Infinity) = NaN\r\n * atanh(-Infinity) = NaN\r\n * atanh(0) = 0\r\n * atanh(-0) = -0\r\n * atanh(1) = Infinity\r\n * atanh(-1) = -Infinity\r\n *\r\n */\r\nP.inverseHyperbolicTangent = P.atanh = function () {\r\n var pr, rm, wpr, xsd,\r\n x = this,\r\n Ctor = x.constructor;\r\n\r\n if (!x.isFinite()) return new Ctor(NaN);\r\n if (x.e >= 0) return new Ctor(x.abs().eq(1) ? x.s / 0 : x.isZero() ? x : NaN);\r\n\r\n pr = Ctor.precision;\r\n rm = Ctor.rounding;\r\n xsd = x.sd();\r\n\r\n if (Math.max(xsd, pr) < 2 * -x.e - 1) return finalise(new Ctor(x), pr, rm, true);\r\n\r\n Ctor.precision = wpr = xsd - x.e;\r\n\r\n x = divide(x.plus(1), new Ctor(1).minus(x), wpr + pr, 1);\r\n\r\n Ctor.precision = pr + 4;\r\n Ctor.rounding = 1;\r\n\r\n x = x.ln();\r\n\r\n Ctor.precision = pr;\r\n Ctor.rounding = rm;\r\n\r\n return x.times(0.5);\r\n};\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is the arcsine (inverse sine) in radians of the value of this\r\n * Decimal.\r\n *\r\n * Domain: [-Infinity, Infinity]\r\n * Range: [-pi/2, pi/2]\r\n *\r\n * asin(x) = 2*atan(x/(1 + sqrt(1 - x^2)))\r\n *\r\n * asin(0) = 0\r\n * asin(-0) = -0\r\n * asin(1/2) = pi/6\r\n * asin(-1/2) = -pi/6\r\n * asin(1) = pi/2\r\n * asin(-1) = -pi/2\r\n * asin(|x| > 1) = NaN\r\n * asin(NaN) = NaN\r\n *\r\n * TODO? Compare performance of Taylor series.\r\n *\r\n */\r\nP.inverseSine = P.asin = function () {\r\n var halfPi, k,\r\n pr, rm,\r\n x = this,\r\n Ctor = x.constructor;\r\n\r\n if (x.isZero()) return new Ctor(x);\r\n\r\n k = x.abs().cmp(1);\r\n pr = Ctor.precision;\r\n rm = Ctor.rounding;\r\n\r\n if (k !== -1) {\r\n\r\n // |x| is 1\r\n if (k === 0) {\r\n halfPi = getPi(Ctor, pr + 4, rm).times(0.5);\r\n halfPi.s = x.s;\r\n return halfPi;\r\n }\r\n\r\n // |x| > 1 or x is NaN\r\n return new Ctor(NaN);\r\n }\r\n\r\n // TODO? Special case asin(1/2) = pi/6 and asin(-1/2) = -pi/6\r\n\r\n Ctor.precision = pr + 6;\r\n Ctor.rounding = 1;\r\n\r\n x = x.div(new Ctor(1).minus(x.times(x)).sqrt().plus(1)).atan();\r\n\r\n Ctor.precision = pr;\r\n Ctor.rounding = rm;\r\n\r\n return x.times(2);\r\n};\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is the arctangent (inverse tangent) in radians of the value\r\n * of this Decimal.\r\n *\r\n * Domain: [-Infinity, Infinity]\r\n * Range: [-pi/2, pi/2]\r\n *\r\n * atan(x) = x - x^3/3 + x^5/5 - x^7/7 + ...\r\n *\r\n * atan(0) = 0\r\n * atan(-0) = -0\r\n * atan(1) = pi/4\r\n * atan(-1) = -pi/4\r\n * atan(Infinity) = pi/2\r\n * atan(-Infinity) = -pi/2\r\n * atan(NaN) = NaN\r\n *\r\n */\r\nP.inverseTangent = P.atan = function () {\r\n var i, j, k, n, px, t, r, wpr, x2,\r\n x = this,\r\n Ctor = x.constructor,\r\n pr = Ctor.precision,\r\n rm = Ctor.rounding;\r\n\r\n if (!x.isFinite()) {\r\n if (!x.s) return new Ctor(NaN);\r\n if (pr + 4 <= PI_PRECISION) {\r\n r = getPi(Ctor, pr + 4, rm).times(0.5);\r\n r.s = x.s;\r\n return r;\r\n }\r\n } else if (x.isZero()) {\r\n return new Ctor(x);\r\n } else if (x.abs().eq(1) && pr + 4 <= PI_PRECISION) {\r\n r = getPi(Ctor, pr + 4, rm).times(0.25);\r\n r.s = x.s;\r\n return r;\r\n }\r\n\r\n Ctor.precision = wpr = pr + 10;\r\n Ctor.rounding = 1;\r\n\r\n // TODO? if (x >= 1 && pr <= PI_PRECISION) atan(x) = halfPi * x.s - atan(1 / x);\r\n\r\n // Argument reduction\r\n // Ensure |x| < 0.42\r\n // atan(x) = 2 * atan(x / (1 + sqrt(1 + x^2)))\r\n\r\n k = Math.min(28, wpr / LOG_BASE + 2 | 0);\r\n\r\n for (i = k; i; --i) x = x.div(x.times(x).plus(1).sqrt().plus(1));\r\n\r\n external = false;\r\n\r\n j = Math.ceil(wpr / LOG_BASE);\r\n n = 1;\r\n x2 = x.times(x);\r\n r = new Ctor(x);\r\n px = x;\r\n\r\n // atan(x) = x - x^3/3 + x^5/5 - x^7/7 + ...\r\n for (; i !== -1;) {\r\n px = px.times(x2);\r\n t = r.minus(px.div(n += 2));\r\n\r\n px = px.times(x2);\r\n r = t.plus(px.div(n += 2));\r\n\r\n if (r.d[j] !== void 0) for (i = j; r.d[i] === t.d[i] && i--;);\r\n }\r\n\r\n if (k) r = r.times(2 << (k - 1));\r\n\r\n external = true;\r\n\r\n return finalise(r, Ctor.precision = pr, Ctor.rounding = rm, true);\r\n};\r\n\r\n\r\n/*\r\n * Return true if the value of this Decimal is a finite number, otherwise return false.\r\n *\r\n */\r\nP.isFinite = function () {\r\n return !!this.d;\r\n};\r\n\r\n\r\n/*\r\n * Return true if the value of this Decimal is an integer, otherwise return false.\r\n *\r\n */\r\nP.isInteger = P.isInt = function () {\r\n return !!this.d && mathfloor(this.e / LOG_BASE) > this.d.length - 2;\r\n};\r\n\r\n\r\n/*\r\n * Return true if the value of this Decimal is NaN, otherwise return false.\r\n *\r\n */\r\nP.isNaN = function () {\r\n return !this.s;\r\n};\r\n\r\n\r\n/*\r\n * Return true if the value of this Decimal is negative, otherwise return false.\r\n *\r\n */\r\nP.isNegative = P.isNeg = function () {\r\n return this.s < 0;\r\n};\r\n\r\n\r\n/*\r\n * Return true if the value of this Decimal is positive, otherwise return false.\r\n *\r\n */\r\nP.isPositive = P.isPos = function () {\r\n return this.s > 0;\r\n};\r\n\r\n\r\n/*\r\n * Return true if the value of this Decimal is 0 or -0, otherwise return false.\r\n *\r\n */\r\nP.isZero = function () {\r\n return !!this.d && this.d[0] === 0;\r\n};\r\n\r\n\r\n/*\r\n * Return true if the value of this Decimal is less than `y`, otherwise return false.\r\n *\r\n */\r\nP.lessThan = P.lt = function (y) {\r\n return this.cmp(y) < 0;\r\n};\r\n\r\n\r\n/*\r\n * Return true if the value of this Decimal is less than or equal to `y`, otherwise return false.\r\n *\r\n */\r\nP.lessThanOrEqualTo = P.lte = function (y) {\r\n return this.cmp(y) < 1;\r\n};\r\n\r\n\r\n/*\r\n * Return the logarithm of the value of this Decimal to the specified base, rounded to `precision`\r\n * significant digits using rounding mode `rounding`.\r\n *\r\n * If no base is specified, return log[10](arg).\r\n *\r\n * log[base](arg) = ln(arg) / ln(base)\r\n *\r\n * The result will always be correctly rounded if the base of the log is 10, and 'almost always'\r\n * otherwise:\r\n *\r\n * Depending on the rounding mode, the result may be incorrectly rounded if the first fifteen\r\n * rounding digits are [49]99999999999999 or [50]00000000000000. In that case, the maximum error\r\n * between the result and the correctly rounded result will be one ulp (unit in the last place).\r\n *\r\n * log[-b](a) = NaN\r\n * log[0](a) = NaN\r\n * log[1](a) = NaN\r\n * log[NaN](a) = NaN\r\n * log[Infinity](a) = NaN\r\n * log[b](0) = -Infinity\r\n * log[b](-0) = -Infinity\r\n * log[b](-a) = NaN\r\n * log[b](1) = 0\r\n * log[b](Infinity) = Infinity\r\n * log[b](NaN) = NaN\r\n *\r\n * [base] {number|string|Decimal} The base of the logarithm.\r\n *\r\n */\r\nP.logarithm = P.log = function (base) {\r\n var isBase10, d, denominator, k, inf, num, sd, r,\r\n arg = this,\r\n Ctor = arg.constructor,\r\n pr = Ctor.precision,\r\n rm = Ctor.rounding,\r\n guard = 5;\r\n\r\n // Default base is 10.\r\n if (base == null) {\r\n base = new Ctor(10);\r\n isBase10 = true;\r\n } else {\r\n base = new Ctor(base);\r\n d = base.d;\r\n\r\n // Return NaN if base is negative, or non-finite, or is 0 or 1.\r\n if (base.s < 0 || !d || !d[0] || base.eq(1)) return new Ctor(NaN);\r\n\r\n isBase10 = base.eq(10);\r\n }\r\n\r\n d = arg.d;\r\n\r\n // Is arg negative, non-finite, 0 or 1?\r\n if (arg.s < 0 || !d || !d[0] || arg.eq(1)) {\r\n return new Ctor(d && !d[0] ? -1 / 0 : arg.s != 1 ? NaN : d ? 0 : 1 / 0);\r\n }\r\n\r\n // The result will have a non-terminating decimal expansion if base is 10 and arg is not an\r\n // integer power of 10.\r\n if (isBase10) {\r\n if (d.length > 1) {\r\n inf = true;\r\n } else {\r\n for (k = d[0]; k % 10 === 0;) k /= 10;\r\n inf = k !== 1;\r\n }\r\n }\r\n\r\n external = false;\r\n sd = pr + guard;\r\n num = naturalLogarithm(arg, sd);\r\n denominator = isBase10 ? getLn10(Ctor, sd + 10) : naturalLogarithm(base, sd);\r\n\r\n // The result will have 5 rounding digits.\r\n r = divide(num, denominator, sd, 1);\r\n\r\n // If at a rounding boundary, i.e. the result's rounding digits are [49]9999 or [50]0000,\r\n // calculate 10 further digits.\r\n //\r\n // If the result is known to have an infinite decimal expansion, repeat this until it is clear\r\n // that the result is above or below the boundary. Otherwise, if after calculating the 10\r\n // further digits, the last 14 are nines, round up and assume the result is exact.\r\n // Also assume the result is exact if the last 14 are zero.\r\n //\r\n // Example of a result that will be incorrectly rounded:\r\n // log[1048576](4503599627370502) = 2.60000000000000009610279511444746...\r\n // The above result correctly rounded using ROUND_CEIL to 1 decimal place should be 2.7, but it\r\n // will be given as 2.6 as there are 15 zeros immediately after the requested decimal place, so\r\n // the exact result would be assumed to be 2.6, which rounded using ROUND_CEIL to 1 decimal\r\n // place is still 2.6.\r\n if (checkRoundingDigits(r.d, k = pr, rm)) {\r\n\r\n do {\r\n sd += 10;\r\n num = naturalLogarithm(arg, sd);\r\n denominator = isBase10 ? getLn10(Ctor, sd + 10) : naturalLogarithm(base, sd);\r\n r = divide(num, denominator, sd, 1);\r\n\r\n if (!inf) {\r\n\r\n // Check for 14 nines from the 2nd rounding digit, as the first may be 4.\r\n if (+digitsToString(r.d).slice(k + 1, k + 15) + 1 == 1e14) {\r\n r = finalise(r, pr + 1, 0);\r\n }\r\n\r\n break;\r\n }\r\n } while (checkRoundingDigits(r.d, k += 10, rm));\r\n }\r\n\r\n external = true;\r\n\r\n return finalise(r, pr, rm);\r\n};\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is the maximum of the arguments and the value of this Decimal.\r\n *\r\n * arguments {number|string|Decimal}\r\n *\r\nP.max = function () {\r\n Array.prototype.push.call(arguments, this);\r\n return maxOrMin(this.constructor, arguments, 'lt');\r\n};\r\n */\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is the minimum of the arguments and the value of this Decimal.\r\n *\r\n * arguments {number|string|Decimal}\r\n *\r\nP.min = function () {\r\n Array.prototype.push.call(arguments, this);\r\n return maxOrMin(this.constructor, arguments, 'gt');\r\n};\r\n */\r\n\r\n\r\n/*\r\n * n - 0 = n\r\n * n - N = N\r\n * n - I = -I\r\n * 0 - n = -n\r\n * 0 - 0 = 0\r\n * 0 - N = N\r\n * 0 - I = -I\r\n * N - n = N\r\n * N - 0 = N\r\n * N - N = N\r\n * N - I = N\r\n * I - n = I\r\n * I - 0 = I\r\n * I - N = N\r\n * I - I = N\r\n *\r\n * Return a new Decimal whose value is the value of this Decimal minus `y`, rounded to `precision`\r\n * significant digits using rounding mode `rounding`.\r\n *\r\n */\r\nP.minus = P.sub = function (y) {\r\n var d, e, i, j, k, len, pr, rm, xd, xe, xLTy, yd,\r\n x = this,\r\n Ctor = x.constructor;\r\n\r\n y = new Ctor(y);\r\n\r\n // If either is not finite...\r\n if (!x.d || !y.d) {\r\n\r\n // Return NaN if either is NaN.\r\n if (!x.s || !y.s) y = new Ctor(NaN);\r\n\r\n // Return y negated if x is finite and y is ±Infinity.\r\n else if (x.d) y.s = -y.s;\r\n\r\n // Return x if y is finite and x is ±Infinity.\r\n // Return x if both are ±Infinity with different signs.\r\n // Return NaN if both are ±Infinity with the same sign.\r\n else y = new Ctor(y.d || x.s !== y.s ? x : NaN);\r\n\r\n return y;\r\n }\r\n\r\n // If signs differ...\r\n if (x.s != y.s) {\r\n y.s = -y.s;\r\n return x.plus(y);\r\n }\r\n\r\n xd = x.d;\r\n yd = y.d;\r\n pr = Ctor.precision;\r\n rm = Ctor.rounding;\r\n\r\n // If either is zero...\r\n if (!xd[0] || !yd[0]) {\r\n\r\n // Return y negated if x is zero and y is non-zero.\r\n if (yd[0]) y.s = -y.s;\r\n\r\n // Return x if y is zero and x is non-zero.\r\n else if (xd[0]) y = new Ctor(x);\r\n\r\n // Return zero if both are zero.\r\n // From IEEE 754 (2008) 6.3: 0 - 0 = -0 - -0 = -0 when rounding to -Infinity.\r\n else return new Ctor(rm === 3 ? -0 : 0);\r\n\r\n return external ? finalise(y, pr, rm) : y;\r\n }\r\n\r\n // x and y are finite, non-zero numbers with the same sign.\r\n\r\n // Calculate base 1e7 exponents.\r\n e = mathfloor(y.e / LOG_BASE);\r\n xe = mathfloor(x.e / LOG_BASE);\r\n\r\n xd = xd.slice();\r\n k = xe - e;\r\n\r\n // If base 1e7 exponents differ...\r\n if (k) {\r\n xLTy = k < 0;\r\n\r\n if (xLTy) {\r\n d = xd;\r\n k = -k;\r\n len = yd.length;\r\n } else {\r\n d = yd;\r\n e = xe;\r\n len = xd.length;\r\n }\r\n\r\n // Numbers with massively different exponents would result in a very high number of\r\n // zeros needing to be prepended, but this can be avoided while still ensuring correct\r\n // rounding by limiting the number of zeros to `Math.ceil(pr / LOG_BASE) + 2`.\r\n i = Math.max(Math.ceil(pr / LOG_BASE), len) + 2;\r\n\r\n if (k > i) {\r\n k = i;\r\n d.length = 1;\r\n }\r\n\r\n // Prepend zeros to equalise exponents.\r\n d.reverse();\r\n for (i = k; i--;) d.push(0);\r\n d.reverse();\r\n\r\n // Base 1e7 exponents equal.\r\n } else {\r\n\r\n // Check digits to determine which is the bigger number.\r\n\r\n i = xd.length;\r\n len = yd.length;\r\n xLTy = i < len;\r\n if (xLTy) len = i;\r\n\r\n for (i = 0; i < len; i++) {\r\n if (xd[i] != yd[i]) {\r\n xLTy = xd[i] < yd[i];\r\n break;\r\n }\r\n }\r\n\r\n k = 0;\r\n }\r\n\r\n if (xLTy) {\r\n d = xd;\r\n xd = yd;\r\n yd = d;\r\n y.s = -y.s;\r\n }\r\n\r\n len = xd.length;\r\n\r\n // Append zeros to `xd` if shorter.\r\n // Don't add zeros to `yd` if shorter as subtraction only needs to start at `yd` length.\r\n for (i = yd.length - len; i > 0; --i) xd[len++] = 0;\r\n\r\n // Subtract yd from xd.\r\n for (i = yd.length; i > k;) {\r\n\r\n if (xd[--i] < yd[i]) {\r\n for (j = i; j && xd[--j] === 0;) xd[j] = BASE - 1;\r\n --xd[j];\r\n xd[i] += BASE;\r\n }\r\n\r\n xd[i] -= yd[i];\r\n }\r\n\r\n // Remove trailing zeros.\r\n for (; xd[--len] === 0;) xd.pop();\r\n\r\n // Remove leading zeros and adjust exponent accordingly.\r\n for (; xd[0] === 0; xd.shift()) --e;\r\n\r\n // Zero?\r\n if (!xd[0]) return new Ctor(rm === 3 ? -0 : 0);\r\n\r\n y.d = xd;\r\n y.e = getBase10Exponent(xd, e);\r\n\r\n return external ? finalise(y, pr, rm) : y;\r\n};\r\n\r\n\r\n/*\r\n * n % 0 = N\r\n * n % N = N\r\n * n % I = n\r\n * 0 % n = 0\r\n * -0 % n = -0\r\n * 0 % 0 = N\r\n * 0 % N = N\r\n * 0 % I = 0\r\n * N % n = N\r\n * N % 0 = N\r\n * N % N = N\r\n * N % I = N\r\n * I % n = N\r\n * I % 0 = N\r\n * I % N = N\r\n * I % I = N\r\n *\r\n * Return a new Decimal whose value is the value of this Decimal modulo `y`, rounded to\r\n * `precision` significant digits using rounding mode `rounding`.\r\n *\r\n * The result depends on the modulo mode.\r\n *\r\n */\r\nP.modulo = P.mod = function (y) {\r\n var q,\r\n x = this,\r\n Ctor = x.constructor;\r\n\r\n y = new Ctor(y);\r\n\r\n // Return NaN if x is ±Infinity or NaN, or y is NaN or ±0.\r\n if (!x.d || !y.s || y.d && !y.d[0]) return new Ctor(NaN);\r\n\r\n // Return x if y is ±Infinity or x is ±0.\r\n if (!y.d || x.d && !x.d[0]) {\r\n return finalise(new Ctor(x), Ctor.precision, Ctor.rounding);\r\n }\r\n\r\n // Prevent rounding of intermediate calculations.\r\n external = false;\r\n\r\n if (Ctor.modulo == 9) {\r\n\r\n // Euclidian division: q = sign(y) * floor(x / abs(y))\r\n // result = x - q * y where 0 <= result < abs(y)\r\n q = divide(x, y.abs(), 0, 3, 1);\r\n q.s *= y.s;\r\n } else {\r\n q = divide(x, y, 0, Ctor.modulo, 1);\r\n }\r\n\r\n q = q.times(y);\r\n\r\n external = true;\r\n\r\n return x.minus(q);\r\n};\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is the natural exponential of the value of this Decimal,\r\n * i.e. the base e raised to the power the value of this Decimal, rounded to `precision`\r\n * significant digits using rounding mode `rounding`.\r\n *\r\n */\r\nP.naturalExponential = P.exp = function () {\r\n return naturalExponential(this);\r\n};\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is the natural logarithm of the value of this Decimal,\r\n * rounded to `precision` significant digits using rounding mode `rounding`.\r\n *\r\n */\r\nP.naturalLogarithm = P.ln = function () {\r\n return naturalLogarithm(this);\r\n};\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is the value of this Decimal negated, i.e. as if multiplied by\r\n * -1.\r\n *\r\n */\r\nP.negated = P.neg = function () {\r\n var x = new this.constructor(this);\r\n x.s = -x.s;\r\n return finalise(x);\r\n};\r\n\r\n\r\n/*\r\n * n + 0 = n\r\n * n + N = N\r\n * n + I = I\r\n * 0 + n = n\r\n * 0 + 0 = 0\r\n * 0 + N = N\r\n * 0 + I = I\r\n * N + n = N\r\n * N + 0 = N\r\n * N + N = N\r\n * N + I = N\r\n * I + n = I\r\n * I + 0 = I\r\n * I + N = N\r\n * I + I = I\r\n *\r\n * Return a new Decimal whose value is the value of this Decimal plus `y`, rounded to `precision`\r\n * significant digits using rounding mode `rounding`.\r\n *\r\n */\r\nP.plus = P.add = function (y) {\r\n var carry, d, e, i, k, len, pr, rm, xd, yd,\r\n x = this,\r\n Ctor = x.constructor;\r\n\r\n y = new Ctor(y);\r\n\r\n // If either is not finite...\r\n if (!x.d || !y.d) {\r\n\r\n // Return NaN if either is NaN.\r\n if (!x.s || !y.s) y = new Ctor(NaN);\r\n\r\n // Return x if y is finite and x is ±Infinity.\r\n // Return x if both are ±Infinity with the same sign.\r\n // Return NaN if both are ±Infinity with different signs.\r\n // Return y if x is finite and y is ±Infinity.\r\n else if (!x.d) y = new Ctor(y.d || x.s === y.s ? x : NaN);\r\n\r\n return y;\r\n }\r\n\r\n // If signs differ...\r\n if (x.s != y.s) {\r\n y.s = -y.s;\r\n return x.minus(y);\r\n }\r\n\r\n xd = x.d;\r\n yd = y.d;\r\n pr = Ctor.precision;\r\n rm = Ctor.rounding;\r\n\r\n // If either is zero...\r\n if (!xd[0] || !yd[0]) {\r\n\r\n // Return x if y is zero.\r\n // Return y if y is non-zero.\r\n if (!yd[0]) y = new Ctor(x);\r\n\r\n return external ? finalise(y, pr, rm) : y;\r\n }\r\n\r\n // x and y are finite, non-zero numbers with the same sign.\r\n\r\n // Calculate base 1e7 exponents.\r\n k = mathfloor(x.e / LOG_BASE);\r\n e = mathfloor(y.e / LOG_BASE);\r\n\r\n xd = xd.slice();\r\n i = k - e;\r\n\r\n // If base 1e7 exponents differ...\r\n if (i) {\r\n\r\n if (i < 0) {\r\n d = xd;\r\n i = -i;\r\n len = yd.length;\r\n } else {\r\n d = yd;\r\n e = k;\r\n len = xd.length;\r\n }\r\n\r\n // Limit number of zeros prepended to max(ceil(pr / LOG_BASE), len) + 1.\r\n k = Math.ceil(pr / LOG_BASE);\r\n len = k > len ? k + 1 : len + 1;\r\n\r\n if (i > len) {\r\n i = len;\r\n d.length = 1;\r\n }\r\n\r\n // Prepend zeros to equalise exponents. Note: Faster to use reverse then do unshifts.\r\n d.reverse();\r\n for (; i--;) d.push(0);\r\n d.reverse();\r\n }\r\n\r\n len = xd.length;\r\n i = yd.length;\r\n\r\n // If yd is longer than xd, swap xd and yd so xd points to the longer array.\r\n if (len - i < 0) {\r\n i = len;\r\n d = yd;\r\n yd = xd;\r\n xd = d;\r\n }\r\n\r\n // Only start adding at yd.length - 1 as the further digits of xd can be left as they are.\r\n for (carry = 0; i;) {\r\n carry = (xd[--i] = xd[i] + yd[i] + carry) / BASE | 0;\r\n xd[i] %= BASE;\r\n }\r\n\r\n if (carry) {\r\n xd.unshift(carry);\r\n ++e;\r\n }\r\n\r\n // Remove trailing zeros.\r\n // No need to check for zero, as +x + +y != 0 && -x + -y != 0\r\n for (len = xd.length; xd[--len] == 0;) xd.pop();\r\n\r\n y.d = xd;\r\n y.e = getBase10Exponent(xd, e);\r\n\r\n return external ? finalise(y, pr, rm) : y;\r\n};\r\n\r\n\r\n/*\r\n * Return the number of significant digits of the value of this Decimal.\r\n *\r\n * [z] {boolean|number} Whether to count integer-part trailing zeros: true, false, 1 or 0.\r\n *\r\n */\r\nP.precision = P.sd = function (z) {\r\n var k,\r\n x = this;\r\n\r\n if (z !== void 0 && z !== !!z && z !== 1 && z !== 0) throw Error(invalidArgument + z);\r\n\r\n if (x.d) {\r\n k = getPrecision(x.d);\r\n if (z && x.e + 1 > k) k = x.e + 1;\r\n } else {\r\n k = NaN;\r\n }\r\n\r\n return k;\r\n};\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is the value of this Decimal rounded to a whole number using\r\n * rounding mode `rounding`.\r\n *\r\n */\r\nP.round = function () {\r\n var x = this,\r\n Ctor = x.constructor;\r\n\r\n return finalise(new Ctor(x), x.e + 1, Ctor.rounding);\r\n};\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is the sine of the value in radians of this Decimal.\r\n *\r\n * Domain: [-Infinity, Infinity]\r\n * Range: [-1, 1]\r\n *\r\n * sin(x) = x - x^3/3! + x^5/5! - ...\r\n *\r\n * sin(0) = 0\r\n * sin(-0) = -0\r\n * sin(Infinity) = NaN\r\n * sin(-Infinity) = NaN\r\n * sin(NaN) = NaN\r\n *\r\n */\r\nP.sine = P.sin = function () {\r\n var pr, rm,\r\n x = this,\r\n Ctor = x.constructor;\r\n\r\n if (!x.isFinite()) return new Ctor(NaN);\r\n if (x.isZero()) return new Ctor(x);\r\n\r\n pr = Ctor.precision;\r\n rm = Ctor.rounding;\r\n Ctor.precision = pr + Math.max(x.e, x.sd()) + LOG_BASE;\r\n Ctor.rounding = 1;\r\n\r\n x = sine(Ctor, toLessThanHalfPi(Ctor, x));\r\n\r\n Ctor.precision = pr;\r\n Ctor.rounding = rm;\r\n\r\n return finalise(quadrant > 2 ? x.neg() : x, pr, rm, true);\r\n};\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is the square root of this Decimal, rounded to `precision`\r\n * significant digits using rounding mode `rounding`.\r\n *\r\n * sqrt(-n) = N\r\n * sqrt(N) = N\r\n * sqrt(-I) = N\r\n * sqrt(I) = I\r\n * sqrt(0) = 0\r\n * sqrt(-0) = -0\r\n *\r\n */\r\nP.squareRoot = P.sqrt = function () {\r\n var m, n, sd, r, rep, t,\r\n x = this,\r\n d = x.d,\r\n e = x.e,\r\n s = x.s,\r\n Ctor = x.constructor;\r\n\r\n // Negative/NaN/Infinity/zero?\r\n if (s !== 1 || !d || !d[0]) {\r\n return new Ctor(!s || s < 0 && (!d || d[0]) ? NaN : d ? x : 1 / 0);\r\n }\r\n\r\n external = false;\r\n\r\n // Initial estimate.\r\n s = Math.sqrt(+x);\r\n\r\n // Math.sqrt underflow/overflow?\r\n // Pass x to Math.sqrt as integer, then adjust the exponent of the result.\r\n if (s == 0 || s == 1 / 0) {\r\n n = digitsToString(d);\r\n\r\n if ((n.length + e) % 2 == 0) n += '0';\r\n s = Math.sqrt(n);\r\n e = mathfloor((e + 1) / 2) - (e < 0 || e % 2);\r\n\r\n if (s == 1 / 0) {\r\n n = '5e' + e;\r\n } else {\r\n n = s.toExponential();\r\n n = n.slice(0, n.indexOf('e') + 1) + e;\r\n }\r\n\r\n r = new Ctor(n);\r\n } else {\r\n r = new Ctor(s.toString());\r\n }\r\n\r\n sd = (e = Ctor.precision) + 3;\r\n\r\n // Newton-Raphson iteration.\r\n for (;;) {\r\n t = r;\r\n r = t.plus(divide(x, t, sd + 2, 1)).times(0.5);\r\n\r\n // TODO? Replace with for-loop and checkRoundingDigits.\r\n if (digitsToString(t.d).slice(0, sd) === (n = digitsToString(r.d)).slice(0, sd)) {\r\n n = n.slice(sd - 3, sd + 1);\r\n\r\n // The 4th rounding digit may be in error by -1 so if the 4 rounding digits are 9999 or\r\n // 4999, i.e. approaching a rounding boundary, continue the iteration.\r\n if (n == '9999' || !rep && n == '4999') {\r\n\r\n // On the first iteration only, check to see if rounding up gives the exact result as the\r\n // nines may infinitely repeat.\r\n if (!rep) {\r\n finalise(t, e + 1, 0);\r\n\r\n if (t.times(t).eq(x)) {\r\n r = t;\r\n break;\r\n }\r\n }\r\n\r\n sd += 4;\r\n rep = 1;\r\n } else {\r\n\r\n // If the rounding digits are null, 0{0,4} or 50{0,3}, check for an exact result.\r\n // If not, then there are further digits and m will be truthy.\r\n if (!+n || !+n.slice(1) && n.charAt(0) == '5') {\r\n\r\n // Truncate to the first rounding digit.\r\n finalise(r, e + 1, 1);\r\n m = !r.times(r).eq(x);\r\n }\r\n\r\n break;\r\n }\r\n }\r\n }\r\n\r\n external = true;\r\n\r\n return finalise(r, e, Ctor.rounding, m);\r\n};\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is the tangent of the value in radians of this Decimal.\r\n *\r\n * Domain: [-Infinity, Infinity]\r\n * Range: [-Infinity, Infinity]\r\n *\r\n * tan(0) = 0\r\n * tan(-0) = -0\r\n * tan(Infinity) = NaN\r\n * tan(-Infinity) = NaN\r\n * tan(NaN) = NaN\r\n *\r\n */\r\nP.tangent = P.tan = function () {\r\n var pr, rm,\r\n x = this,\r\n Ctor = x.constructor;\r\n\r\n if (!x.isFinite()) return new Ctor(NaN);\r\n if (x.isZero()) return new Ctor(x);\r\n\r\n pr = Ctor.precision;\r\n rm = Ctor.rounding;\r\n Ctor.precision = pr + 10;\r\n Ctor.rounding = 1;\r\n\r\n x = x.sin();\r\n x.s = 1;\r\n x = divide(x, new Ctor(1).minus(x.times(x)).sqrt(), pr + 10, 0);\r\n\r\n Ctor.precision = pr;\r\n Ctor.rounding = rm;\r\n\r\n return finalise(quadrant == 2 || quadrant == 4 ? x.neg() : x, pr, rm, true);\r\n};\r\n\r\n\r\n/*\r\n * n * 0 = 0\r\n * n * N = N\r\n * n * I = I\r\n * 0 * n = 0\r\n * 0 * 0 = 0\r\n * 0 * N = N\r\n * 0 * I = N\r\n * N * n = N\r\n * N * 0 = N\r\n * N * N = N\r\n * N * I = N\r\n * I * n = I\r\n * I * 0 = N\r\n * I * N = N\r\n * I * I = I\r\n *\r\n * Return a new Decimal whose value is this Decimal times `y`, rounded to `precision` significant\r\n * digits using rounding mode `rounding`.\r\n *\r\n */\r\nP.times = P.mul = function (y) {\r\n var carry, e, i, k, r, rL, t, xdL, ydL,\r\n x = this,\r\n Ctor = x.constructor,\r\n xd = x.d,\r\n yd = (y = new Ctor(y)).d;\r\n\r\n y.s *= x.s;\r\n\r\n // If either is NaN, ±Infinity or ±0...\r\n if (!xd || !xd[0] || !yd || !yd[0]) {\r\n\r\n return new Ctor(!y.s || xd && !xd[0] && !yd || yd && !yd[0] && !xd\r\n\r\n // Return NaN if either is NaN.\r\n // Return NaN if x is ±0 and y is ±Infinity, or y is ±0 and x is ±Infinity.\r\n ? NaN\r\n\r\n // Return ±Infinity if either is ±Infinity.\r\n // Return ±0 if either is ±0.\r\n : !xd || !yd ? y.s / 0 : y.s * 0);\r\n }\r\n\r\n e = mathfloor(x.e / LOG_BASE) + mathfloor(y.e / LOG_BASE);\r\n xdL = xd.length;\r\n ydL = yd.length;\r\n\r\n // Ensure xd points to the longer array.\r\n if (xdL < ydL) {\r\n r = xd;\r\n xd = yd;\r\n yd = r;\r\n rL = xdL;\r\n xdL = ydL;\r\n ydL = rL;\r\n }\r\n\r\n // Initialise the result array with zeros.\r\n r = [];\r\n rL = xdL + ydL;\r\n for (i = rL; i--;) r.push(0);\r\n\r\n // Multiply!\r\n for (i = ydL; --i >= 0;) {\r\n carry = 0;\r\n for (k = xdL + i; k > i;) {\r\n t = r[k] + yd[i] * xd[k - i - 1] + carry;\r\n r[k--] = t % BASE | 0;\r\n carry = t / BASE | 0;\r\n }\r\n\r\n r[k] = (r[k] + carry) % BASE | 0;\r\n }\r\n\r\n // Remove trailing zeros.\r\n for (; !r[--rL];) r.pop();\r\n\r\n if (carry) ++e;\r\n else r.shift();\r\n\r\n y.d = r;\r\n y.e = getBase10Exponent(r, e);\r\n\r\n return external ? finalise(y, Ctor.precision, Ctor.rounding) : y;\r\n};\r\n\r\n\r\n/*\r\n * Return a string representing the value of this Decimal in base 2, round to `sd` significant\r\n * digits using rounding mode `rm`.\r\n *\r\n * If the optional `sd` argument is present then return binary exponential notation.\r\n *\r\n * [sd] {number} Significant digits. Integer, 1 to MAX_DIGITS inclusive.\r\n * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.\r\n *\r\n */\r\nP.toBinary = function (sd, rm) {\r\n return toStringBinary(this, 2, sd, rm);\r\n};\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is the value of this Decimal rounded to a maximum of `dp`\r\n * decimal places using rounding mode `rm` or `rounding` if `rm` is omitted.\r\n *\r\n * If `dp` is omitted, return a new Decimal whose value is the value of this Decimal.\r\n *\r\n * [dp] {number} Decimal places. Integer, 0 to MAX_DIGITS inclusive.\r\n * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.\r\n *\r\n */\r\nP.toDecimalPlaces = P.toDP = function (dp, rm) {\r\n var x = this,\r\n Ctor = x.constructor;\r\n\r\n x = new Ctor(x);\r\n if (dp === void 0) return x;\r\n\r\n checkInt32(dp, 0, MAX_DIGITS);\r\n\r\n if (rm === void 0) rm = Ctor.rounding;\r\n else checkInt32(rm, 0, 8);\r\n\r\n return finalise(x, dp + x.e + 1, rm);\r\n};\r\n\r\n\r\n/*\r\n * Return a string representing the value of this Decimal in exponential notation rounded to\r\n * `dp` fixed decimal places using rounding mode `rounding`.\r\n *\r\n * [dp] {number} Decimal places. Integer, 0 to MAX_DIGITS inclusive.\r\n * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.\r\n *\r\n */\r\nP.toExponential = function (dp, rm) {\r\n var str,\r\n x = this,\r\n Ctor = x.constructor;\r\n\r\n if (dp === void 0) {\r\n str = finiteToString(x, true);\r\n } else {\r\n checkInt32(dp, 0, MAX_DIGITS);\r\n\r\n if (rm === void 0) rm = Ctor.rounding;\r\n else checkInt32(rm, 0, 8);\r\n\r\n x = finalise(new Ctor(x), dp + 1, rm);\r\n str = finiteToString(x, true, dp + 1);\r\n }\r\n\r\n return x.isNeg() && !x.isZero() ? '-' + str : str;\r\n};\r\n\r\n\r\n/*\r\n * Return a string representing the value of this Decimal in normal (fixed-point) notation to\r\n * `dp` fixed decimal places and rounded using rounding mode `rm` or `rounding` if `rm` is\r\n * omitted.\r\n *\r\n * As with JavaScript numbers, (-0).toFixed(0) is '0', but e.g. (-0.00001).toFixed(0) is '-0'.\r\n *\r\n * [dp] {number} Decimal places. Integer, 0 to MAX_DIGITS inclusive.\r\n * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.\r\n *\r\n * (-0).toFixed(0) is '0', but (-0.1).toFixed(0) is '-0'.\r\n * (-0).toFixed(1) is '0.0', but (-0.01).toFixed(1) is '-0.0'.\r\n * (-0).toFixed(3) is '0.000'.\r\n * (-0.5).toFixed(0) is '-0'.\r\n *\r\n */\r\nP.toFixed = function (dp, rm) {\r\n var str, y,\r\n x = this,\r\n Ctor = x.constructor;\r\n\r\n if (dp === void 0) {\r\n str = finiteToString(x);\r\n } else {\r\n checkInt32(dp, 0, MAX_DIGITS);\r\n\r\n if (rm === void 0) rm = Ctor.rounding;\r\n else checkInt32(rm, 0, 8);\r\n\r\n y = finalise(new Ctor(x), dp + x.e + 1, rm);\r\n str = finiteToString(y, false, dp + y.e + 1);\r\n }\r\n\r\n // To determine whether to add the minus sign look at the value before it was rounded,\r\n // i.e. look at `x` rather than `y`.\r\n return x.isNeg() && !x.isZero() ? '-' + str : str;\r\n};\r\n\r\n\r\n/*\r\n * Return an array representing the value of this Decimal as a simple fraction with an integer\r\n * numerator and an integer denominator.\r\n *\r\n * The denominator will be a positive non-zero value less than or equal to the specified maximum\r\n * denominator. If a maximum denominator is not specified, the denominator will be the lowest\r\n * value necessary to represent the number exactly.\r\n *\r\n * [maxD] {number|string|Decimal} Maximum denominator. Integer >= 1 and < Infinity.\r\n *\r\n */\r\nP.toFraction = function (maxD) {\r\n var d, d0, d1, d2, e, k, n, n0, n1, pr, q, r,\r\n x = this,\r\n xd = x.d,\r\n Ctor = x.constructor;\r\n\r\n if (!xd) return new Ctor(x);\r\n\r\n n1 = d0 = new Ctor(1);\r\n d1 = n0 = new Ctor(0);\r\n\r\n d = new Ctor(d1);\r\n e = d.e = getPrecision(xd) - x.e - 1;\r\n k = e % LOG_BASE;\r\n d.d[0] = mathpow(10, k < 0 ? LOG_BASE + k : k);\r\n\r\n if (maxD == null) {\r\n\r\n // d is 10**e, the minimum max-denominator needed.\r\n maxD = e > 0 ? d : n1;\r\n } else {\r\n n = new Ctor(maxD);\r\n if (!n.isInt() || n.lt(n1)) throw Error(invalidArgument + n);\r\n maxD = n.gt(d) ? (e > 0 ? d : n1) : n;\r\n }\r\n\r\n external = false;\r\n n = new Ctor(digitsToString(xd));\r\n pr = Ctor.precision;\r\n Ctor.precision = e = xd.length * LOG_BASE * 2;\r\n\r\n for (;;) {\r\n q = divide(n, d, 0, 1, 1);\r\n d2 = d0.plus(q.times(d1));\r\n if (d2.cmp(maxD) == 1) break;\r\n d0 = d1;\r\n d1 = d2;\r\n d2 = n1;\r\n n1 = n0.plus(q.times(d2));\r\n n0 = d2;\r\n d2 = d;\r\n d = n.minus(q.times(d2));\r\n n = d2;\r\n }\r\n\r\n d2 = divide(maxD.minus(d0), d1, 0, 1, 1);\r\n n0 = n0.plus(d2.times(n1));\r\n d0 = d0.plus(d2.times(d1));\r\n n0.s = n1.s = x.s;\r\n\r\n // Determine which fraction is closer to x, n0/d0 or n1/d1?\r\n r = divide(n1, d1, e, 1).minus(x).abs().cmp(divide(n0, d0, e, 1).minus(x).abs()) < 1\r\n ? [n1, d1] : [n0, d0];\r\n\r\n Ctor.precision = pr;\r\n external = true;\r\n\r\n return r;\r\n};\r\n\r\n\r\n/*\r\n * Return a string representing the value of this Decimal in base 16, round to `sd` significant\r\n * digits using rounding mode `rm`.\r\n *\r\n * If the optional `sd` argument is present then return binary exponential notation.\r\n *\r\n * [sd] {number} Significant digits. Integer, 1 to MAX_DIGITS inclusive.\r\n * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.\r\n *\r\n */\r\nP.toHexadecimal = P.toHex = function (sd, rm) {\r\n return toStringBinary(this, 16, sd, rm);\r\n};\r\n\r\n\r\n/*\r\n * Returns a new Decimal whose value is the nearest multiple of `y` in the direction of rounding\r\n * mode `rm`, or `Decimal.rounding` if `rm` is omitted, to the value of this Decimal.\r\n *\r\n * The return value will always have the same sign as this Decimal, unless either this Decimal\r\n * or `y` is NaN, in which case the return value will be also be NaN.\r\n *\r\n * The return value is not affected by the value of `precision`.\r\n *\r\n * y {number|string|Decimal} The magnitude to round to a multiple of.\r\n * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.\r\n *\r\n * 'toNearest() rounding mode not an integer: {rm}'\r\n * 'toNearest() rounding mode out of range: {rm}'\r\n *\r\n */\r\nP.toNearest = function (y, rm) {\r\n var x = this,\r\n Ctor = x.constructor;\r\n\r\n x = new Ctor(x);\r\n\r\n if (y == null) {\r\n\r\n // If x is not finite, return x.\r\n if (!x.d) return x;\r\n\r\n y = new Ctor(1);\r\n rm = Ctor.rounding;\r\n } else {\r\n y = new Ctor(y);\r\n if (rm === void 0) {\r\n rm = Ctor.rounding;\r\n } else {\r\n checkInt32(rm, 0, 8);\r\n }\r\n\r\n // If x is not finite, return x if y is not NaN, else NaN.\r\n if (!x.d) return y.s ? x : y;\r\n\r\n // If y is not finite, return Infinity with the sign of x if y is Infinity, else NaN.\r\n if (!y.d) {\r\n if (y.s) y.s = x.s;\r\n return y;\r\n }\r\n }\r\n\r\n // If y is not zero, calculate the nearest multiple of y to x.\r\n if (y.d[0]) {\r\n external = false;\r\n x = divide(x, y, 0, rm, 1).times(y);\r\n external = true;\r\n finalise(x);\r\n\r\n // If y is zero, return zero with the sign of x.\r\n } else {\r\n y.s = x.s;\r\n x = y;\r\n }\r\n\r\n return x;\r\n};\r\n\r\n\r\n/*\r\n * Return the value of this Decimal converted to a number primitive.\r\n * Zero keeps its sign.\r\n *\r\n */\r\nP.toNumber = function () {\r\n return +this;\r\n};\r\n\r\n\r\n/*\r\n * Return a string representing the value of this Decimal in base 8, round to `sd` significant\r\n * digits using rounding mode `rm`.\r\n *\r\n * If the optional `sd` argument is present then return binary exponential notation.\r\n *\r\n * [sd] {number} Significant digits. Integer, 1 to MAX_DIGITS inclusive.\r\n * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.\r\n *\r\n */\r\nP.toOctal = function (sd, rm) {\r\n return toStringBinary(this, 8, sd, rm);\r\n};\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is the value of this Decimal raised to the power `y`, rounded\r\n * to `precision` significant digits using rounding mode `rounding`.\r\n *\r\n * ECMAScript compliant.\r\n *\r\n * pow(x, NaN) = NaN\r\n * pow(x, ±0) = 1\r\n\r\n * pow(NaN, non-zero) = NaN\r\n * pow(abs(x) > 1, +Infinity) = +Infinity\r\n * pow(abs(x) > 1, -Infinity) = +0\r\n * pow(abs(x) == 1, ±Infinity) = NaN\r\n * pow(abs(x) < 1, +Infinity) = +0\r\n * pow(abs(x) < 1, -Infinity) = +Infinity\r\n * pow(+Infinity, y > 0) = +Infinity\r\n * pow(+Infinity, y < 0) = +0\r\n * pow(-Infinity, odd integer > 0) = -Infinity\r\n * pow(-Infinity, even integer > 0) = +Infinity\r\n * pow(-Infinity, odd integer < 0) = -0\r\n * pow(-Infinity, even integer < 0) = +0\r\n * pow(+0, y > 0) = +0\r\n * pow(+0, y < 0) = +Infinity\r\n * pow(-0, odd integer > 0) = -0\r\n * pow(-0, even integer > 0) = +0\r\n * pow(-0, odd integer < 0) = -Infinity\r\n * pow(-0, even integer < 0) = +Infinity\r\n * pow(finite x < 0, finite non-integer) = NaN\r\n *\r\n * For non-integer or very large exponents pow(x, y) is calculated using\r\n *\r\n * x^y = exp(y*ln(x))\r\n *\r\n * Assuming the first 15 rounding digits are each equally likely to be any digit 0-9, the\r\n * probability of an incorrectly rounded result\r\n * P([49]9{14} | [50]0{14}) = 2 * 0.2 * 10^-14 = 4e-15 = 1/2.5e+14\r\n * i.e. 1 in 250,000,000,000,000\r\n *\r\n * If a result is incorrectly rounded the maximum error will be 1 ulp (unit in last place).\r\n *\r\n * y {number|string|Decimal} The power to which to raise this Decimal.\r\n *\r\n */\r\nP.toPower = P.pow = function (y) {\r\n var e, k, pr, r, rm, s,\r\n x = this,\r\n Ctor = x.constructor,\r\n yn = +(y = new Ctor(y));\r\n\r\n // Either ±Infinity, NaN or ±0?\r\n if (!x.d || !y.d || !x.d[0] || !y.d[0]) return new Ctor(mathpow(+x, yn));\r\n\r\n x = new Ctor(x);\r\n\r\n if (x.eq(1)) return x;\r\n\r\n pr = Ctor.precision;\r\n rm = Ctor.rounding;\r\n\r\n if (y.eq(1)) return finalise(x, pr, rm);\r\n\r\n // y exponent\r\n e = mathfloor(y.e / LOG_BASE);\r\n\r\n // If y is a small integer use the 'exponentiation by squaring' algorithm.\r\n if (e >= y.d.length - 1 && (k = yn < 0 ? -yn : yn) <= MAX_SAFE_INTEGER) {\r\n r = intPow(Ctor, x, k, pr);\r\n return y.s < 0 ? new Ctor(1).div(r) : finalise(r, pr, rm);\r\n }\r\n\r\n s = x.s;\r\n\r\n // if x is negative\r\n if (s < 0) {\r\n\r\n // if y is not an integer\r\n if (e < y.d.length - 1) return new Ctor(NaN);\r\n\r\n // Result is positive if x is negative and the last digit of integer y is even.\r\n if ((y.d[e] & 1) == 0) s = 1;\r\n\r\n // if x.eq(-1)\r\n if (x.e == 0 && x.d[0] == 1 && x.d.length == 1) {\r\n x.s = s;\r\n return x;\r\n }\r\n }\r\n\r\n // Estimate result exponent.\r\n // x^y = 10^e, where e = y * log10(x)\r\n // log10(x) = log10(x_significand) + x_exponent\r\n // log10(x_significand) = ln(x_significand) / ln(10)\r\n k = mathpow(+x, yn);\r\n e = k == 0 || !isFinite(k)\r\n ? mathfloor(yn * (Math.log('0.' + digitsToString(x.d)) / Math.LN10 + x.e + 1))\r\n : new Ctor(k + '').e;\r\n\r\n // Exponent estimate may be incorrect e.g. x: 0.999999999999999999, y: 2.29, e: 0, r.e: -1.\r\n\r\n // Overflow/underflow?\r\n if (e > Ctor.maxE + 1 || e < Ctor.minE - 1) return new Ctor(e > 0 ? s / 0 : 0);\r\n\r\n external = false;\r\n Ctor.rounding = x.s = 1;\r\n\r\n // Estimate the extra guard digits needed to ensure five correct rounding digits from\r\n // naturalLogarithm(x). Example of failure without these extra digits (precision: 10):\r\n // new Decimal(2.32456).pow('2087987436534566.46411')\r\n // should be 1.162377823e+764914905173815, but is 1.162355823e+764914905173815\r\n k = Math.min(12, (e + '').length);\r\n\r\n // r = x^y = exp(y*ln(x))\r\n r = naturalExponential(y.times(naturalLogarithm(x, pr + k)), pr);\r\n\r\n // r may be Infinity, e.g. (0.9999999999999999).pow(-1e+40)\r\n if (r.d) {\r\n\r\n // Truncate to the required precision plus five rounding digits.\r\n r = finalise(r, pr + 5, 1);\r\n\r\n // If the rounding digits are [49]9999 or [50]0000 increase the precision by 10 and recalculate\r\n // the result.\r\n if (checkRoundingDigits(r.d, pr, rm)) {\r\n e = pr + 10;\r\n\r\n // Truncate to the increased precision plus five rounding digits.\r\n r = finalise(naturalExponential(y.times(naturalLogarithm(x, e + k)), e), e + 5, 1);\r\n\r\n // Check for 14 nines from the 2nd rounding digit (the first rounding digit may be 4 or 9).\r\n if (+digitsToString(r.d).slice(pr + 1, pr + 15) + 1 == 1e14) {\r\n r = finalise(r, pr + 1, 0);\r\n }\r\n }\r\n }\r\n\r\n r.s = s;\r\n external = true;\r\n Ctor.rounding = rm;\r\n\r\n return finalise(r, pr, rm);\r\n};\r\n\r\n\r\n/*\r\n * Return a string representing the value of this Decimal rounded to `sd` significant digits\r\n * using rounding mode `rounding`.\r\n *\r\n * Return exponential notation if `sd` is less than the number of digits necessary to represent\r\n * the integer part of the value in normal notation.\r\n *\r\n * [sd] {number} Significant digits. Integer, 1 to MAX_DIGITS inclusive.\r\n * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.\r\n *\r\n */\r\nP.toPrecision = function (sd, rm) {\r\n var str,\r\n x = this,\r\n Ctor = x.constructor;\r\n\r\n if (sd === void 0) {\r\n str = finiteToString(x, x.e <= Ctor.toExpNeg || x.e >= Ctor.toExpPos);\r\n } else {\r\n checkInt32(sd, 1, MAX_DIGITS);\r\n\r\n if (rm === void 0) rm = Ctor.rounding;\r\n else checkInt32(rm, 0, 8);\r\n\r\n x = finalise(new Ctor(x), sd, rm);\r\n str = finiteToString(x, sd <= x.e || x.e <= Ctor.toExpNeg, sd);\r\n }\r\n\r\n return x.isNeg() && !x.isZero() ? '-' + str : str;\r\n};\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is the value of this Decimal rounded to a maximum of `sd`\r\n * significant digits using rounding mode `rm`, or to `precision` and `rounding` respectively if\r\n * omitted.\r\n *\r\n * [sd] {number} Significant digits. Integer, 1 to MAX_DIGITS inclusive.\r\n * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.\r\n *\r\n * 'toSD() digits out of range: {sd}'\r\n * 'toSD() digits not an integer: {sd}'\r\n * 'toSD() rounding mode not an integer: {rm}'\r\n * 'toSD() rounding mode out of range: {rm}'\r\n *\r\n */\r\nP.toSignificantDigits = P.toSD = function (sd, rm) {\r\n var x = this,\r\n Ctor = x.constructor;\r\n\r\n if (sd === void 0) {\r\n sd = Ctor.precision;\r\n rm = Ctor.rounding;\r\n } else {\r\n checkInt32(sd, 1, MAX_DIGITS);\r\n\r\n if (rm === void 0) rm = Ctor.rounding;\r\n else checkInt32(rm, 0, 8);\r\n }\r\n\r\n return finalise(new Ctor(x), sd, rm);\r\n};\r\n\r\n\r\n/*\r\n * Return a string representing the value of this Decimal.\r\n *\r\n * Return exponential notation if this Decimal has a positive exponent equal to or greater than\r\n * `toExpPos`, or a negative exponent equal to or less than `toExpNeg`.\r\n *\r\n */\r\nP.toString = function () {\r\n var x = this,\r\n Ctor = x.constructor,\r\n str = finiteToString(x, x.e <= Ctor.toExpNeg || x.e >= Ctor.toExpPos);\r\n\r\n return x.isNeg() && !x.isZero() ? '-' + str : str;\r\n};\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is the value of this Decimal truncated to a whole number.\r\n *\r\n */\r\nP.truncated = P.trunc = function () {\r\n return finalise(new this.constructor(this), this.e + 1, 1);\r\n};\r\n\r\n\r\n/*\r\n * Return a string representing the value of this Decimal.\r\n * Unlike `toString`, negative zero will include the minus sign.\r\n *\r\n */\r\nP.valueOf = P.toJSON = function () {\r\n var x = this,\r\n Ctor = x.constructor,\r\n str = finiteToString(x, x.e <= Ctor.toExpNeg || x.e >= Ctor.toExpPos);\r\n\r\n return x.isNeg() ? '-' + str : str;\r\n};\r\n\r\n\r\n// Helper functions for Decimal.prototype (P) and/or Decimal methods, and their callers.\r\n\r\n\r\n/*\r\n * digitsToString P.cubeRoot, P.logarithm, P.squareRoot, P.toFraction, P.toPower,\r\n * finiteToString, naturalExponential, naturalLogarithm\r\n * checkInt32 P.toDecimalPlaces, P.toExponential, P.toFixed, P.toNearest,\r\n * P.toPrecision, P.toSignificantDigits, toStringBinary, random\r\n * checkRoundingDigits P.logarithm, P.toPower, naturalExponential, naturalLogarithm\r\n * convertBase toStringBinary, parseOther\r\n * cos P.cos\r\n * divide P.atanh, P.cubeRoot, P.dividedBy, P.dividedToIntegerBy,\r\n * P.logarithm, P.modulo, P.squareRoot, P.tan, P.tanh, P.toFraction,\r\n * P.toNearest, toStringBinary, naturalExponential, naturalLogarithm,\r\n * taylorSeries, atan2, parseOther\r\n * finalise P.absoluteValue, P.atan, P.atanh, P.ceil, P.cos, P.cosh,\r\n * P.cubeRoot, P.dividedToIntegerBy, P.floor, P.logarithm, P.minus,\r\n * P.modulo, P.negated, P.plus, P.round, P.sin, P.sinh, P.squareRoot,\r\n * P.tan, P.times, P.toDecimalPlaces, P.toExponential, P.toFixed,\r\n * P.toNearest, P.toPower, P.toPrecision, P.toSignificantDigits,\r\n * P.truncated, divide, getLn10, getPi, naturalExponential,\r\n * naturalLogarithm, ceil, floor, round, trunc\r\n * finiteToString P.toExponential, P.toFixed, P.toPrecision, P.toString, P.valueOf,\r\n * toStringBinary\r\n * getBase10Exponent P.minus, P.plus, P.times, parseOther\r\n * getLn10 P.logarithm, naturalLogarithm\r\n * getPi P.acos, P.asin, P.atan, toLessThanHalfPi, atan2\r\n * getPrecision P.precision, P.toFraction\r\n * getZeroString digitsToString, finiteToString\r\n * intPow P.toPower, parseOther\r\n * isOdd toLessThanHalfPi\r\n * maxOrMin max, min\r\n * naturalExponential P.naturalExponential, P.toPower\r\n * naturalLogarithm P.acosh, P.asinh, P.atanh, P.logarithm, P.naturalLogarithm,\r\n * P.toPower, naturalExponential\r\n * nonFiniteToString finiteToString, toStringBinary\r\n * parseDecimal Decimal\r\n * parseOther Decimal\r\n * sin P.sin\r\n * taylorSeries P.cosh, P.sinh, cos, sin\r\n * toLessThanHalfPi P.cos, P.sin\r\n * toStringBinary P.toBinary, P.toHexadecimal, P.toOctal\r\n * truncate intPow\r\n *\r\n * Throws: P.logarithm, P.precision, P.toFraction, checkInt32, getLn10, getPi,\r\n * naturalLogarithm, config, parseOther, random, Decimal\r\n */\r\n\r\n\r\nfunction digitsToString(d) {\r\n var i, k, ws,\r\n indexOfLastWord = d.length - 1,\r\n str = '',\r\n w = d[0];\r\n\r\n if (indexOfLastWord > 0) {\r\n str += w;\r\n for (i = 1; i < indexOfLastWord; i++) {\r\n ws = d[i] + '';\r\n k = LOG_BASE - ws.length;\r\n if (k) str += getZeroString(k);\r\n str += ws;\r\n }\r\n\r\n w = d[i];\r\n ws = w + '';\r\n k = LOG_BASE - ws.length;\r\n if (k) str += getZeroString(k);\r\n } else if (w === 0) {\r\n return '0';\r\n }\r\n\r\n // Remove trailing zeros of last w.\r\n for (; w % 10 === 0;) w /= 10;\r\n\r\n return str + w;\r\n}\r\n\r\n\r\nfunction checkInt32(i, min, max) {\r\n if (i !== ~~i || i < min || i > max) {\r\n throw Error(invalidArgument + i);\r\n }\r\n}\r\n\r\n\r\n/*\r\n * Check 5 rounding digits if `repeating` is null, 4 otherwise.\r\n * `repeating == null` if caller is `log` or `pow`,\r\n * `repeating != null` if caller is `naturalLogarithm` or `naturalExponential`.\r\n */\r\nfunction checkRoundingDigits(d, i, rm, repeating) {\r\n var di, k, r, rd;\r\n\r\n // Get the length of the first word of the array d.\r\n for (k = d[0]; k >= 10; k /= 10) --i;\r\n\r\n // Is the rounding digit in the first word of d?\r\n if (--i < 0) {\r\n i += LOG_BASE;\r\n di = 0;\r\n } else {\r\n di = Math.ceil((i + 1) / LOG_BASE);\r\n i %= LOG_BASE;\r\n }\r\n\r\n // i is the index (0 - 6) of the rounding digit.\r\n // E.g. if within the word 3487563 the first rounding digit is 5,\r\n // then i = 4, k = 1000, rd = 3487563 % 1000 = 563\r\n k = mathpow(10, LOG_BASE - i);\r\n rd = d[di] % k | 0;\r\n\r\n if (repeating == null) {\r\n if (i < 3) {\r\n if (i == 0) rd = rd / 100 | 0;\r\n else if (i == 1) rd = rd / 10 | 0;\r\n r = rm < 4 && rd == 99999 || rm > 3 && rd == 49999 || rd == 50000 || rd == 0;\r\n } else {\r\n r = (rm < 4 && rd + 1 == k || rm > 3 && rd + 1 == k / 2) &&\r\n (d[di + 1] / k / 100 | 0) == mathpow(10, i - 2) - 1 ||\r\n (rd == k / 2 || rd == 0) && (d[di + 1] / k / 100 | 0) == 0;\r\n }\r\n } else {\r\n if (i < 4) {\r\n if (i == 0) rd = rd / 1000 | 0;\r\n else if (i == 1) rd = rd / 100 | 0;\r\n else if (i == 2) rd = rd / 10 | 0;\r\n r = (repeating || rm < 4) && rd == 9999 || !repeating && rm > 3 && rd == 4999;\r\n } else {\r\n r = ((repeating || rm < 4) && rd + 1 == k ||\r\n (!repeating && rm > 3) && rd + 1 == k / 2) &&\r\n (d[di + 1] / k / 1000 | 0) == mathpow(10, i - 3) - 1;\r\n }\r\n }\r\n\r\n return r;\r\n}\r\n\r\n\r\n// Convert string of `baseIn` to an array of numbers of `baseOut`.\r\n// Eg. convertBase('255', 10, 16) returns [15, 15].\r\n// Eg. convertBase('ff', 16, 10) returns [2, 5, 5].\r\nfunction convertBase(str, baseIn, baseOut) {\r\n var j,\r\n arr = [0],\r\n arrL,\r\n i = 0,\r\n strL = str.length;\r\n\r\n for (; i < strL;) {\r\n for (arrL = arr.length; arrL--;) arr[arrL] *= baseIn;\r\n arr[0] += NUMERALS.indexOf(str.charAt(i++));\r\n for (j = 0; j < arr.length; j++) {\r\n if (arr[j] > baseOut - 1) {\r\n if (arr[j + 1] === void 0) arr[j + 1] = 0;\r\n arr[j + 1] += arr[j] / baseOut | 0;\r\n arr[j] %= baseOut;\r\n }\r\n }\r\n }\r\n\r\n return arr.reverse();\r\n}\r\n\r\n\r\n/*\r\n * cos(x) = 1 - x^2/2! + x^4/4! - ...\r\n * |x| < pi/2\r\n *\r\n */\r\nfunction cosine(Ctor, x) {\r\n var k, len, y;\r\n\r\n if (x.isZero()) return x;\r\n\r\n // Argument reduction: cos(4x) = 8*(cos^4(x) - cos^2(x)) + 1\r\n // i.e. cos(x) = 8*(cos^4(x/4) - cos^2(x/4)) + 1\r\n\r\n // Estimate the optimum number of times to use the argument reduction.\r\n len = x.d.length;\r\n if (len < 32) {\r\n k = Math.ceil(len / 3);\r\n y = (1 / tinyPow(4, k)).toString();\r\n } else {\r\n k = 16;\r\n y = '2.3283064365386962890625e-10';\r\n }\r\n\r\n Ctor.precision += k;\r\n\r\n x = taylorSeries(Ctor, 1, x.times(y), new Ctor(1));\r\n\r\n // Reverse argument reduction\r\n for (var i = k; i--;) {\r\n var cos2x = x.times(x);\r\n x = cos2x.times(cos2x).minus(cos2x).times(8).plus(1);\r\n }\r\n\r\n Ctor.precision -= k;\r\n\r\n return x;\r\n}\r\n\r\n\r\n/*\r\n * Perform division in the specified base.\r\n */\r\nvar divide = (function () {\r\n\r\n // Assumes non-zero x and k, and hence non-zero result.\r\n function multiplyInteger(x, k, base) {\r\n var temp,\r\n carry = 0,\r\n i = x.length;\r\n\r\n for (x = x.slice(); i--;) {\r\n temp = x[i] * k + carry;\r\n x[i] = temp % base | 0;\r\n carry = temp / base | 0;\r\n }\r\n\r\n if (carry) x.unshift(carry);\r\n\r\n return x;\r\n }\r\n\r\n function compare(a, b, aL, bL) {\r\n var i, r;\r\n\r\n if (aL != bL) {\r\n r = aL > bL ? 1 : -1;\r\n } else {\r\n for (i = r = 0; i < aL; i++) {\r\n if (a[i] != b[i]) {\r\n r = a[i] > b[i] ? 1 : -1;\r\n break;\r\n }\r\n }\r\n }\r\n\r\n return r;\r\n }\r\n\r\n function subtract(a, b, aL, base) {\r\n var i = 0;\r\n\r\n // Subtract b from a.\r\n for (; aL--;) {\r\n a[aL] -= i;\r\n i = a[aL] < b[aL] ? 1 : 0;\r\n a[aL] = i * base + a[aL] - b[aL];\r\n }\r\n\r\n // Remove leading zeros.\r\n for (; !a[0] && a.length > 1;) a.shift();\r\n }\r\n\r\n return function (x, y, pr, rm, dp, base) {\r\n var cmp, e, i, k, logBase, more, prod, prodL, q, qd, rem, remL, rem0, sd, t, xi, xL, yd0,\r\n yL, yz,\r\n Ctor = x.constructor,\r\n sign = x.s == y.s ? 1 : -1,\r\n xd = x.d,\r\n yd = y.d;\r\n\r\n // Either NaN, Infinity or 0?\r\n if (!xd || !xd[0] || !yd || !yd[0]) {\r\n\r\n return new Ctor(// Return NaN if either NaN, or both Infinity or 0.\r\n !x.s || !y.s || (xd ? yd && xd[0] == yd[0] : !yd) ? NaN :\r\n\r\n // Return ±0 if x is 0 or y is ±Infinity, or return ±Infinity as y is 0.\r\n xd && xd[0] == 0 || !yd ? sign * 0 : sign / 0);\r\n }\r\n\r\n if (base) {\r\n logBase = 1;\r\n e = x.e - y.e;\r\n } else {\r\n base = BASE;\r\n logBase = LOG_BASE;\r\n e = mathfloor(x.e / logBase) - mathfloor(y.e / logBase);\r\n }\r\n\r\n yL = yd.length;\r\n xL = xd.length;\r\n q = new Ctor(sign);\r\n qd = q.d = [];\r\n\r\n // Result exponent may be one less than e.\r\n // The digit array of a Decimal from toStringBinary may have trailing zeros.\r\n for (i = 0; yd[i] == (xd[i] || 0); i++);\r\n\r\n if (yd[i] > (xd[i] || 0)) e--;\r\n\r\n if (pr == null) {\r\n sd = pr = Ctor.precision;\r\n rm = Ctor.rounding;\r\n } else if (dp) {\r\n sd = pr + (x.e - y.e) + 1;\r\n } else {\r\n sd = pr;\r\n }\r\n\r\n if (sd < 0) {\r\n qd.push(1);\r\n more = true;\r\n } else {\r\n\r\n // Convert precision in number of base 10 digits to base 1e7 digits.\r\n sd = sd / logBase + 2 | 0;\r\n i = 0;\r\n\r\n // divisor < 1e7\r\n if (yL == 1) {\r\n k = 0;\r\n yd = yd[0];\r\n sd++;\r\n\r\n // k is the carry.\r\n for (; (i < xL || k) && sd--; i++) {\r\n t = k * base + (xd[i] || 0);\r\n qd[i] = t / yd | 0;\r\n k = t % yd | 0;\r\n }\r\n\r\n more = k || i < xL;\r\n\r\n // divisor >= 1e7\r\n } else {\r\n\r\n // Normalise xd and yd so highest order digit of yd is >= base/2\r\n k = base / (yd[0] + 1) | 0;\r\n\r\n if (k > 1) {\r\n yd = multiplyInteger(yd, k, base);\r\n xd = multiplyInteger(xd, k, base);\r\n yL = yd.length;\r\n xL = xd.length;\r\n }\r\n\r\n xi = yL;\r\n rem = xd.slice(0, yL);\r\n remL = rem.length;\r\n\r\n // Add zeros to make remainder as long as divisor.\r\n for (; remL < yL;) rem[remL++] = 0;\r\n\r\n yz = yd.slice();\r\n yz.unshift(0);\r\n yd0 = yd[0];\r\n\r\n if (yd[1] >= base / 2) ++yd0;\r\n\r\n do {\r\n k = 0;\r\n\r\n // Compare divisor and remainder.\r\n cmp = compare(yd, rem, yL, remL);\r\n\r\n // If divisor < remainder.\r\n if (cmp < 0) {\r\n\r\n // Calculate trial digit, k.\r\n rem0 = rem[0];\r\n if (yL != remL) rem0 = rem0 * base + (rem[1] || 0);\r\n\r\n // k will be how many times the divisor goes into the current remainder.\r\n k = rem0 / yd0 | 0;\r\n\r\n // Algorithm:\r\n // 1. product = divisor * trial digit (k)\r\n // 2. if product > remainder: product -= divisor, k--\r\n // 3. remainder -= product\r\n // 4. if product was < remainder at 2:\r\n // 5. compare new remainder and divisor\r\n // 6. If remainder > divisor: remainder -= divisor, k++\r\n\r\n if (k > 1) {\r\n if (k >= base) k = base - 1;\r\n\r\n // product = divisor * trial digit.\r\n prod = multiplyInteger(yd, k, base);\r\n prodL = prod.length;\r\n remL = rem.length;\r\n\r\n // Compare product and remainder.\r\n cmp = compare(prod, rem, prodL, remL);\r\n\r\n // product > remainder.\r\n if (cmp == 1) {\r\n k--;\r\n\r\n // Subtract divisor from product.\r\n subtract(prod, yL < prodL ? yz : yd, prodL, base);\r\n }\r\n } else {\r\n\r\n // cmp is -1.\r\n // If k is 0, there is no need to compare yd and rem again below, so change cmp to 1\r\n // to avoid it. If k is 1 there is a need to compare yd and rem again below.\r\n if (k == 0) cmp = k = 1;\r\n prod = yd.slice();\r\n }\r\n\r\n prodL = prod.length;\r\n if (prodL < remL) prod.unshift(0);\r\n\r\n // Subtract product from remainder.\r\n subtract(rem, prod, remL, base);\r\n\r\n // If product was < previous remainder.\r\n if (cmp == -1) {\r\n remL = rem.length;\r\n\r\n // Compare divisor and new remainder.\r\n cmp = compare(yd, rem, yL, remL);\r\n\r\n // If divisor < new remainder, subtract divisor from remainder.\r\n if (cmp < 1) {\r\n k++;\r\n\r\n // Subtract divisor from remainder.\r\n subtract(rem, yL < remL ? yz : yd, remL, base);\r\n }\r\n }\r\n\r\n remL = rem.length;\r\n } else if (cmp === 0) {\r\n k++;\r\n rem = [0];\r\n } // if cmp === 1, k will be 0\r\n\r\n // Add the next digit, k, to the result array.\r\n qd[i++] = k;\r\n\r\n // Update the remainder.\r\n if (cmp && rem[0]) {\r\n rem[remL++] = xd[xi] || 0;\r\n } else {\r\n rem = [xd[xi]];\r\n remL = 1;\r\n }\r\n\r\n } while ((xi++ < xL || rem[0] !== void 0) && sd--);\r\n\r\n more = rem[0] !== void 0;\r\n }\r\n\r\n // Leading zero?\r\n if (!qd[0]) qd.shift();\r\n }\r\n\r\n // logBase is 1 when divide is being used for base conversion.\r\n if (logBase == 1) {\r\n q.e = e;\r\n inexact = more;\r\n } else {\r\n\r\n // To calculate q.e, first get the number of digits of qd[0].\r\n for (i = 1, k = qd[0]; k >= 10; k /= 10) i++;\r\n q.e = i + e * logBase - 1;\r\n\r\n finalise(q, dp ? pr + q.e + 1 : pr, rm, more);\r\n }\r\n\r\n return q;\r\n };\r\n})();\r\n\r\n\r\n/*\r\n * Round `x` to `sd` significant digits using rounding mode `rm`.\r\n * Check for over/under-flow.\r\n */\r\n function finalise(x, sd, rm, isTruncated) {\r\n var digits, i, j, k, rd, roundUp, w, xd, xdi,\r\n Ctor = x.constructor;\r\n\r\n // Don't round if sd is null or undefined.\r\n out: if (sd != null) {\r\n xd = x.d;\r\n\r\n // Infinity/NaN.\r\n if (!xd) return x;\r\n\r\n // rd: the rounding digit, i.e. the digit after the digit that may be rounded up.\r\n // w: the word of xd containing rd, a base 1e7 number.\r\n // xdi: the index of w within xd.\r\n // digits: the number of digits of w.\r\n // i: what would be the index of rd within w if all the numbers were 7 digits long (i.e. if\r\n // they had leading zeros)\r\n // j: if > 0, the actual index of rd within w (if < 0, rd is a leading zero).\r\n\r\n // Get the length of the first word of the digits array xd.\r\n for (digits = 1, k = xd[0]; k >= 10; k /= 10) digits++;\r\n i = sd - digits;\r\n\r\n // Is the rounding digit in the first word of xd?\r\n if (i < 0) {\r\n i += LOG_BASE;\r\n j = sd;\r\n w = xd[xdi = 0];\r\n\r\n // Get the rounding digit at index j of w.\r\n rd = w / mathpow(10, digits - j - 1) % 10 | 0;\r\n } else {\r\n xdi = Math.ceil((i + 1) / LOG_BASE);\r\n k = xd.length;\r\n if (xdi >= k) {\r\n if (isTruncated) {\r\n\r\n // Needed by `naturalExponential`, `naturalLogarithm` and `squareRoot`.\r\n for (; k++ <= xdi;) xd.push(0);\r\n w = rd = 0;\r\n digits = 1;\r\n i %= LOG_BASE;\r\n j = i - LOG_BASE + 1;\r\n } else {\r\n break out;\r\n }\r\n } else {\r\n w = k = xd[xdi];\r\n\r\n // Get the number of digits of w.\r\n for (digits = 1; k >= 10; k /= 10) digits++;\r\n\r\n // Get the index of rd within w.\r\n i %= LOG_BASE;\r\n\r\n // Get the index of rd within w, adjusted for leading zeros.\r\n // The number of leading zeros of w is given by LOG_BASE - digits.\r\n j = i - LOG_BASE + digits;\r\n\r\n // Get the rounding digit at index j of w.\r\n rd = j < 0 ? 0 : w / mathpow(10, digits - j - 1) % 10 | 0;\r\n }\r\n }\r\n\r\n // Are there any non-zero digits after the rounding digit?\r\n isTruncated = isTruncated || sd < 0 ||\r\n xd[xdi + 1] !== void 0 || (j < 0 ? w : w % mathpow(10, digits - j - 1));\r\n\r\n // The expression `w % mathpow(10, digits - j - 1)` returns all the digits of w to the right\r\n // of the digit at (left-to-right) index j, e.g. if w is 908714 and j is 2, the expression\r\n // will give 714.\r\n\r\n roundUp = rm < 4\r\n ? (rd || isTruncated) && (rm == 0 || rm == (x.s < 0 ? 3 : 2))\r\n : rd > 5 || rd == 5 && (rm == 4 || isTruncated || rm == 6 &&\r\n\r\n // Check whether the digit to the left of the rounding digit is odd.\r\n ((i > 0 ? j > 0 ? w / mathpow(10, digits - j) : 0 : xd[xdi - 1]) % 10) & 1 ||\r\n rm == (x.s < 0 ? 8 : 7));\r\n\r\n if (sd < 1 || !xd[0]) {\r\n xd.length = 0;\r\n if (roundUp) {\r\n\r\n // Convert sd to decimal places.\r\n sd -= x.e + 1;\r\n\r\n // 1, 0.1, 0.01, 0.001, 0.0001 etc.\r\n xd[0] = mathpow(10, (LOG_BASE - sd % LOG_BASE) % LOG_BASE);\r\n x.e = -sd || 0;\r\n } else {\r\n\r\n // Zero.\r\n xd[0] = x.e = 0;\r\n }\r\n\r\n return x;\r\n }\r\n\r\n // Remove excess digits.\r\n if (i == 0) {\r\n xd.length = xdi;\r\n k = 1;\r\n xdi--;\r\n } else {\r\n xd.length = xdi + 1;\r\n k = mathpow(10, LOG_BASE - i);\r\n\r\n // E.g. 56700 becomes 56000 if 7 is the rounding digit.\r\n // j > 0 means i > number of leading zeros of w.\r\n xd[xdi] = j > 0 ? (w / mathpow(10, digits - j) % mathpow(10, j) | 0) * k : 0;\r\n }\r\n\r\n if (roundUp) {\r\n for (;;) {\r\n\r\n // Is the digit to be rounded up in the first word of xd?\r\n if (xdi == 0) {\r\n\r\n // i will be the length of xd[0] before k is added.\r\n for (i = 1, j = xd[0]; j >= 10; j /= 10) i++;\r\n j = xd[0] += k;\r\n for (k = 1; j >= 10; j /= 10) k++;\r\n\r\n // if i != k the length has increased.\r\n if (i != k) {\r\n x.e++;\r\n if (xd[0] == BASE) xd[0] = 1;\r\n }\r\n\r\n break;\r\n } else {\r\n xd[xdi] += k;\r\n if (xd[xdi] != BASE) break;\r\n xd[xdi--] = 0;\r\n k = 1;\r\n }\r\n }\r\n }\r\n\r\n // Remove trailing zeros.\r\n for (i = xd.length; xd[--i] === 0;) xd.pop();\r\n }\r\n\r\n if (external) {\r\n\r\n // Overflow?\r\n if (x.e > Ctor.maxE) {\r\n\r\n // Infinity.\r\n x.d = null;\r\n x.e = NaN;\r\n\r\n // Underflow?\r\n } else if (x.e < Ctor.minE) {\r\n\r\n // Zero.\r\n x.e = 0;\r\n x.d = [0];\r\n // Ctor.underflow = true;\r\n } // else Ctor.underflow = false;\r\n }\r\n\r\n return x;\r\n}\r\n\r\n\r\nfunction finiteToString(x, isExp, sd) {\r\n if (!x.isFinite()) return nonFiniteToString(x);\r\n var k,\r\n e = x.e,\r\n str = digitsToString(x.d),\r\n len = str.length;\r\n\r\n if (isExp) {\r\n if (sd && (k = sd - len) > 0) {\r\n str = str.charAt(0) + '.' + str.slice(1) + getZeroString(k);\r\n } else if (len > 1) {\r\n str = str.charAt(0) + '.' + str.slice(1);\r\n }\r\n\r\n str = str + (x.e < 0 ? 'e' : 'e+') + x.e;\r\n } else if (e < 0) {\r\n str = '0.' + getZeroString(-e - 1) + str;\r\n if (sd && (k = sd - len) > 0) str += getZeroString(k);\r\n } else if (e >= len) {\r\n str += getZeroString(e + 1 - len);\r\n if (sd && (k = sd - e - 1) > 0) str = str + '.' + getZeroString(k);\r\n } else {\r\n if ((k = e + 1) < len) str = str.slice(0, k) + '.' + str.slice(k);\r\n if (sd && (k = sd - len) > 0) {\r\n if (e + 1 === len) str += '.';\r\n str += getZeroString(k);\r\n }\r\n }\r\n\r\n return str;\r\n}\r\n\r\n\r\n// Calculate the base 10 exponent from the base 1e7 exponent.\r\nfunction getBase10Exponent(digits, e) {\r\n var w = digits[0];\r\n\r\n // Add the number of digits of the first word of the digits array.\r\n for ( e *= LOG_BASE; w >= 10; w /= 10) e++;\r\n return e;\r\n}\r\n\r\n\r\nfunction getLn10(Ctor, sd, pr) {\r\n if (sd > LN10_PRECISION) {\r\n\r\n // Reset global state in case the exception is caught.\r\n external = true;\r\n if (pr) Ctor.precision = pr;\r\n throw Error(precisionLimitExceeded);\r\n }\r\n return finalise(new Ctor(LN10), sd, 1, true);\r\n}\r\n\r\n\r\nfunction getPi(Ctor, sd, rm) {\r\n if (sd > PI_PRECISION) throw Error(precisionLimitExceeded);\r\n return finalise(new Ctor(PI), sd, rm, true);\r\n}\r\n\r\n\r\nfunction getPrecision(digits) {\r\n var w = digits.length - 1,\r\n len = w * LOG_BASE + 1;\r\n\r\n w = digits[w];\r\n\r\n // If non-zero...\r\n if (w) {\r\n\r\n // Subtract the number of trailing zeros of the last word.\r\n for (; w % 10 == 0; w /= 10) len--;\r\n\r\n // Add the number of digits of the first word.\r\n for (w = digits[0]; w >= 10; w /= 10) len++;\r\n }\r\n\r\n return len;\r\n}\r\n\r\n\r\nfunction getZeroString(k) {\r\n var zs = '';\r\n for (; k--;) zs += '0';\r\n return zs;\r\n}\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is the value of Decimal `x` to the power `n`, where `n` is an\r\n * integer of type number.\r\n *\r\n * Implements 'exponentiation by squaring'. Called by `pow` and `parseOther`.\r\n *\r\n */\r\nfunction intPow(Ctor, x, n, pr) {\r\n var isTruncated,\r\n r = new Ctor(1),\r\n\r\n // Max n of 9007199254740991 takes 53 loop iterations.\r\n // Maximum digits array length; leaves [28, 34] guard digits.\r\n k = Math.ceil(pr / LOG_BASE + 4);\r\n\r\n external = false;\r\n\r\n for (;;) {\r\n if (n % 2) {\r\n r = r.times(x);\r\n if (truncate(r.d, k)) isTruncated = true;\r\n }\r\n\r\n n = mathfloor(n / 2);\r\n if (n === 0) {\r\n\r\n // To ensure correct rounding when r.d is truncated, increment the last word if it is zero.\r\n n = r.d.length - 1;\r\n if (isTruncated && r.d[n] === 0) ++r.d[n];\r\n break;\r\n }\r\n\r\n x = x.times(x);\r\n truncate(x.d, k);\r\n }\r\n\r\n external = true;\r\n\r\n return r;\r\n}\r\n\r\n\r\nfunction isOdd(n) {\r\n return n.d[n.d.length - 1] & 1;\r\n}\r\n\r\n\r\n/*\r\n * Handle `max` and `min`. `ltgt` is 'lt' or 'gt'.\r\n */\r\nfunction maxOrMin(Ctor, args, ltgt) {\r\n var y,\r\n x = new Ctor(args[0]),\r\n i = 0;\r\n\r\n for (; ++i < args.length;) {\r\n y = new Ctor(args[i]);\r\n if (!y.s) {\r\n x = y;\r\n break;\r\n } else if (x[ltgt](y)) {\r\n x = y;\r\n }\r\n }\r\n\r\n return x;\r\n}\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is the natural exponential of `x` rounded to `sd` significant\r\n * digits.\r\n *\r\n * Taylor/Maclaurin series.\r\n *\r\n * exp(x) = x^0/0! + x^1/1! + x^2/2! + x^3/3! + ...\r\n *\r\n * Argument reduction:\r\n * Repeat x = x / 32, k += 5, until |x| < 0.1\r\n * exp(x) = exp(x / 2^k)^(2^k)\r\n *\r\n * Previously, the argument was initially reduced by\r\n * exp(x) = exp(r) * 10^k where r = x - k * ln10, k = floor(x / ln10)\r\n * to first put r in the range [0, ln10], before dividing by 32 until |x| < 0.1, but this was\r\n * found to be slower than just dividing repeatedly by 32 as above.\r\n *\r\n * Max integer argument: exp('20723265836946413') = 6.3e+9000000000000000\r\n * Min integer argument: exp('-20723265836946411') = 1.2e-9000000000000000\r\n * (Math object integer min/max: Math.exp(709) = 8.2e+307, Math.exp(-745) = 5e-324)\r\n *\r\n * exp(Infinity) = Infinity\r\n * exp(-Infinity) = 0\r\n * exp(NaN) = NaN\r\n * exp(±0) = 1\r\n *\r\n * exp(x) is non-terminating for any finite, non-zero x.\r\n *\r\n * The result will always be correctly rounded.\r\n *\r\n */\r\nfunction naturalExponential(x, sd) {\r\n var denominator, guard, j, pow, sum, t, wpr,\r\n rep = 0,\r\n i = 0,\r\n k = 0,\r\n Ctor = x.constructor,\r\n rm = Ctor.rounding,\r\n pr = Ctor.precision;\r\n\r\n // 0/NaN/Infinity?\r\n if (!x.d || !x.d[0] || x.e > 17) {\r\n\r\n return new Ctor(x.d\r\n ? !x.d[0] ? 1 : x.s < 0 ? 0 : 1 / 0\r\n : x.s ? x.s < 0 ? 0 : x : 0 / 0);\r\n }\r\n\r\n if (sd == null) {\r\n external = false;\r\n wpr = pr;\r\n } else {\r\n wpr = sd;\r\n }\r\n\r\n t = new Ctor(0.03125);\r\n\r\n // while abs(x) >= 0.1\r\n while (x.e > -2) {\r\n\r\n // x = x / 2^5\r\n x = x.times(t);\r\n k += 5;\r\n }\r\n\r\n // Use 2 * log10(2^k) + 5 (empirically derived) to estimate the increase in precision\r\n // necessary to ensure the first 4 rounding digits are correct.\r\n guard = Math.log(mathpow(2, k)) / Math.LN10 * 2 + 5 | 0;\r\n wpr += guard;\r\n denominator = pow = sum = new Ctor(1);\r\n Ctor.precision = wpr;\r\n\r\n for (;;) {\r\n pow = finalise(pow.times(x), wpr, 1);\r\n denominator = denominator.times(++i);\r\n t = sum.plus(divide(pow, denominator, wpr, 1));\r\n\r\n if (digitsToString(t.d).slice(0, wpr) === digitsToString(sum.d).slice(0, wpr)) {\r\n j = k;\r\n while (j--) sum = finalise(sum.times(sum), wpr, 1);\r\n\r\n // Check to see if the first 4 rounding digits are [49]999.\r\n // If so, repeat the summation with a higher precision, otherwise\r\n // e.g. with precision: 18, rounding: 1\r\n // exp(18.404272462595034083567793919843761) = 98372560.1229999999 (should be 98372560.123)\r\n // `wpr - guard` is the index of first rounding digit.\r\n if (sd == null) {\r\n\r\n if (rep < 3 && checkRoundingDigits(sum.d, wpr - guard, rm, rep)) {\r\n Ctor.precision = wpr += 10;\r\n denominator = pow = t = new Ctor(1);\r\n i = 0;\r\n rep++;\r\n } else {\r\n return finalise(sum, Ctor.precision = pr, rm, external = true);\r\n }\r\n } else {\r\n Ctor.precision = pr;\r\n return sum;\r\n }\r\n }\r\n\r\n sum = t;\r\n }\r\n}\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is the natural logarithm of `x` rounded to `sd` significant\r\n * digits.\r\n *\r\n * ln(-n) = NaN\r\n * ln(0) = -Infinity\r\n * ln(-0) = -Infinity\r\n * ln(1) = 0\r\n * ln(Infinity) = Infinity\r\n * ln(-Infinity) = NaN\r\n * ln(NaN) = NaN\r\n *\r\n * ln(n) (n != 1) is non-terminating.\r\n *\r\n */\r\nfunction naturalLogarithm(y, sd) {\r\n var c, c0, denominator, e, numerator, rep, sum, t, wpr, x1, x2,\r\n n = 1,\r\n guard = 10,\r\n x = y,\r\n xd = x.d,\r\n Ctor = x.constructor,\r\n rm = Ctor.rounding,\r\n pr = Ctor.precision;\r\n\r\n // Is x negative or Infinity, NaN, 0 or 1?\r\n if (x.s < 0 || !xd || !xd[0] || !x.e && xd[0] == 1 && xd.length == 1) {\r\n return new Ctor(xd && !xd[0] ? -1 / 0 : x.s != 1 ? NaN : xd ? 0 : x);\r\n }\r\n\r\n if (sd == null) {\r\n external = false;\r\n wpr = pr;\r\n } else {\r\n wpr = sd;\r\n }\r\n\r\n Ctor.precision = wpr += guard;\r\n c = digitsToString(xd);\r\n c0 = c.charAt(0);\r\n\r\n if (Math.abs(e = x.e) < 1.5e15) {\r\n\r\n // Argument reduction.\r\n // The series converges faster the closer the argument is to 1, so using\r\n // ln(a^b) = b * ln(a), ln(a) = ln(a^b) / b\r\n // multiply the argument by itself until the leading digits of the significand are 7, 8, 9,\r\n // 10, 11, 12 or 13, recording the number of multiplications so the sum of the series can\r\n // later be divided by this number, then separate out the power of 10 using\r\n // ln(a*10^b) = ln(a) + b*ln(10).\r\n\r\n // max n is 21 (gives 0.9, 1.0 or 1.1) (9e15 / 21 = 4.2e14).\r\n //while (c0 < 9 && c0 != 1 || c0 == 1 && c.charAt(1) > 1) {\r\n // max n is 6 (gives 0.7 - 1.3)\r\n while (c0 < 7 && c0 != 1 || c0 == 1 && c.charAt(1) > 3) {\r\n x = x.times(y);\r\n c = digitsToString(x.d);\r\n c0 = c.charAt(0);\r\n n++;\r\n }\r\n\r\n e = x.e;\r\n\r\n if (c0 > 1) {\r\n x = new Ctor('0.' + c);\r\n e++;\r\n } else {\r\n x = new Ctor(c0 + '.' + c.slice(1));\r\n }\r\n } else {\r\n\r\n // The argument reduction method above may result in overflow if the argument y is a massive\r\n // number with exponent >= 1500000000000000 (9e15 / 6 = 1.5e15), so instead recall this\r\n // function using ln(x*10^e) = ln(x) + e*ln(10).\r\n t = getLn10(Ctor, wpr + 2, pr).times(e + '');\r\n x = naturalLogarithm(new Ctor(c0 + '.' + c.slice(1)), wpr - guard).plus(t);\r\n Ctor.precision = pr;\r\n\r\n return sd == null ? finalise(x, pr, rm, external = true) : x;\r\n }\r\n\r\n // x1 is x reduced to a value near 1.\r\n x1 = x;\r\n\r\n // Taylor series.\r\n // ln(y) = ln((1 + x)/(1 - x)) = 2(x + x^3/3 + x^5/5 + x^7/7 + ...)\r\n // where x = (y - 1)/(y + 1) (|x| < 1)\r\n sum = numerator = x = divide(x.minus(1), x.plus(1), wpr, 1);\r\n x2 = finalise(x.times(x), wpr, 1);\r\n denominator = 3;\r\n\r\n for (;;) {\r\n numerator = finalise(numerator.times(x2), wpr, 1);\r\n t = sum.plus(divide(numerator, new Ctor(denominator), wpr, 1));\r\n\r\n if (digitsToString(t.d).slice(0, wpr) === digitsToString(sum.d).slice(0, wpr)) {\r\n sum = sum.times(2);\r\n\r\n // Reverse the argument reduction. Check that e is not 0 because, besides preventing an\r\n // unnecessary calculation, -0 + 0 = +0 and to ensure correct rounding -0 needs to stay -0.\r\n if (e !== 0) sum = sum.plus(getLn10(Ctor, wpr + 2, pr).times(e + ''));\r\n sum = divide(sum, new Ctor(n), wpr, 1);\r\n\r\n // Is rm > 3 and the first 4 rounding digits 4999, or rm < 4 (or the summation has\r\n // been repeated previously) and the first 4 rounding digits 9999?\r\n // If so, restart the summation with a higher precision, otherwise\r\n // e.g. with precision: 12, rounding: 1\r\n // ln(135520028.6126091714265381533) = 18.7246299999 when it should be 18.72463.\r\n // `wpr - guard` is the index of first rounding digit.\r\n if (sd == null) {\r\n if (checkRoundingDigits(sum.d, wpr - guard, rm, rep)) {\r\n Ctor.precision = wpr += guard;\r\n t = numerator = x = divide(x1.minus(1), x1.plus(1), wpr, 1);\r\n x2 = finalise(x.times(x), wpr, 1);\r\n denominator = rep = 1;\r\n } else {\r\n return finalise(sum, Ctor.precision = pr, rm, external = true);\r\n }\r\n } else {\r\n Ctor.precision = pr;\r\n return sum;\r\n }\r\n }\r\n\r\n sum = t;\r\n denominator += 2;\r\n }\r\n}\r\n\r\n\r\n// ±Infinity, NaN.\r\nfunction nonFiniteToString(x) {\r\n // Unsigned.\r\n return String(x.s * x.s / 0);\r\n}\r\n\r\n\r\n/*\r\n * Parse the value of a new Decimal `x` from string `str`.\r\n */\r\nfunction parseDecimal(x, str) {\r\n var e, i, len;\r\n\r\n // Decimal point?\r\n if ((e = str.indexOf('.')) > -1) str = str.replace('.', '');\r\n\r\n // Exponential form?\r\n if ((i = str.search(/e/i)) > 0) {\r\n\r\n // Determine exponent.\r\n if (e < 0) e = i;\r\n e += +str.slice(i + 1);\r\n str = str.substring(0, i);\r\n } else if (e < 0) {\r\n\r\n // Integer.\r\n e = str.length;\r\n }\r\n\r\n // Determine leading zeros.\r\n for (i = 0; str.charCodeAt(i) === 48; i++);\r\n\r\n // Determine trailing zeros.\r\n for (len = str.length; str.charCodeAt(len - 1) === 48; --len);\r\n str = str.slice(i, len);\r\n\r\n if (str) {\r\n len -= i;\r\n x.e = e = e - i - 1;\r\n x.d = [];\r\n\r\n // Transform base\r\n\r\n // e is the base 10 exponent.\r\n // i is where to slice str to get the first word of the digits array.\r\n i = (e + 1) % LOG_BASE;\r\n if (e < 0) i += LOG_BASE;\r\n\r\n if (i < len) {\r\n if (i) x.d.push(+str.slice(0, i));\r\n for (len -= LOG_BASE; i < len;) x.d.push(+str.slice(i, i += LOG_BASE));\r\n str = str.slice(i);\r\n i = LOG_BASE - str.length;\r\n } else {\r\n i -= len;\r\n }\r\n\r\n for (; i--;) str += '0';\r\n x.d.push(+str);\r\n\r\n if (external) {\r\n\r\n // Overflow?\r\n if (x.e > x.constructor.maxE) {\r\n\r\n // Infinity.\r\n x.d = null;\r\n x.e = NaN;\r\n\r\n // Underflow?\r\n } else if (x.e < x.constructor.minE) {\r\n\r\n // Zero.\r\n x.e = 0;\r\n x.d = [0];\r\n // x.constructor.underflow = true;\r\n } // else x.constructor.underflow = false;\r\n }\r\n } else {\r\n\r\n // Zero.\r\n x.e = 0;\r\n x.d = [0];\r\n }\r\n\r\n return x;\r\n}\r\n\r\n\r\n/*\r\n * Parse the value of a new Decimal `x` from a string `str`, which is not a decimal value.\r\n */\r\nfunction parseOther(x, str) {\r\n var base, Ctor, divisor, i, isFloat, len, p, xd, xe;\r\n\r\n if (str.indexOf('_') > -1) {\r\n str = str.replace(/(\\d)_(?=\\d)/g, '$1');\r\n if (isDecimal.test(str)) return parseDecimal(x, str);\r\n } else if (str === 'Infinity' || str === 'NaN') {\r\n if (!+str) x.s = NaN;\r\n x.e = NaN;\r\n x.d = null;\r\n return x;\r\n }\r\n\r\n if (isHex.test(str)) {\r\n base = 16;\r\n str = str.toLowerCase();\r\n } else if (isBinary.test(str)) {\r\n base = 2;\r\n } else if (isOctal.test(str)) {\r\n base = 8;\r\n } else {\r\n throw Error(invalidArgument + str);\r\n }\r\n\r\n // Is there a binary exponent part?\r\n i = str.search(/p/i);\r\n\r\n if (i > 0) {\r\n p = +str.slice(i + 1);\r\n str = str.substring(2, i);\r\n } else {\r\n str = str.slice(2);\r\n }\r\n\r\n // Convert `str` as an integer then divide the result by `base` raised to a power such that the\r\n // fraction part will be restored.\r\n i = str.indexOf('.');\r\n isFloat = i >= 0;\r\n Ctor = x.constructor;\r\n\r\n if (isFloat) {\r\n str = str.replace('.', '');\r\n len = str.length;\r\n i = len - i;\r\n\r\n // log[10](16) = 1.2041... , log[10](88) = 1.9444....\r\n divisor = intPow(Ctor, new Ctor(base), i, i * 2);\r\n }\r\n\r\n xd = convertBase(str, base, BASE);\r\n xe = xd.length - 1;\r\n\r\n // Remove trailing zeros.\r\n for (i = xe; xd[i] === 0; --i) xd.pop();\r\n if (i < 0) return new Ctor(x.s * 0);\r\n x.e = getBase10Exponent(xd, xe);\r\n x.d = xd;\r\n external = false;\r\n\r\n // At what precision to perform the division to ensure exact conversion?\r\n // maxDecimalIntegerPartDigitCount = ceil(log[10](b) * otherBaseIntegerPartDigitCount)\r\n // log[10](2) = 0.30103, log[10](8) = 0.90309, log[10](16) = 1.20412\r\n // E.g. ceil(1.2 * 3) = 4, so up to 4 decimal digits are needed to represent 3 hex int digits.\r\n // maxDecimalFractionPartDigitCount = {Hex:4|Oct:3|Bin:1} * otherBaseFractionPartDigitCount\r\n // Therefore using 4 * the number of digits of str will always be enough.\r\n if (isFloat) x = divide(x, divisor, len * 4);\r\n\r\n // Multiply by the binary exponent part if present.\r\n if (p) x = x.times(Math.abs(p) < 54 ? mathpow(2, p) : Decimal.pow(2, p));\r\n external = true;\r\n\r\n return x;\r\n}\r\n\r\n\r\n/*\r\n * sin(x) = x - x^3/3! + x^5/5! - ...\r\n * |x| < pi/2\r\n *\r\n */\r\nfunction sine(Ctor, x) {\r\n var k,\r\n len = x.d.length;\r\n\r\n if (len < 3) {\r\n return x.isZero() ? x : taylorSeries(Ctor, 2, x, x);\r\n }\r\n\r\n // Argument reduction: sin(5x) = 16*sin^5(x) - 20*sin^3(x) + 5*sin(x)\r\n // i.e. sin(x) = 16*sin^5(x/5) - 20*sin^3(x/5) + 5*sin(x/5)\r\n // and sin(x) = sin(x/5)(5 + sin^2(x/5)(16sin^2(x/5) - 20))\r\n\r\n // Estimate the optimum number of times to use the argument reduction.\r\n k = 1.4 * Math.sqrt(len);\r\n k = k > 16 ? 16 : k | 0;\r\n\r\n x = x.times(1 / tinyPow(5, k));\r\n x = taylorSeries(Ctor, 2, x, x);\r\n\r\n // Reverse argument reduction\r\n var sin2_x,\r\n d5 = new Ctor(5),\r\n d16 = new Ctor(16),\r\n d20 = new Ctor(20);\r\n for (; k--;) {\r\n sin2_x = x.times(x);\r\n x = x.times(d5.plus(sin2_x.times(d16.times(sin2_x).minus(d20))));\r\n }\r\n\r\n return x;\r\n}\r\n\r\n\r\n// Calculate Taylor series for `cos`, `cosh`, `sin` and `sinh`.\r\nfunction taylorSeries(Ctor, n, x, y, isHyperbolic) {\r\n var j, t, u, x2,\r\n i = 1,\r\n pr = Ctor.precision,\r\n k = Math.ceil(pr / LOG_BASE);\r\n\r\n external = false;\r\n x2 = x.times(x);\r\n u = new Ctor(y);\r\n\r\n for (;;) {\r\n t = divide(u.times(x2), new Ctor(n++ * n++), pr, 1);\r\n u = isHyperbolic ? y.plus(t) : y.minus(t);\r\n y = divide(t.times(x2), new Ctor(n++ * n++), pr, 1);\r\n t = u.plus(y);\r\n\r\n if (t.d[k] !== void 0) {\r\n for (j = k; t.d[j] === u.d[j] && j--;);\r\n if (j == -1) break;\r\n }\r\n\r\n j = u;\r\n u = y;\r\n y = t;\r\n t = j;\r\n i++;\r\n }\r\n\r\n external = true;\r\n t.d.length = k + 1;\r\n\r\n return t;\r\n}\r\n\r\n\r\n// Exponent e must be positive and non-zero.\r\nfunction tinyPow(b, e) {\r\n var n = b;\r\n while (--e) n *= b;\r\n return n;\r\n}\r\n\r\n\r\n// Return the absolute value of `x` reduced to less than or equal to half pi.\r\nfunction toLessThanHalfPi(Ctor, x) {\r\n var t,\r\n isNeg = x.s < 0,\r\n pi = getPi(Ctor, Ctor.precision, 1),\r\n halfPi = pi.times(0.5);\r\n\r\n x = x.abs();\r\n\r\n if (x.lte(halfPi)) {\r\n quadrant = isNeg ? 4 : 1;\r\n return x;\r\n }\r\n\r\n t = x.divToInt(pi);\r\n\r\n if (t.isZero()) {\r\n quadrant = isNeg ? 3 : 2;\r\n } else {\r\n x = x.minus(t.times(pi));\r\n\r\n // 0 <= x < pi\r\n if (x.lte(halfPi)) {\r\n quadrant = isOdd(t) ? (isNeg ? 2 : 3) : (isNeg ? 4 : 1);\r\n return x;\r\n }\r\n\r\n quadrant = isOdd(t) ? (isNeg ? 1 : 4) : (isNeg ? 3 : 2);\r\n }\r\n\r\n return x.minus(pi).abs();\r\n}\r\n\r\n\r\n/*\r\n * Return the value of Decimal `x` as a string in base `baseOut`.\r\n *\r\n * If the optional `sd` argument is present include a binary exponent suffix.\r\n */\r\nfunction toStringBinary(x, baseOut, sd, rm) {\r\n var base, e, i, k, len, roundUp, str, xd, y,\r\n Ctor = x.constructor,\r\n isExp = sd !== void 0;\r\n\r\n if (isExp) {\r\n checkInt32(sd, 1, MAX_DIGITS);\r\n if (rm === void 0) rm = Ctor.rounding;\r\n else checkInt32(rm, 0, 8);\r\n } else {\r\n sd = Ctor.precision;\r\n rm = Ctor.rounding;\r\n }\r\n\r\n if (!x.isFinite()) {\r\n str = nonFiniteToString(x);\r\n } else {\r\n str = finiteToString(x);\r\n i = str.indexOf('.');\r\n\r\n // Use exponential notation according to `toExpPos` and `toExpNeg`? No, but if required:\r\n // maxBinaryExponent = floor((decimalExponent + 1) * log[2](10))\r\n // minBinaryExponent = floor(decimalExponent * log[2](10))\r\n // log[2](10) = 3.321928094887362347870319429489390175864\r\n\r\n if (isExp) {\r\n base = 2;\r\n if (baseOut == 16) {\r\n sd = sd * 4 - 3;\r\n } else if (baseOut == 8) {\r\n sd = sd * 3 - 2;\r\n }\r\n } else {\r\n base = baseOut;\r\n }\r\n\r\n // Convert the number as an integer then divide the result by its base raised to a power such\r\n // that the fraction part will be restored.\r\n\r\n // Non-integer.\r\n if (i >= 0) {\r\n str = str.replace('.', '');\r\n y = new Ctor(1);\r\n y.e = str.length - i;\r\n y.d = convertBase(finiteToString(y), 10, base);\r\n y.e = y.d.length;\r\n }\r\n\r\n xd = convertBase(str, 10, base);\r\n e = len = xd.length;\r\n\r\n // Remove trailing zeros.\r\n for (; xd[--len] == 0;) xd.pop();\r\n\r\n if (!xd[0]) {\r\n str = isExp ? '0p+0' : '0';\r\n } else {\r\n if (i < 0) {\r\n e--;\r\n } else {\r\n x = new Ctor(x);\r\n x.d = xd;\r\n x.e = e;\r\n x = divide(x, y, sd, rm, 0, base);\r\n xd = x.d;\r\n e = x.e;\r\n roundUp = inexact;\r\n }\r\n\r\n // The rounding digit, i.e. the digit after the digit that may be rounded up.\r\n i = xd[sd];\r\n k = base / 2;\r\n roundUp = roundUp || xd[sd + 1] !== void 0;\r\n\r\n roundUp = rm < 4\r\n ? (i !== void 0 || roundUp) && (rm === 0 || rm === (x.s < 0 ? 3 : 2))\r\n : i > k || i === k && (rm === 4 || roundUp || rm === 6 && xd[sd - 1] & 1 ||\r\n rm === (x.s < 0 ? 8 : 7));\r\n\r\n xd.length = sd;\r\n\r\n if (roundUp) {\r\n\r\n // Rounding up may mean the previous digit has to be rounded up and so on.\r\n for (; ++xd[--sd] > base - 1;) {\r\n xd[sd] = 0;\r\n if (!sd) {\r\n ++e;\r\n xd.unshift(1);\r\n }\r\n }\r\n }\r\n\r\n // Determine trailing zeros.\r\n for (len = xd.length; !xd[len - 1]; --len);\r\n\r\n // E.g. [4, 11, 15] becomes 4bf.\r\n for (i = 0, str = ''; i < len; i++) str += NUMERALS.charAt(xd[i]);\r\n\r\n // Add binary exponent suffix?\r\n if (isExp) {\r\n if (len > 1) {\r\n if (baseOut == 16 || baseOut == 8) {\r\n i = baseOut == 16 ? 4 : 3;\r\n for (--len; len % i; len++) str += '0';\r\n xd = convertBase(str, base, baseOut);\r\n for (len = xd.length; !xd[len - 1]; --len);\r\n\r\n // xd[0] will always be be 1\r\n for (i = 1, str = '1.'; i < len; i++) str += NUMERALS.charAt(xd[i]);\r\n } else {\r\n str = str.charAt(0) + '.' + str.slice(1);\r\n }\r\n }\r\n\r\n str = str + (e < 0 ? 'p' : 'p+') + e;\r\n } else if (e < 0) {\r\n for (; ++e;) str = '0' + str;\r\n str = '0.' + str;\r\n } else {\r\n if (++e > len) for (e -= len; e-- ;) str += '0';\r\n else if (e < len) str = str.slice(0, e) + '.' + str.slice(e);\r\n }\r\n }\r\n\r\n str = (baseOut == 16 ? '0x' : baseOut == 2 ? '0b' : baseOut == 8 ? '0o' : '') + str;\r\n }\r\n\r\n return x.s < 0 ? '-' + str : str;\r\n}\r\n\r\n\r\n// Does not strip trailing zeros.\r\nfunction truncate(arr, len) {\r\n if (arr.length > len) {\r\n arr.length = len;\r\n return true;\r\n }\r\n}\r\n\r\n\r\n// Decimal methods\r\n\r\n\r\n/*\r\n * abs\r\n * acos\r\n * acosh\r\n * add\r\n * asin\r\n * asinh\r\n * atan\r\n * atanh\r\n * atan2\r\n * cbrt\r\n * ceil\r\n * clamp\r\n * clone\r\n * config\r\n * cos\r\n * cosh\r\n * div\r\n * exp\r\n * floor\r\n * hypot\r\n * ln\r\n * log\r\n * log2\r\n * log10\r\n * max\r\n * min\r\n * mod\r\n * mul\r\n * pow\r\n * random\r\n * round\r\n * set\r\n * sign\r\n * sin\r\n * sinh\r\n * sqrt\r\n * sub\r\n * sum\r\n * tan\r\n * tanh\r\n * trunc\r\n */\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is the absolute value of `x`.\r\n *\r\n * x {number|string|Decimal}\r\n *\r\n */\r\nfunction abs(x) {\r\n return new this(x).abs();\r\n}\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is the arccosine in radians of `x`.\r\n *\r\n * x {number|string|Decimal}\r\n *\r\n */\r\nfunction acos(x) {\r\n return new this(x).acos();\r\n}\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is the inverse of the hyperbolic cosine of `x`, rounded to\r\n * `precision` significant digits using rounding mode `rounding`.\r\n *\r\n * x {number|string|Decimal} A value in radians.\r\n *\r\n */\r\nfunction acosh(x) {\r\n return new this(x).acosh();\r\n}\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is the sum of `x` and `y`, rounded to `precision` significant\r\n * digits using rounding mode `rounding`.\r\n *\r\n * x {number|string|Decimal}\r\n * y {number|string|Decimal}\r\n *\r\n */\r\nfunction add(x, y) {\r\n return new this(x).plus(y);\r\n}\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is the arcsine in radians of `x`, rounded to `precision`\r\n * significant digits using rounding mode `rounding`.\r\n *\r\n * x {number|string|Decimal}\r\n *\r\n */\r\nfunction asin(x) {\r\n return new this(x).asin();\r\n}\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is the inverse of the hyperbolic sine of `x`, rounded to\r\n * `precision` significant digits using rounding mode `rounding`.\r\n *\r\n * x {number|string|Decimal} A value in radians.\r\n *\r\n */\r\nfunction asinh(x) {\r\n return new this(x).asinh();\r\n}\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is the arctangent in radians of `x`, rounded to `precision`\r\n * significant digits using rounding mode `rounding`.\r\n *\r\n * x {number|string|Decimal}\r\n *\r\n */\r\nfunction atan(x) {\r\n return new this(x).atan();\r\n}\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is the inverse of the hyperbolic tangent of `x`, rounded to\r\n * `precision` significant digits using rounding mode `rounding`.\r\n *\r\n * x {number|string|Decimal} A value in radians.\r\n *\r\n */\r\nfunction atanh(x) {\r\n return new this(x).atanh();\r\n}\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is the arctangent in radians of `y/x` in the range -pi to pi\r\n * (inclusive), rounded to `precision` significant digits using rounding mode `rounding`.\r\n *\r\n * Domain: [-Infinity, Infinity]\r\n * Range: [-pi, pi]\r\n *\r\n * y {number|string|Decimal} The y-coordinate.\r\n * x {number|string|Decimal} The x-coordinate.\r\n *\r\n * atan2(±0, -0) = ±pi\r\n * atan2(±0, +0) = ±0\r\n * atan2(±0, -x) = ±pi for x > 0\r\n * atan2(±0, x) = ±0 for x > 0\r\n * atan2(-y, ±0) = -pi/2 for y > 0\r\n * atan2(y, ±0) = pi/2 for y > 0\r\n * atan2(±y, -Infinity) = ±pi for finite y > 0\r\n * atan2(±y, +Infinity) = ±0 for finite y > 0\r\n * atan2(±Infinity, x) = ±pi/2 for finite x\r\n * atan2(±Infinity, -Infinity) = ±3*pi/4\r\n * atan2(±Infinity, +Infinity) = ±pi/4\r\n * atan2(NaN, x) = NaN\r\n * atan2(y, NaN) = NaN\r\n *\r\n */\r\nfunction atan2(y, x) {\r\n y = new this(y);\r\n x = new this(x);\r\n var r,\r\n pr = this.precision,\r\n rm = this.rounding,\r\n wpr = pr + 4;\r\n\r\n // Either NaN\r\n if (!y.s || !x.s) {\r\n r = new this(NaN);\r\n\r\n // Both ±Infinity\r\n } else if (!y.d && !x.d) {\r\n r = getPi(this, wpr, 1).times(x.s > 0 ? 0.25 : 0.75);\r\n r.s = y.s;\r\n\r\n // x is ±Infinity or y is ±0\r\n } else if (!x.d || y.isZero()) {\r\n r = x.s < 0 ? getPi(this, pr, rm) : new this(0);\r\n r.s = y.s;\r\n\r\n // y is ±Infinity or x is ±0\r\n } else if (!y.d || x.isZero()) {\r\n r = getPi(this, wpr, 1).times(0.5);\r\n r.s = y.s;\r\n\r\n // Both non-zero and finite\r\n } else if (x.s < 0) {\r\n this.precision = wpr;\r\n this.rounding = 1;\r\n r = this.atan(divide(y, x, wpr, 1));\r\n x = getPi(this, wpr, 1);\r\n this.precision = pr;\r\n this.rounding = rm;\r\n r = y.s < 0 ? r.minus(x) : r.plus(x);\r\n } else {\r\n r = this.atan(divide(y, x, wpr, 1));\r\n }\r\n\r\n return r;\r\n}\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is the cube root of `x`, rounded to `precision` significant\r\n * digits using rounding mode `rounding`.\r\n *\r\n * x {number|string|Decimal}\r\n *\r\n */\r\nfunction cbrt(x) {\r\n return new this(x).cbrt();\r\n}\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is `x` rounded to an integer using `ROUND_CEIL`.\r\n *\r\n * x {number|string|Decimal}\r\n *\r\n */\r\nfunction ceil(x) {\r\n return finalise(x = new this(x), x.e + 1, 2);\r\n}\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is `x` clamped to the range delineated by `min` and `max`.\r\n *\r\n * x {number|string|Decimal}\r\n * min {number|string|Decimal}\r\n * max {number|string|Decimal}\r\n *\r\n */\r\nfunction clamp(x, min, max) {\r\n return new this(x).clamp(min, max);\r\n}\r\n\r\n\r\n/*\r\n * Configure global settings for a Decimal constructor.\r\n *\r\n * `obj` is an object with one or more of the following properties,\r\n *\r\n * precision {number}\r\n * rounding {number}\r\n * toExpNeg {number}\r\n * toExpPos {number}\r\n * maxE {number}\r\n * minE {number}\r\n * modulo {number}\r\n * crypto {boolean|number}\r\n * defaults {true}\r\n *\r\n * E.g. Decimal.config({ precision: 20, rounding: 4 })\r\n *\r\n */\r\nfunction config(obj) {\r\n if (!obj || typeof obj !== 'object') throw Error(decimalError + 'Object expected');\r\n var i, p, v,\r\n useDefaults = obj.defaults === true,\r\n ps = [\r\n 'precision', 1, MAX_DIGITS,\r\n 'rounding', 0, 8,\r\n 'toExpNeg', -EXP_LIMIT, 0,\r\n 'toExpPos', 0, EXP_LIMIT,\r\n 'maxE', 0, EXP_LIMIT,\r\n 'minE', -EXP_LIMIT, 0,\r\n 'modulo', 0, 9\r\n ];\r\n\r\n for (i = 0; i < ps.length; i += 3) {\r\n if (p = ps[i], useDefaults) this[p] = DEFAULTS[p];\r\n if ((v = obj[p]) !== void 0) {\r\n if (mathfloor(v) === v && v >= ps[i + 1] && v <= ps[i + 2]) this[p] = v;\r\n else throw Error(invalidArgument + p + ': ' + v);\r\n }\r\n }\r\n\r\n if (p = 'crypto', useDefaults) this[p] = DEFAULTS[p];\r\n if ((v = obj[p]) !== void 0) {\r\n if (v === true || v === false || v === 0 || v === 1) {\r\n if (v) {\r\n if (typeof crypto != 'undefined' && crypto &&\r\n (crypto.getRandomValues || crypto.randomBytes)) {\r\n this[p] = true;\r\n } else {\r\n throw Error(cryptoUnavailable);\r\n }\r\n } else {\r\n this[p] = false;\r\n }\r\n } else {\r\n throw Error(invalidArgument + p + ': ' + v);\r\n }\r\n }\r\n\r\n return this;\r\n}\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is the cosine of `x`, rounded to `precision` significant\r\n * digits using rounding mode `rounding`.\r\n *\r\n * x {number|string|Decimal} A value in radians.\r\n *\r\n */\r\nfunction cos(x) {\r\n return new this(x).cos();\r\n}\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is the hyperbolic cosine of `x`, rounded to precision\r\n * significant digits using rounding mode `rounding`.\r\n *\r\n * x {number|string|Decimal} A value in radians.\r\n *\r\n */\r\nfunction cosh(x) {\r\n return new this(x).cosh();\r\n}\r\n\r\n\r\n/*\r\n * Create and return a Decimal constructor with the same configuration properties as this Decimal\r\n * constructor.\r\n *\r\n */\r\nfunction clone(obj) {\r\n var i, p, ps;\r\n\r\n /*\r\n * The Decimal constructor and exported function.\r\n * Return a new Decimal instance.\r\n *\r\n * v {number|string|Decimal} A numeric value.\r\n *\r\n */\r\n function Decimal(v) {\r\n var e, i, t,\r\n x = this;\r\n\r\n // Decimal called without new.\r\n if (!(x instanceof Decimal)) return new Decimal(v);\r\n\r\n // Retain a reference to this Decimal constructor, and shadow Decimal.prototype.constructor\r\n // which points to Object.\r\n x.constructor = Decimal;\r\n\r\n // Duplicate.\r\n if (isDecimalInstance(v)) {\r\n x.s = v.s;\r\n\r\n if (external) {\r\n if (!v.d || v.e > Decimal.maxE) {\r\n\r\n // Infinity.\r\n x.e = NaN;\r\n x.d = null;\r\n } else if (v.e < Decimal.minE) {\r\n\r\n // Zero.\r\n x.e = 0;\r\n x.d = [0];\r\n } else {\r\n x.e = v.e;\r\n x.d = v.d.slice();\r\n }\r\n } else {\r\n x.e = v.e;\r\n x.d = v.d ? v.d.slice() : v.d;\r\n }\r\n\r\n return;\r\n }\r\n\r\n t = typeof v;\r\n\r\n if (t === 'number') {\r\n if (v === 0) {\r\n x.s = 1 / v < 0 ? -1 : 1;\r\n x.e = 0;\r\n x.d = [0];\r\n return;\r\n }\r\n\r\n if (v < 0) {\r\n v = -v;\r\n x.s = -1;\r\n } else {\r\n x.s = 1;\r\n }\r\n\r\n // Fast path for small integers.\r\n if (v === ~~v && v < 1e7) {\r\n for (e = 0, i = v; i >= 10; i /= 10) e++;\r\n\r\n if (external) {\r\n if (e > Decimal.maxE) {\r\n x.e = NaN;\r\n x.d = null;\r\n } else if (e < Decimal.minE) {\r\n x.e = 0;\r\n x.d = [0];\r\n } else {\r\n x.e = e;\r\n x.d = [v];\r\n }\r\n } else {\r\n x.e = e;\r\n x.d = [v];\r\n }\r\n\r\n return;\r\n\r\n // Infinity, NaN.\r\n } else if (v * 0 !== 0) {\r\n if (!v) x.s = NaN;\r\n x.e = NaN;\r\n x.d = null;\r\n return;\r\n }\r\n\r\n return parseDecimal(x, v.toString());\r\n\r\n } else if (t !== 'string') {\r\n throw Error(invalidArgument + v);\r\n }\r\n\r\n // Minus sign?\r\n if ((i = v.charCodeAt(0)) === 45) {\r\n v = v.slice(1);\r\n x.s = -1;\r\n } else {\r\n // Plus sign?\r\n if (i === 43) v = v.slice(1);\r\n x.s = 1;\r\n }\r\n\r\n return isDecimal.test(v) ? parseDecimal(x, v) : parseOther(x, v);\r\n }\r\n\r\n Decimal.prototype = P;\r\n\r\n Decimal.ROUND_UP = 0;\r\n Decimal.ROUND_DOWN = 1;\r\n Decimal.ROUND_CEIL = 2;\r\n Decimal.ROUND_FLOOR = 3;\r\n Decimal.ROUND_HALF_UP = 4;\r\n Decimal.ROUND_HALF_DOWN = 5;\r\n Decimal.ROUND_HALF_EVEN = 6;\r\n Decimal.ROUND_HALF_CEIL = 7;\r\n Decimal.ROUND_HALF_FLOOR = 8;\r\n Decimal.EUCLID = 9;\r\n\r\n Decimal.config = Decimal.set = config;\r\n Decimal.clone = clone;\r\n Decimal.isDecimal = isDecimalInstance;\r\n\r\n Decimal.abs = abs;\r\n Decimal.acos = acos;\r\n Decimal.acosh = acosh; // ES6\r\n Decimal.add = add;\r\n Decimal.asin = asin;\r\n Decimal.asinh = asinh; // ES6\r\n Decimal.atan = atan;\r\n Decimal.atanh = atanh; // ES6\r\n Decimal.atan2 = atan2;\r\n Decimal.cbrt = cbrt; // ES6\r\n Decimal.ceil = ceil;\r\n Decimal.clamp = clamp;\r\n Decimal.cos = cos;\r\n Decimal.cosh = cosh; // ES6\r\n Decimal.div = div;\r\n Decimal.exp = exp;\r\n Decimal.floor = floor;\r\n Decimal.hypot = hypot; // ES6\r\n Decimal.ln = ln;\r\n Decimal.log = log;\r\n Decimal.log10 = log10; // ES6\r\n Decimal.log2 = log2; // ES6\r\n Decimal.max = max;\r\n Decimal.min = min;\r\n Decimal.mod = mod;\r\n Decimal.mul = mul;\r\n Decimal.pow = pow;\r\n Decimal.random = random;\r\n Decimal.round = round;\r\n Decimal.sign = sign; // ES6\r\n Decimal.sin = sin;\r\n Decimal.sinh = sinh; // ES6\r\n Decimal.sqrt = sqrt;\r\n Decimal.sub = sub;\r\n Decimal.sum = sum;\r\n Decimal.tan = tan;\r\n Decimal.tanh = tanh; // ES6\r\n Decimal.trunc = trunc; // ES6\r\n\r\n if (obj === void 0) obj = {};\r\n if (obj) {\r\n if (obj.defaults !== true) {\r\n ps = ['precision', 'rounding', 'toExpNeg', 'toExpPos', 'maxE', 'minE', 'modulo', 'crypto'];\r\n for (i = 0; i < ps.length;) if (!obj.hasOwnProperty(p = ps[i++])) obj[p] = this[p];\r\n }\r\n }\r\n\r\n Decimal.config(obj);\r\n\r\n return Decimal;\r\n}\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is `x` divided by `y`, rounded to `precision` significant\r\n * digits using rounding mode `rounding`.\r\n *\r\n * x {number|string|Decimal}\r\n * y {number|string|Decimal}\r\n *\r\n */\r\nfunction div(x, y) {\r\n return new this(x).div(y);\r\n}\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is the natural exponential of `x`, rounded to `precision`\r\n * significant digits using rounding mode `rounding`.\r\n *\r\n * x {number|string|Decimal} The power to which to raise the base of the natural log.\r\n *\r\n */\r\nfunction exp(x) {\r\n return new this(x).exp();\r\n}\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is `x` round to an integer using `ROUND_FLOOR`.\r\n *\r\n * x {number|string|Decimal}\r\n *\r\n */\r\nfunction floor(x) {\r\n return finalise(x = new this(x), x.e + 1, 3);\r\n}\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is the square root of the sum of the squares of the arguments,\r\n * rounded to `precision` significant digits using rounding mode `rounding`.\r\n *\r\n * hypot(a, b, ...) = sqrt(a^2 + b^2 + ...)\r\n *\r\n * arguments {number|string|Decimal}\r\n *\r\n */\r\nfunction hypot() {\r\n var i, n,\r\n t = new this(0);\r\n\r\n external = false;\r\n\r\n for (i = 0; i < arguments.length;) {\r\n n = new this(arguments[i++]);\r\n if (!n.d) {\r\n if (n.s) {\r\n external = true;\r\n return new this(1 / 0);\r\n }\r\n t = n;\r\n } else if (t.d) {\r\n t = t.plus(n.times(n));\r\n }\r\n }\r\n\r\n external = true;\r\n\r\n return t.sqrt();\r\n}\r\n\r\n\r\n/*\r\n * Return true if object is a Decimal instance (where Decimal is any Decimal constructor),\r\n * otherwise return false.\r\n *\r\n */\r\nfunction isDecimalInstance(obj) {\r\n return obj instanceof Decimal || obj && obj.toStringTag === tag || false;\r\n}\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is the natural logarithm of `x`, rounded to `precision`\r\n * significant digits using rounding mode `rounding`.\r\n *\r\n * x {number|string|Decimal}\r\n *\r\n */\r\nfunction ln(x) {\r\n return new this(x).ln();\r\n}\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is the log of `x` to the base `y`, or to base 10 if no base\r\n * is specified, rounded to `precision` significant digits using rounding mode `rounding`.\r\n *\r\n * log[y](x)\r\n *\r\n * x {number|string|Decimal} The argument of the logarithm.\r\n * y {number|string|Decimal} The base of the logarithm.\r\n *\r\n */\r\nfunction log(x, y) {\r\n return new this(x).log(y);\r\n}\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is the base 2 logarithm of `x`, rounded to `precision`\r\n * significant digits using rounding mode `rounding`.\r\n *\r\n * x {number|string|Decimal}\r\n *\r\n */\r\nfunction log2(x) {\r\n return new this(x).log(2);\r\n}\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is the base 10 logarithm of `x`, rounded to `precision`\r\n * significant digits using rounding mode `rounding`.\r\n *\r\n * x {number|string|Decimal}\r\n *\r\n */\r\nfunction log10(x) {\r\n return new this(x).log(10);\r\n}\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is the maximum of the arguments.\r\n *\r\n * arguments {number|string|Decimal}\r\n *\r\n */\r\nfunction max() {\r\n return maxOrMin(this, arguments, 'lt');\r\n}\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is the minimum of the arguments.\r\n *\r\n * arguments {number|string|Decimal}\r\n *\r\n */\r\nfunction min() {\r\n return maxOrMin(this, arguments, 'gt');\r\n}\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is `x` modulo `y`, rounded to `precision` significant digits\r\n * using rounding mode `rounding`.\r\n *\r\n * x {number|string|Decimal}\r\n * y {number|string|Decimal}\r\n *\r\n */\r\nfunction mod(x, y) {\r\n return new this(x).mod(y);\r\n}\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is `x` multiplied by `y`, rounded to `precision` significant\r\n * digits using rounding mode `rounding`.\r\n *\r\n * x {number|string|Decimal}\r\n * y {number|string|Decimal}\r\n *\r\n */\r\nfunction mul(x, y) {\r\n return new this(x).mul(y);\r\n}\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is `x` raised to the power `y`, rounded to precision\r\n * significant digits using rounding mode `rounding`.\r\n *\r\n * x {number|string|Decimal} The base.\r\n * y {number|string|Decimal} The exponent.\r\n *\r\n */\r\nfunction pow(x, y) {\r\n return new this(x).pow(y);\r\n}\r\n\r\n\r\n/*\r\n * Returns a new Decimal with a random value equal to or greater than 0 and less than 1, and with\r\n * `sd`, or `Decimal.precision` if `sd` is omitted, significant digits (or less if trailing zeros\r\n * are produced).\r\n *\r\n * [sd] {number} Significant digits. Integer, 0 to MAX_DIGITS inclusive.\r\n *\r\n */\r\nfunction random(sd) {\r\n var d, e, k, n,\r\n i = 0,\r\n r = new this(1),\r\n rd = [];\r\n\r\n if (sd === void 0) sd = this.precision;\r\n else checkInt32(sd, 1, MAX_DIGITS);\r\n\r\n k = Math.ceil(sd / LOG_BASE);\r\n\r\n if (!this.crypto) {\r\n for (; i < k;) rd[i++] = Math.random() * 1e7 | 0;\r\n\r\n // Browsers supporting crypto.getRandomValues.\r\n } else if (crypto.getRandomValues) {\r\n d = crypto.getRandomValues(new Uint32Array(k));\r\n\r\n for (; i < k;) {\r\n n = d[i];\r\n\r\n // 0 <= n < 4294967296\r\n // Probability n >= 4.29e9, is 4967296 / 4294967296 = 0.00116 (1 in 865).\r\n if (n >= 4.29e9) {\r\n d[i] = crypto.getRandomValues(new Uint32Array(1))[0];\r\n } else {\r\n\r\n // 0 <= n <= 4289999999\r\n // 0 <= (n % 1e7) <= 9999999\r\n rd[i++] = n % 1e7;\r\n }\r\n }\r\n\r\n // Node.js supporting crypto.randomBytes.\r\n } else if (crypto.randomBytes) {\r\n\r\n // buffer\r\n d = crypto.randomBytes(k *= 4);\r\n\r\n for (; i < k;) {\r\n\r\n // 0 <= n < 2147483648\r\n n = d[i] + (d[i + 1] << 8) + (d[i + 2] << 16) + ((d[i + 3] & 0x7f) << 24);\r\n\r\n // Probability n >= 2.14e9, is 7483648 / 2147483648 = 0.0035 (1 in 286).\r\n if (n >= 2.14e9) {\r\n crypto.randomBytes(4).copy(d, i);\r\n } else {\r\n\r\n // 0 <= n <= 2139999999\r\n // 0 <= (n % 1e7) <= 9999999\r\n rd.push(n % 1e7);\r\n i += 4;\r\n }\r\n }\r\n\r\n i = k / 4;\r\n } else {\r\n throw Error(cryptoUnavailable);\r\n }\r\n\r\n k = rd[--i];\r\n sd %= LOG_BASE;\r\n\r\n // Convert trailing digits to zeros according to sd.\r\n if (k && sd) {\r\n n = mathpow(10, LOG_BASE - sd);\r\n rd[i] = (k / n | 0) * n;\r\n }\r\n\r\n // Remove trailing words which are zero.\r\n for (; rd[i] === 0; i--) rd.pop();\r\n\r\n // Zero?\r\n if (i < 0) {\r\n e = 0;\r\n rd = [0];\r\n } else {\r\n e = -1;\r\n\r\n // Remove leading words which are zero and adjust exponent accordingly.\r\n for (; rd[0] === 0; e -= LOG_BASE) rd.shift();\r\n\r\n // Count the digits of the first word of rd to determine leading zeros.\r\n for (k = 1, n = rd[0]; n >= 10; n /= 10) k++;\r\n\r\n // Adjust the exponent for leading zeros of the first word of rd.\r\n if (k < LOG_BASE) e -= LOG_BASE - k;\r\n }\r\n\r\n r.e = e;\r\n r.d = rd;\r\n\r\n return r;\r\n}\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is `x` rounded to an integer using rounding mode `rounding`.\r\n *\r\n * To emulate `Math.round`, set rounding to 7 (ROUND_HALF_CEIL).\r\n *\r\n * x {number|string|Decimal}\r\n *\r\n */\r\nfunction round(x) {\r\n return finalise(x = new this(x), x.e + 1, this.rounding);\r\n}\r\n\r\n\r\n/*\r\n * Return\r\n * 1 if x > 0,\r\n * -1 if x < 0,\r\n * 0 if x is 0,\r\n * -0 if x is -0,\r\n * NaN otherwise\r\n *\r\n * x {number|string|Decimal}\r\n *\r\n */\r\nfunction sign(x) {\r\n x = new this(x);\r\n return x.d ? (x.d[0] ? x.s : 0 * x.s) : x.s || NaN;\r\n}\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is the sine of `x`, rounded to `precision` significant digits\r\n * using rounding mode `rounding`.\r\n *\r\n * x {number|string|Decimal} A value in radians.\r\n *\r\n */\r\nfunction sin(x) {\r\n return new this(x).sin();\r\n}\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is the hyperbolic sine of `x`, rounded to `precision`\r\n * significant digits using rounding mode `rounding`.\r\n *\r\n * x {number|string|Decimal} A value in radians.\r\n *\r\n */\r\nfunction sinh(x) {\r\n return new this(x).sinh();\r\n}\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is the square root of `x`, rounded to `precision` significant\r\n * digits using rounding mode `rounding`.\r\n *\r\n * x {number|string|Decimal}\r\n *\r\n */\r\nfunction sqrt(x) {\r\n return new this(x).sqrt();\r\n}\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is `x` minus `y`, rounded to `precision` significant digits\r\n * using rounding mode `rounding`.\r\n *\r\n * x {number|string|Decimal}\r\n * y {number|string|Decimal}\r\n *\r\n */\r\nfunction sub(x, y) {\r\n return new this(x).sub(y);\r\n}\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is the sum of the arguments, rounded to `precision`\r\n * significant digits using rounding mode `rounding`.\r\n *\r\n * Only the result is rounded, not the intermediate calculations.\r\n *\r\n * arguments {number|string|Decimal}\r\n *\r\n */\r\nfunction sum() {\r\n var i = 0,\r\n args = arguments,\r\n x = new this(args[i]);\r\n\r\n external = false;\r\n for (; x.s && ++i < args.length;) x = x.plus(args[i]);\r\n external = true;\r\n\r\n return finalise(x, this.precision, this.rounding);\r\n}\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is the tangent of `x`, rounded to `precision` significant\r\n * digits using rounding mode `rounding`.\r\n *\r\n * x {number|string|Decimal} A value in radians.\r\n *\r\n */\r\nfunction tan(x) {\r\n return new this(x).tan();\r\n}\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is the hyperbolic tangent of `x`, rounded to `precision`\r\n * significant digits using rounding mode `rounding`.\r\n *\r\n * x {number|string|Decimal} A value in radians.\r\n *\r\n */\r\nfunction tanh(x) {\r\n return new this(x).tanh();\r\n}\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is `x` truncated to an integer.\r\n *\r\n * x {number|string|Decimal}\r\n *\r\n */\r\nfunction trunc(x) {\r\n return finalise(x = new this(x), x.e + 1, 1);\r\n}\r\n\r\n\r\nP[Symbol.for('nodejs.util.inspect.custom')] = P.toString;\r\nP[Symbol.toStringTag] = 'Decimal';\r\n\r\n// Create and configure initial Decimal constructor.\r\nexport var Decimal = P.constructor = clone(DEFAULTS);\r\n\r\n// Create the internal constants from their string values.\r\nLN10 = new Decimal(LN10);\r\nPI = new Decimal(PI);\r\n\r\nexport default Decimal;\r\n","import { PublicKey } from \"@solana/web3.js\";\n\nimport { PublicKeyish, SOLMint, validateAndParsePublicKey } from \"../common/pubKey\";\nimport { TOKEN_WSOL } from \"../raydium/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 { 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.raydium.io/icon/So11111111111111111111111111111111111111112.png`,\n tags: [],\n priority: 2,\n type: \"raydium\",\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.raydium.io/icon/So11111111111111111111111111111111111111112.png`,\n tags: [],\n priority: 2,\n type: \"raydium\",\n extensions: {\n coingeckoId: \"solana\",\n },\n};\n","import _Big from \"big.js\";\nimport BN from \"bn.js\";\nimport _Decimal from \"decimal.js-light\";\n\nimport { BigNumberish, parseBigNumberish, Rounding } from \"../common/bignumber\";\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 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 { BigNumberish, Rounding, tenExponential } from \"../common/bignumber\";\nimport { createLogger } from \"../common/logger\";\n\nimport { Fraction } from \"./fraction\";\nimport { Token } from \"./token\";\n\nconst logger = createLogger(\"Raydium_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 { SOL_INFO } from \"../raydium/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/bignumber\";\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 {\n Connection,\n PublicKey,\n sendAndConfirmTransaction,\n Signer,\n Transaction,\n TransactionInstruction,\n TransactionMessage,\n VersionedTransaction,\n} from \"@solana/web3.js\";\nimport axios from \"axios\";\n\nimport { SignAllTransactions, ComputeBudgetConfig } from \"@/raydium/type\";\nimport { Cluster } from \"@/solana\";\nimport { TxVersion } from \"./txType\";\nimport { Owner } from \"../owner\";\nimport { getRecentBlockHash, addComputeBudget, checkLegacyTxSize, checkV0TxSize, printSimulate } from \"./txUtils\";\nimport { CacheLTA, getMultipleLookupTableInfo, LOOKUP_TABLE_CACHE } from \"./lookupTable\";\n\ninterface SolanaFeeInfo {\n min: number;\n max: number;\n avg: number;\n priorityTx: number;\n nonVotes: number;\n priorityRatio: number;\n avgCuPerBlock: number;\n blockspaceUsageRatio: number;\n}\ntype SolanaFeeInfoJson = {\n \"1\": SolanaFeeInfo;\n \"5\": SolanaFeeInfo;\n \"15\": SolanaFeeInfo;\n};\n\ninterface ExecuteParams {\n skipPreflight?: boolean;\n recentBlockHash?: string;\n}\n\ninterface TxBuilderInit {\n connection: Connection;\n feePayer: PublicKey;\n cluster: Cluster;\n owner?: Owner;\n signAllTransactions?: SignAllTransactions;\n}\n\nexport interface AddInstructionParam {\n addresses?: Record<string, PublicKey>;\n instructions?: TransactionInstruction[];\n endInstructions?: TransactionInstruction[];\n lookupTableAddress?: string[];\n signers?: Signer[];\n instructionTypes?: string[];\n endInstructionTypes?: string[];\n}\n\nexport interface TxBuildData<T = Record<string, any>> {\n builder: TxBuilder;\n transaction: Transaction;\n instructionTypes: string[];\n signers: Signer[];\n execute: (params?: ExecuteParams) => Promise<{ txId: string; signedTx: Transaction }>;\n extInfo: T;\n}\n\nexport interface TxV0BuildData<T = Record<string, any>> extends Omit<TxBuildData<T>, \"transaction\" | \"execute\"> {\n builder: TxBuilder;\n transaction: VersionedTransaction;\n buildProps?: {\n lookupTableCache?: CacheLTA;\n lookupTableAddress?: string[];\n };\n execute: (params?: ExecuteParams) => Promise<{ txId: string; signedTx: VersionedTransaction }>;\n}\n\ntype TxUpdateParams = {\n txId: string;\n status: \"success\" | \"error\" | \"sent\";\n signedTx: Transaction | VersionedTransaction;\n};\nexport interface MultiTxExecuteParam extends ExecuteParams {\n sequentially: boolean;\n onTxUpdate?: (completeTxs: TxUpdateParams[]) => void;\n}\nexport interface MultiTxBuildData<T = Record<string, any>> {\n builder: TxBuilder;\n transactions: Transaction[];\n instructionTypes: string[];\n signers: Signer[][];\n execute: (executeParams?: MultiTxExecuteParam) => Promise<{ txIds: string[]; signedTxs: Transaction[] }>;\n extInfo: T;\n}\n\nexport interface MultiTxV0BuildData<T = Record<string, any>>\n extends Omit<MultiTxBuildData<T>, \"transactions\" | \"execute\"> {\n builder: TxBuilder;\n transactions: VersionedTransaction[];\n buildProps?: {\n lookupTableCache?: CacheLTA;\n lookupTableAddress?: string[];\n };\n execute: (executeParams?: MultiTxExecuteParam) => Promise<{ txIds: string[]; signedTxs: VersionedTransaction[] }>;\n}\n\nexport type MakeMultiTxData<T = TxVersion.LEGACY, O = Record<string, any>> = T extends TxVersion.LEGACY\n ? MultiTxBuildData<O>\n : MultiTxV0BuildData<O>;\n\nexport type MakeTxData<T = TxVersion.LEGACY, O = Record<string, any>> = T extends TxVersion.LEGACY\n ? TxBuildData<O>\n : TxV0BuildData<O>;\n\nexport class TxBuilder {\n private connection: Connection;\n private owner?: Owner;\n private instructions: TransactionInstruction[] = [];\n private endInstructions: TransactionInstruction[] = [];\n private lookupTableAddress: string[] = [];\n private signers: Signer[] = [];\n private instructionTypes: string[] = [];\n private endInstructionTypes: string[] = [];\n private feePayer: PublicKey;\n private cluster: Cluster;\n private signAllTransactions?: SignAllTransactions;\n\n constructor(params: TxBuilderInit) {\n this.connection = params.connection;\n this.feePayer = params.feePayer;\n this.signAllTransactions = params.signAllTransactions;\n this.owner = params.owner;\n this.cluster = params.cluster;\n }\n\n get AllTxData(): {\n instructions: TransactionInstruction[];\n endInstructions: TransactionInstruction[];\n signers: Signer[];\n instructionTypes: string[];\n endInstructionTypes: string[];\n lookupTableAddress: string[];\n } {\n return {\n instructions: this.instructions,\n endInstructions: this.endInstructions,\n signers: this.signers,\n instructionTypes: this.instructionTypes,\n endInstructionTypes: this.endInstructionTypes,\n lookupTableAddress: this.lookupTableAddress,\n };\n }\n\n get allInstructions(): TransactionInstruction[] {\n return [...this.instructions, ...this.endInstructions];\n }\n\n public async getComputeBudgetConfig(): Promise<ComputeBudgetConfig | undefined> {\n const json = (\n await axios.get<SolanaFeeInfoJson>(`https://solanacompass.com/api/fees?cacheFreshTime=${5 * 60 * 1000}`)\n ).data;\n const { avg } = json?.[15] ?? {};\n if (!avg) return undefined;\n return {\n units: 600000,\n microLamports: Math.min(Math.ceil((avg * 1000000) / 600000), 25000),\n };\n }\n\n public addCustomComputeBudget(config?: ComputeBudgetConfig): boolean {\n if (config) {\n const { instructions, instructionTypes } = addComputeBudget(config);\n this.instructions.unshift(...instructions);\n this.instructionTypes.unshift(...instructionTypes);\n return true;\n }\n return false;\n }\n\n public async calComputeBudget({\n config: propConfig,\n defaultIns,\n }: {\n config?: ComputeBudgetConfig;\n defaultIns?: TransactionInstruction[];\n }): Promise<void> {\n try {\n const config = propConfig || (await this.getComputeBudgetConfig());\n if (this.addCustomComputeBudget(config)) return;\n defaultIns && this.instructions.unshift(...defaultIns);\n } catch {\n defaultIns && this.instructions.unshift(...defaultIns);\n }\n }\n\n public addInstruction({\n instructions = [],\n endInstructions = [],\n signers = [],\n instructionTypes = [],\n endInstructionTypes = [],\n lookupTableAddress = [],\n }: AddInstructionParam): TxBuilder {\n this.instructions.push(...instructions);\n this.endInstructions.push(...endInstructions);\n this.signers.push(...signers);\n this.instructionTypes.push(...instructionTypes);\n this.endInstructionTypes.push(...endInstructionTypes);\n this.lookupTableAddress.push(...lookupTableAddress.filter((address) => address !== PublicKey.default.toString()));\n return this;\n }\n\n public async versionBuild<O = Record<string, any>>({\n txVersion,\n extInfo,\n }: {\n txVersion?: TxVersion;\n extInfo?: O;\n }): Promise<MakeTxData<TxVersion.LEGACY, O> | MakeTxData<TxVersion.V0, O>> {\n if (txVersion === TxVersion.V0) return (await this.buildV0({ ...(extInfo || {}) })) as MakeTxData<TxVersion.V0, O>;\n return this.build<O>(extInfo) as MakeTxData<TxVersion.LEGACY, O>;\n }\n\n public build<O = Record<string, any>>(extInfo?: O): MakeTxData<TxVersion.LEGACY, O> {\n const transaction = new Transaction();\n if (this.allInstructions.length) transaction.add(...this.allInstructions);\n transaction.feePayer = this.feePayer;\n\n return {\n builder: this,\n transaction,\n signers: this.signers,\n instructionTypes: [...this.instructionTypes, ...this.endInstructionTypes],\n execute: async (params) => {\n const { recentBlockHash: propBlockHash, skipPreflight = true } = params || {};\n const recentBlockHash = propBlockHash ?? (await getRecentBlockHash(this.connection));\n transaction.recentBlockhash = recentBlockHash;\n if (this.signers.length) transaction.sign(...this.signers);\n printSimulate([transaction]);\n if (this.owner?.isKeyPair) {\n return {\n txId: await sendAndConfirmTransaction(\n this.connection,\n transaction,\n this.signers.find((s) => s.publicKey.equals(this.owner!.publicKey))\n ? this.signers\n : [...this.signers, this.owner.signer!],\n { skipPreflight },\n ),\n signedTx: transaction,\n };\n }\n if (this.signAllTransactions) {\n const txs = await this.signAllTransactions([transaction]);\n return {\n txId: await this.connection.sendRawTransaction(txs[0].serialize(), { skipPreflight }),\n signedTx: txs[0],\n };\n }\n throw new Error(\"please provide owner in keypair format or signAllTransactions function\");\n },\n extInfo: extInfo || ({} as O),\n };\n }\n\n public buildMultiTx<T = Record<string, any>>(params: {\n extraPreBuildData?: MakeTxData<TxVersion.LEGACY>[];\n extInfo?: T;\n }): MultiTxBuildData {\n const { extraPreBuildData = [], extInfo } = params;\n const { transaction } = this.build(extInfo);\n\n const filterExtraBuildData = extraPreBuildData.filter((data) => data.transaction.instructions.length > 0);\n\n const allTransactions: Transaction[] = [transaction, ...filterExtraBuildData.map((data) => data.transaction)];\n const allSigners: Signer[][] = [this.signers, ...filterExtraBuildData.map((data) => data.signers)];\n const allInstructionTypes: string[] = [\n ...this.instructionTypes,\n ...filterExtraBuildData.map((data) => data.instructionTypes).flat(),\n ];\n\n return {\n builder: this,\n transactions: allTransactions,\n signers: allSigners,\n instructionTypes: allInstructionTypes,\n execute: async (executeParams?: MultiTxExecuteParam) => {\n const { sequentially, onTxUpdate, recentBlockHash: propBlockHash, skipPreflight = true } = executeParams || {};\n const recentBlockHash = propBlockHash ?? (await getRecentBlockHash(this.connection));\n if (this.owner?.isKeyPair) {\n if (sequentially) {\n const txIds: string[] = [];\n for (const tx of allTransactions) {\n const txId = await sendAndConfirmTransaction(\n this.connection,\n tx,\n this.signers.find((s) => s.publicKey.equals(this.owner!.publicKey))\n ? this.signers\n : [...this.signers, this.owner.signer!],\n { skipPreflight },\n );\n txIds.push(txId);\n }\n\n return {\n txIds,\n signedTxs: allTransactions,\n };\n }\n\n return {\n txIds: await await Promise.all(\n allTransactions.map(async (tx, idx) => {\n tx.recentBlockhash = recentBlockHash;\n return await sendAndConfirmTransaction(\n this.connection,\n tx,\n allSigners[idx].find((s) => s.publicKey.equals(this.owner!.publicKey))\n ? allSigners[idx]\n : [...allSigners[idx], this.owner!.signer!],\n { skipPreflight },\n );\n }),\n ),\n signedTxs: allTransactions,\n };\n }\n\n if (this.signAllTransactions) {\n const partialSignedTxs = allTransactions.map((tx, idx) => {\n tx.recentBlockhash = recentBlockHash;\n if (allSigners[idx].length) tx.sign(...allSigners[idx]);\n return tx;\n });\n printSimulate(partialSignedTxs);\n const signedTxs = await this.signAllTransactions(partialSignedTxs);\n if (sequentially) {\n let i = 0;\n const processedTxs: TxUpdateParams[] = [];\n const checkSendTx = async (): Promise<void> => {\n if (!signedTxs[i]) return;\n const txId = await this.connection.sendRawTransaction(signedTxs[i].serialize(), { skipPreflight });\n processedTxs.push({ txId, status: \"sent\", signedTx: signedTxs[i] });\n onTxUpdate?.([...processedTxs]);\n i++;\n this.connection.onSignature(\n txId,\n (signatureResult) => {\n const targetTxIdx = processedTxs.findIndex((tx) => tx.txId === txId);\n if (targetTxIdx > -1) processedTxs[targetTxIdx].status = signatureResult.err ? \"error\" : \"success\";\n onTxUpdate?.([...processedTxs]);\n if (!signatureResult.err) checkSendTx();\n },\n \"processed\",\n );\n this.connection.getSignatureStatus(txId);\n };\n await checkSendTx();\n return {\n txIds: processedTxs.map((d) => d.txId),\n signedTxs,\n };\n } else {\n const txIds: string[] = [];\n for (let i = 0; i < signedTxs.length; i += 1) {\n const txId = await this.connection.sendRawTransaction(signedTxs[i].serialize(), { skipPreflight });\n txIds.push(txId);\n }\n return {\n txIds,\n signedTxs,\n };\n }\n }\n throw new Error(\"please provide owner in keypair format or signAllTransactions function\");\n },\n extInfo: extInfo || {},\n };\n }\n\n public async versionMultiBuild<T extends TxVersion, O = Record<string, any>>({\n extraPreBuildData,\n txVersion,\n extInfo,\n }: {\n extraPreBuildData?: MakeTxData<TxVersion.V0>[] | MakeTxData<TxVersion.LEGACY>[];\n txVersion?: T;\n extInfo?: O;\n }): Promise<MakeMultiTxData<T, O>> {\n if (txVersion === TxVersion.V0)\n return (await this.buildV0MultiTx({\n extraPreBuildData: extraPreBuildData as MakeTxData<TxVersion.V0>[],\n buildProps: extInfo || {},\n })) as MakeMultiTxData<T, O>;\n return this.buildMultiTx<O>({\n extraPreBuildData: extraPreBuildData as MakeTxData<TxVersion.LEGACY>[],\n extInfo,\n }) as MakeMultiTxData<T, O>;\n }\n\n public async buildV0<O = Record<string, any>>(\n props?: O & {\n lookupTableCache?: CacheLTA;\n lookupTableAddress?: string[];\n forerunCreate?: boolean;\n },\n ): Promise<MakeTxData<TxVersion.V0, O>> {\n const { lookupTableCache = {}, lookupTableAddress = [], forerunCreate, ...extInfo } = props || {};\n const lookupTableAddressAccount = {\n ...(this.cluster === \"devnet\" ? {} : LOOKUP_TABLE_CACHE),\n ...lookupTableCache,\n };\n const allLTA = Array.from(new Set<string>([...lookupTableAddress, ...this.lookupTableAddress]));\n const needCacheLTA: PublicKey[] = [];\n for (const item of allLTA) {\n if (lookupTableAddressAccount[item] === undefined) needCacheLTA.push(new PublicKey(item));\n }\n const newCacheLTA = await getMultipleLookupTableInfo({ connection: this.connection, address: needCacheLTA });\n for (const [key, value] of Object.entries(newCacheLTA)) lookupTableAddressAccount[key] = value;\n\n const messageV0 = new TransactionMessage({\n payerKey: this.feePayer,\n recentBlockhash: forerunCreate ? PublicKey.default.toBase58() : await getRecentBlockHash(this.connection),\n instructions: [...this.allInstructions],\n }).compileToV0Message(Object.values(lookupTableAddressAccount));\n const transaction = new VersionedTransaction(messageV0);\n transaction.sign(this.signers);\n\n return {\n builder: this,\n transaction,\n signers: this.signers,\n instructionTypes: [...this.instructionTypes, ...this.endInstructionTypes],\n execute: async (params) => {\n const { recentBlockHash: propBlockHash, skipPreflight = true } = params || {};\n if (propBlockHash) transaction.message.recentBlockhash = propBlockHash;\n printSimulate([transaction]);\n if (this.owner?.isKeyPair) {\n if (!this.signers.find((s) => s.publicKey.equals(this.owner!.publicKey)))\n transaction.sign([this.owner.signer as Signer]);\n const txId = await this.connection.sendTransaction(transaction, { skipPreflight });\n const { lastValidBlockHeight, blockhash } = await this.connection.getLatestBlockhash();\n await this.connection.confirmTransaction(\n {\n blockhash,\n lastValidBlockHeight,\n signature: txId,\n },\n \"confirmed\",\n );\n\n return {\n txId,\n signedTx: transaction,\n };\n }\n if (this.signAllTransactions) {\n const txs = await this.signAllTransactions<VersionedTransaction>([transaction]);\n return {\n txId: await this.connection.sendTransaction(txs[0], { skipPreflight }),\n signedTx: txs[0],\n };\n }\n throw new Error(\"please provide owner in keypair format or signAllTransactions function\");\n },\n extInfo: (extInfo || {}) as O,\n };\n }\n\n public async buildV0MultiTx<T = Record<string, any>>(params: {\n extraPreBuildData?: MakeTxData<TxVersion.V0>[];\n buildProps?: T & {\n lookupTableCache?: CacheLTA;\n lookupTableAddress?: string[];\n };\n }): Promise<MultiTxV0BuildData> {\n const { extraPreBuildData = [], buildProps } = params;\n const { transaction } = await this.buildV0(buildProps);\n\n const filterExtraBuildData = extraPreBuildData.filter((data) => data.builder.instructions.length > 0);\n\n const allTransactions: VersionedTransaction[] = [\n transaction,\n ...filterExtraBuildData.map((data) => data.transaction),\n ];\n const allSigners: Signer[][] = [this.signers, ...filterExtraBuildData.map((data) => data.signers)];\n const allInstructionTypes: string[] = [\n ...this.instructionTypes,\n ...filterExtraBuildData.map((data) => data.instructionTypes).flat(),\n ];\n\n allTransactions.forEach(async (tx, idx) => {\n tx.sign(allSigners[idx]);\n });\n\n return {\n builder: this,\n transactions: allTransactions,\n signers: allSigners,\n instructionTypes: allInstructionTypes,\n buildProps,\n execute: async (executeParams?: MultiTxExecuteParam) => {\n const { sequentially, onTxUpdate, recentBlockHash: propBlockHash, skipPreflight = true } = executeParams || {};\n if (propBlockHash) allTransactions.forEach((tx) => (tx.message.recentBlockhash = propBlockHash));\n printSimulate(allTransactions);\n if (this.owner?.isKeyPair) {\n const { lastValidBlockHeight, blockhash } = await this.connection.getLatestBlockhash();\n allTransactions.forEach((tx, idx) => {\n if (!allSigners[idx].find((s) => s.publicKey.equals(this.owner!.publicKey)))\n tx.sign([this.owner!.signer as Signer]);\n });\n\n if (sequentially) {\n const txIds: string[] = [];\n for (const tx of allTransactions) {\n const txId = await this.connection.sendTransaction(tx, { skipPreflight });\n const { lastValidBlockHeight, blockhash } = await this.connection.getLatestBlockhash();\n await this.connection.confirmTransaction(\n {\n blockhash,\n lastValidBlockHeight,\n signature: txId,\n },\n \"confirmed\",\n );\n txIds.push(txId);\n }\n\n return { txIds, signedTxs: allTransactions };\n }\n\n return {\n txIds: await Promise.all(\n allTransactions.map(async (tx) => {\n const txId = await this.connection.sendTransaction(tx, { skipPreflight });\n await this.connection.confirmTransaction(\n {\n blockhash,\n lastValidBlockHeight,\n signature: txId,\n },\n \"confirmed\",\n );\n return txId;\n }),\n ),\n signedTxs: allTransactions,\n };\n }\n\n if (this.signAllTransactions) {\n const signedTxs = await this.signAllTransactions(allTransactions);\n\n if (sequentially) {\n let i = 0;\n const processedTxs: TxUpdateParams[] = [];\n const checkSendTx = async (): Promise<void> => {\n if (!signedTxs[i]) return;\n const txId = await this.connection.sendTransaction(signedTxs[i], { skipPreflight });\n processedTxs.push({ txId, status: \"sent\", signedTx: signedTxs[i] });\n onTxUpdate?.([...processedTxs]);\n i++;\n this.connection.onSignature(\n txId,\n (signatureResult) => {\n const targetTxIdx = processedTxs.findIndex((tx) => tx.txId === txId);\n if (targetTxIdx > -1) processedTxs[targetTxIdx].status = signatureResult.err ? \"error\" : \"success\";\n onTxUpdate?.([...processedTxs]);\n if (!signatureResult.err) checkSendTx();\n },\n \"processed\",\n );\n this.connection.getSignatureStatus(txId);\n };\n checkSendTx();\n return {\n txIds: [],\n signedTxs,\n };\n } else {\n const txIds: string[] = [];\n for (let i = 0; i < signedTxs.length; i += 1) {\n const txId = await this.connection.sendTransaction(signedTxs[i], { skipPreflight });\n txIds.push(txId);\n }\n return { txIds, signedTxs };\n }\n }\n throw new Error(\"please provide owner in keypair format or signAllTransactions function\");\n },\n extInfo: buildProps || {},\n };\n }\n\n public async sizeCheckBuild(\n props?: Record<string, any> & { computeBudgetConfig?: ComputeBudgetConfig },\n ): Promise<MultiTxBuildData> {\n const { computeBudgetConfig, ...extInfo } = props || {};\n\n const computeBudgetData: { instructions: TransactionInstruction[]; instructionTypes: string[] } =\n computeBudgetConfig\n ? addComputeBudget(computeBudgetConfig)\n : {\n instructions: [],\n instructionTypes: [],\n };\n\n const signerKey: { [key: string]: Signer } = this.signers.reduce(\n (acc, cur) => ({ ...acc, [cur.publicKey.toBase58()]: cur }),\n {},\n );\n\n const allTransactions: Transaction[] = [];\n const allSigners: Signer[][] = [];\n\n let instructionQueue: TransactionInstruction[] = [];\n this.allInstructions.forEach((item) => {\n const _itemIns = [...instructionQueue, item];\n const _itemInsWithCompute = computeBudgetConfig ? [...computeBudgetData.instructions, ..._itemIns] : _itemIns;\n const _signerStrs = new Set<string>(\n _itemIns.map((i) => i.keys.filter((ii) => ii.isSigner).map((ii) => ii.pubkey.toString())).flat(),\n );\n const _signer = [..._signerStrs.values()].map((i) => new PublicKey(i));\n\n if (\n (instructionQueue.length < 12 &&\n checkLegacyTxSize({ instructions: _itemInsWithCompute, payer: this.feePayer, signers: _signer })) ||\n checkLegacyTxSize({ instructions: _itemIns, payer: this.feePayer, signers: _signer })\n ) {\n // current ins add to queue still not exceed tx size limit\n instructionQueue.push(item);\n } else {\n if (instructionQueue.length === 0) throw Error(\"item ins too big\");\n\n // if add computeBudget still not exceed tx size limit\n if (\n checkLegacyTxSize({\n instructions: computeBudgetConfig\n ? [...computeBudgetData.instructions, ...instructionQueue]\n : [...instructionQueue],\n payer: this.feePayer,\n signers: _signer,\n })\n ) {\n allTransactions.push(new Transaction().add(...computeBudgetData.instructions, ...instructionQueue));\n } else {\n allTransactions.push(new Transaction().add(...instructionQueue));\n }\n allSigners.push(\n Array.from(\n new Set<string>(\n instructionQueue.map((i) => i.keys.filter((ii) => ii.isSigner).map((ii) => ii.pubkey.toString())).flat(),\n ),\n )\n .map((i) => signerKey[i])\n .filter((i) => i !== undefined),\n );\n instructionQueue = [item];\n }\n });\n\n if (instructionQueue.length > 0) {\n const _signerStrs = new Set<string>(\n instructionQueue.map((i) => i.keys.filter((ii) => ii.isSigner).map((ii) => ii.pubkey.toString())).flat(),\n );\n const _signers = [..._signerStrs.values()].map((i) => signerKey[i]).filter((i) => i !== undefined);\n\n if (\n checkLegacyTxSize({\n instructions: computeBudgetConfig\n ? [...computeBudgetData.instructions, ...instructionQueue]\n : [...instructionQueue],\n payer: this.feePayer,\n signers: _signers.map((s) => s.publicKey),\n })\n ) {\n allTransactions.push(new Transaction().add(...computeBudgetData.instructions, ...instructionQueue));\n } else {\n allTransactions.push(new Transaction().add(...instructionQueue));\n }\n allSigners.push(_signers);\n }\n allTransactions.forEach((tx) => (tx.feePayer = this.feePayer));\n\n return {\n builder: this,\n transactions: allTransactions,\n signers: allSigners,\n instructionTypes: this.instructionTypes,\n execute: async (executeParams?: MultiTxExecuteParam) => {\n const { sequentially, onTxUpdate, recentBlockHash: propBlockHash, skipPreflight = true } = executeParams || {};\n const recentBlockHash = propBlockHash ?? (await getRecentBlockHash(this.connection));\n allTransactions.forEach(async (tx, idx) => {\n tx.recentBlockhash = recentBlockHash;\n if (allSigners[idx].length) tx.sign(...allSigners[idx]);\n });\n printSimulate(allTransactions);\n if (this.owner?.isKeyPair) {\n if (sequentially) {\n const txIds: string[] = [];\n for (const tx of allTransactions) {\n const txId = await sendAndConfirmTransaction(\n this.connection,\n tx,\n this.signers.find((s) => s.publicKey.equals(this.owner!.publicKey))\n ? this.signers\n : [...this.signers, this.owner.signer!],\n { skipPreflight },\n );\n txIds.push(txId);\n }\n\n return {\n txIds,\n signedTxs: allTransactions,\n };\n }\n return {\n txIds: await Promise.all(\n allTransactions.map(async (tx, idx) => {\n return await sendAndConfirmTransaction(\n this.connection,\n tx,\n allSigners[idx].find((s) => s.publicKey.equals(this.owner!.publicKey))\n ? allSigners[idx]\n : [...allSigners[idx], this.owner!.signer!],\n { skipPreflight },\n );\n }),\n ),\n signedTxs: allTransactions,\n };\n }\n if (this.signAllTransactions) {\n const signedTxs = await this.signAllTransactions(allTransactions);\n if (sequentially) {\n let i = 0;\n const processedTxs: TxUpdateParams[] = [];\n const checkSendTx = async (): Promise<void> => {\n if (!signedTxs[i]) return;\n const txId = await this.connection.sendRawTransaction(signedTxs[i].serialize(), { skipPreflight });\n processedTxs.push({ txId, status: \"sent\", signedTx: signedTxs[i] });\n onTxUpdate?.([...processedTxs]);\n i++;\n this.connection.onSignature(\n txId,\n (signatureResult) => {\n const targetTxIdx = processedTxs.findIndex((tx) => tx.txId === txId);\n if (targetTxIdx > -1) processedTxs[targetTxIdx].status = signatureResult.err ? \"error\" : \"success\";\n onTxUpdate?.([...processedTxs]);\n if (!signatureResult.err) checkSendTx();\n },\n \"processed\",\n );\n this.connection.getSignatureStatus(txId);\n };\n await checkSendTx();\n return {\n txIds: processedTxs.map((d) => d.txId),\n signedTxs,\n };\n } else {\n const txIds: string[] = [];\n for (let i = 0; i < signedTxs.length; i += 1) {\n const txId = await this.connection.sendRawTransaction(signedTxs[i].serialize(), { skipPreflight });\n txIds.push(txId);\n }\n return { txIds, signedTxs };\n }\n }\n throw new Error(\"please provide owner in keypair format or signAllTransactions function\");\n },\n extInfo: extInfo || {},\n };\n }\n\n public async sizeCheckBuildV0(\n props?: Record<string, any> & {\n computeBudgetConfig?: ComputeBudgetConfig;\n lookupTableCache?: CacheLTA;\n lookupTableAddress?: string[];\n },\n ): Promise<MultiTxV0BuildData> {\n const { computeBudgetConfig, lookupTableCache = {}, lookupTableAddress = [], ...extInfo } = props || {};\n const lookupTableAddressAccount = {\n ...(this.cluster === \"devnet\" ? {} : LOOKUP_TABLE_CACHE),\n ...lookupTableCache,\n };\n const allLTA = Array.from(new Set<string>([...this.lookupTableAddress, ...lookupTableAddress]));\n const needCacheLTA: PublicKey[] = [];\n for (const item of allLTA) {\n if (lookupTableAddressAccount[item] === undefined) needCacheLTA.push(new PublicKey(item));\n }\n const newCacheLTA = await getMultipleLookupTableInfo({ connection: this.connection, address: needCacheLTA });\n for (const [key, value] of Object.entries(newCacheLTA)) lookupTableAddressAccount[key] = value;\n\n const computeBudgetData: { instructions: TransactionInstruction[]; instructionTypes: string[] } =\n computeBudgetConfig\n ? addComputeBudget(computeBudgetConfig)\n : {\n instructions: [],\n instructionTypes: [],\n };\n\n const blockHash = await getRecentBlockHash(this.connection);\n\n const signerKey: { [key: string]: Signer } = this.signers.reduce(\n (acc, cur) => ({ ...acc, [cur.publicKey.toBase58()]: cur }),\n {},\n );\n\n const allTransactions: VersionedTransaction[] = [];\n const allSigners: Signer[][] = [];\n\n let instructionQueue: TransactionInstruction[] = [];\n this.allInstructions.forEach((item) => {\n const _itemIns = [...instructionQueue, item];\n const _itemInsWithCompute = computeBudgetConfig ? [...computeBudgetData.instructions, ..._itemIns] : _itemIns;\n if (\n (instructionQueue.length < 12 &&\n checkV0TxSize({ instructions: _itemInsWithCompute, payer: this.feePayer, lookupTableAddressAccount })) ||\n checkV0TxSize({ instructions: _itemIns, payer: this.feePayer, lookupTableAddressAccount })\n ) {\n // current ins add to queue still not exceed tx size limit\n instructionQueue.push(item);\n } else {\n if (instructionQueue.length === 0) throw Error(\"item ins too big\");\n\n const lookupTableAddress: undefined | CacheLTA = {};\n for (const item of [...new Set<string>(allLTA)]) {\n if (lookupTableAddressAccount[item] !== undefined) lookupTableAddress[item] = lookupTableAddressAccount[item];\n }\n // if add computeBudget still not exceed tx size limit\n if (\n computeBudgetConfig &&\n checkV0TxSize({\n instructions: [...computeBudgetData.instructions, ...instructionQueue],\n payer: this.feePayer,\n lookupTableAddressAccount,\n recentBlockhash: blockHash,\n })\n ) {\n const messageV0 = new TransactionMessage({\n payerKey: this.feePayer,\n recentBlockhash: blockHash,\n\n instructions: [...computeBudgetData.instructions, ...instructionQueue],\n }).compileToV0Message(Object.values(lookupTableAddressAccount));\n allTransactions.push(new VersionedTransaction(messageV0));\n } else {\n const messageV0 = new TransactionMessage({\n payerKey: this.feePayer,\n recentBlockhash: blockHash,\n instructions: [...instructionQueue],\n }).compileToV0Message(Object.values(lookupTableAddressAccount));\n allTransactions.push(new VersionedTransaction(messageV0));\n }\n allSigners.push(\n Array.from(\n new Set<string>(\n instructionQueue.map((i) => i.keys.filter((ii) => ii.isSigner).map((ii) => ii.pubkey.toString())).flat(),\n ),\n )\n .map((i) => signerKey[i])\n .filter((i) => i !== undefined),\n );\n instructionQueue = [item];\n }\n });\n\n if (instructionQueue.length > 0) {\n const _signerStrs = new Set<string>(\n instructionQueue.map((i) => i.keys.filter((ii) => ii.isSigner).map((ii) => ii.pubkey.toString())).flat(),\n );\n const _signers = [..._signerStrs.values()].map((i) => signerKey[i]).filter((i) => i !== undefined);\n\n if (\n computeBudgetConfig &&\n checkV0TxSize({\n instructions: [...computeBudgetData.instructions, ...instructionQueue],\n payer: this.feePayer,\n lookupTableAddressAccount,\n recentBlockhash: blockHash,\n })\n ) {\n const messageV0 = new TransactionMessage({\n payerKey: this.feePayer,\n recentBlockhash: blockHash,\n instructions: [...computeBudgetData.instructions, ...instructionQueue],\n }).compileToV0Message(Object.values(lookupTableAddressAccount));\n allTransactions.push(new VersionedTransaction(messageV0));\n } else {\n const messageV0 = new TransactionMessage({\n payerKey: this.feePayer,\n recentBlockhash: blockHash,\n instructions: [...instructionQueue],\n }).compileToV0Message(Object.values(lookupTableAddressAccount));\n allTransactions.push(new VersionedTransaction(messageV0));\n }\n allSigners.push(_signers);\n }\n\n return {\n builder: this,\n transactions: allTransactions,\n buildProps: props,\n signers: allSigners,\n instructionTypes: this.instructionTypes,\n execute: async (executeParams?: MultiTxExecuteParam) => {\n const { sequentially, onTxUpdate, recentBlockHash: propBlockHash, skipPreflight = true } = executeParams || {};\n allTransactions.map(async (tx, idx) => {\n if (allSigners[idx].length) tx.sign(allSigners[idx]);\n if (propBlockHash) tx.message.recentBlockhash = propBlockHash;\n });\n printSimulate(allTransactions);\n if (this.owner?.isKeyPair) {\n const { lastValidBlockHeight, blockhash } = await this.connection.getLatestBlockhash();\n allTransactions.forEach((tx, idx) => {\n if (!allSigners[idx].find((s) => s.publicKey.equals(this.owner!.publicKey)))\n tx.sign([this.owner!.signer as Signer]);\n });\n\n if (sequentially) {\n const txIds: string[] = [];\n for (const tx of allTransactions) {\n const txId = await this.connection.sendTransaction(tx, { skipPreflight });\n const { lastValidBlockHeight, blockhash } = await this.connection.getLatestBlockhash();\n await this.connection.confirmTransaction(\n {\n blockhash,\n lastValidBlockHeight,\n signature: txId,\n },\n \"confirmed\",\n );\n txIds.push(txId);\n }\n\n return { txIds, signedTxs: allTransactions };\n }\n\n return {\n txIds: await Promise.all(\n allTransactions.map(async (tx) => {\n const txId = await this.connection.sendTransaction(tx, { skipPreflight });\n await this.connection.confirmTransaction(\n {\n blockhash,\n lastValidBlockHeight,\n signature: txId,\n },\n \"confirmed\",\n );\n return txId;\n }),\n ),\n signedTxs: allTransactions,\n };\n }\n if (this.signAllTransactions) {\n const signedTxs = await this.signAllTransactions(allTransactions);\n if (sequentially) {\n let i = 0;\n const processedTxs: TxUpdateParams[] = [];\n const checkSendTx = async (): Promise<void> => {\n if (!signedTxs[i]) return;\n const txId = await this.connection.sendTransaction(signedTxs[i], { skipPreflight });\n processedTxs.push({ txId, status: \"sent\", signedTx: signedTxs[i] });\n onTxUpdate?.([...processedTxs]);\n i++;\n this.connection.onSignature(\n txId,\n (signatureResult) => {\n const targetTxIdx = processedTxs.findIndex((tx) => tx.txId === txId);\n if (targetTxIdx > -1) processedTxs[targetTxIdx].status = signatureResult.err ? \"error\" : \"success\";\n onTxUpdate?.([...processedTxs]);\n if (!signatureResult.err) checkSendTx();\n },\n \"processed\",\n );\n this.connection.getSignatureStatus(txId);\n };\n checkSendTx();\n return {\n txIds: [],\n signedTxs,\n };\n } else {\n const txIds: string[] = [];\n for (let i = 0; i < signedTxs.length; i += 1) {\n const txId = await this.connection.sendTransaction(signedTxs[i], { skipPreflight });\n txIds.push(txId);\n }\n return { txIds, signedTxs };\n }\n }\n throw new Error(\"please provide owner in keypair format or signAllTransactions function\");\n },\n extInfo: extInfo || {},\n };\n }\n}\n","export enum TxVersion {\n \"V0\",\n \"LEGACY\",\n}\n\nexport const InstructionType = {\n CreateAccount: \"CreateAccount\",\n InitAccount: \"InitAccount\",\n CreateATA: \"CreateATA\",\n CloseAccount: \"CloseAccount\",\n TransferAmount: \"TransferAmount\",\n InitMint: \"InitMint\",\n MintTo: \"MintTo\",\n\n InitMarket: \"InitMarket\", // create market main ins\n Util1216OwnerClaim: \"Util1216OwnerClaim\", // owner claim token ins\n\n SetComputeUnitPrice: \"SetComputeUnitPrice\",\n SetComputeUnitLimit: \"SetComputeUnitLimit\",\n\n // CLMM\n ClmmCreatePool: \"ClmmCreatePool\",\n ClmmOpenPosition: \"ClmmOpenPosition\",\n ClmmIncreasePosition: \"ClmmIncreasePosition\",\n ClmmDecreasePosition: \"ClmmDecreasePosition\",\n ClmmClosePosition: \"ClmmClosePosition\",\n ClmmSwapBaseIn: \"ClmmSwapBaseIn\",\n ClmmSwapBaseOut: \"ClmmSwapBaseOut\",\n ClmmInitReward: \"ClmmInitReward\",\n ClmmSetReward: \"ClmmSetReward\",\n ClmmCollectReward: \"ClmmCollectReward\",\n\n AmmV4Swap: \"AmmV4Swap\",\n AmmV4AddLiquidity: \"AmmV4AddLiquidity\",\n AmmV4RemoveLiquidity: \"AmmV4RemoveLiquidity\",\n AmmV4SimulatePoolInfo: \"AmmV4SimulatePoolInfo\",\n AmmV4SwapBaseIn: \"AmmV4SwapBaseIn\",\n AmmV4SwapBaseOut: \"AmmV4SwapBaseOut\",\n AmmV4CreatePool: \"AmmV4CreatePool\",\n AmmV4InitPool: \"AmmV4InitPool\",\n\n AmmV5AddLiquidity: \"AmmV5AddLiquidity\",\n AmmV5RemoveLiquidity: \"AmmV5RemoveLiquidity\",\n AmmV5SimulatePoolInfo: \"AmmV5SimulatePoolInfo\",\n AmmV5SwapBaseIn: \"AmmV5SwapBaseIn\",\n AmmV5SwapBaseOut: \"AmmV5SwapBaseOut\",\n\n RouteSwap: \"RouteSwap\",\n RouteSwap1: \"RouteSwap1\",\n RouteSwap2: \"RouteSwap2\",\n\n FarmV3Deposit: \"FarmV3Deposit\",\n FarmV3Withdraw: \"FarmV3Withdraw\",\n FarmV3CreateLedger: \"FarmV3CreateLedger\",\n\n FarmV5Deposit: \"FarmV5Deposit\",\n FarmV5Withdraw: \"FarmV5Withdraw\",\n FarmV5CreateLedger: \"FarmV5CreateLedger\",\n\n FarmV6Deposit: \"FarmV6Deposit\",\n FarmV6Withdraw: \"FarmV6Withdraw\",\n FarmV6Create: \"FarmV6Create\",\n FarmV6Restart: \"FarmV6Restart\",\n FarmV6CreatorAddReward: \"FarmV6CreatorAddReward\",\n FarmV6CreatorWithdraw: \"FarmV6CreatorWithdraw\",\n\n CpmmCreatePool: \"CpmmCreatePool\",\n CpmmAddLiquidity: \"CpmmAddLiquidity\",\n CpmmWithdrawLiquidity: \"CpmmWithdrawLiquidity\",\n CpmmSwapBaseIn: \"CpmmSwapBaseIn\",\n CpmmSwapBaseOut: \"CpmmSwapBaseOut\",\n};\n","import {\n Connection,\n PublicKey,\n ComputeBudgetProgram,\n SimulatedTransactionResponse,\n Transaction,\n TransactionInstruction,\n TransactionMessage,\n Keypair,\n EpochInfo,\n VersionedTransaction,\n} from \"@solana/web3.js\";\nimport { TOKEN_PROGRAM_ID } from \"@solana/spl-token\";\n\nimport { createLogger } from \"../logger\";\nimport { InstructionType } from \"./txType\";\nimport { CacheLTA } from \"./lookupTable\";\n\nimport { ComputeBudgetConfig } from \"@/raydium/type\";\n\nconst logger = createLogger(\"Raydium_txUtil\");\n\nexport const MAX_BASE64_SIZE = 1644;\n\nexport function addComputeBudget(config: ComputeBudgetConfig): {\n instructions: TransactionInstruction[];\n instructionTypes: string[];\n} {\n const ins: TransactionInstruction[] = [];\n const insTypes: string[] = [];\n if (config.microLamports) {\n ins.push(ComputeBudgetProgram.setComputeUnitPrice({ microLamports: config.microLamports }));\n insTypes.push(InstructionType.SetComputeUnitPrice);\n }\n if (config.units) {\n ins.push(ComputeBudgetProgram.setComputeUnitLimit({ units: config.units }));\n insTypes.push(InstructionType.SetComputeUnitLimit);\n }\n\n return {\n instructions: ins,\n instructionTypes: insTypes,\n };\n}\n\nexport async function getRecentBlockHash(connection: Connection): Promise<string> {\n try {\n return (await connection.getLatestBlockhash?.())?.blockhash || (await connection.getRecentBlockhash()).blockhash;\n } catch {\n return (await connection.getRecentBlockhash()).blockhash;\n }\n}\n\n/**\n * Forecast transaction size\n */\nexport function forecastTransactionSize(instructions: TransactionInstruction[], signers: PublicKey[]): boolean {\n if (instructions.length < 1) logger.logWithError(`no instructions provided: ${instructions.toString()}`);\n if (signers.length < 1) logger.logWithError(`no signers provided:, ${signers.toString()}`);\n\n const transaction = new Transaction();\n transaction.recentBlockhash = \"11111111111111111111111111111111\";\n transaction.feePayer = signers[0];\n transaction.add(...instructions);\n\n try {\n return Buffer.from(transaction.serialize({ verifySignatures: false })).toString(\"base64\").length < MAX_BASE64_SIZE;\n } catch (error) {\n return false;\n }\n}\n\n/**\n * Simulates multiple instruction\n */\n/**\n * Simulates multiple instruction\n */\nexport async function simulateMultipleInstruction(\n connection: Connection,\n instructions: TransactionInstruction[],\n keyword: string,\n batchRequest = true,\n): Promise<string[]> {\n const feePayer = new PublicKey(\"RaydiumSimuLateTransaction11111111111111111\");\n\n const transactions: Transaction[] = [];\n\n let transaction = new Transaction();\n transaction.feePayer = feePayer;\n\n for (const instruction of instructions) {\n if (!forecastTransactionSize([...transaction.instructions, instruction], [feePayer])) {\n transactions.push(transaction);\n transaction = new Transaction();\n transaction.feePayer = feePayer;\n }\n transaction.add(instruction);\n }\n if (transaction.instructions.length > 0) {\n transactions.push(transaction);\n }\n\n let results: SimulatedTransactionResponse[] = [];\n\n try {\n results = await simulateTransaction(connection, transactions, batchRequest);\n if (results.find((i) => i.err !== null)) throw Error(\"rpc simulateTransaction error\");\n } catch (error) {\n if (error instanceof Error) {\n logger.logWithError(\"failed to simulate for instructions\", \"RPC_ERROR\", {\n message: error.message,\n });\n }\n }\n\n const logs: string[] = [];\n for (const result of results) {\n logger.debug(\"simulate result:\", result);\n\n if (result.logs) {\n const filteredLog = result.logs.filter((log) => log && log.includes(keyword));\n logger.debug(\"filteredLog:\", logs);\n if (!filteredLog.length) logger.logWithError(\"simulate log not match keyword\", \"keyword\", keyword);\n logs.push(...filteredLog);\n }\n }\n\n return logs;\n}\n\nexport function parseSimulateLogToJson(log: string, keyword: string): any {\n const results = log.match(/{[\"\\w:,]+}/g);\n if (!results || results.length !== 1) {\n return logger.logWithError(`simulate log fail to match json, keyword: ${keyword}`);\n }\n\n return results[0];\n}\n\nexport function parseSimulateValue(log: string, key: string): any {\n const reg = new RegExp(`\"${key}\":(\\\\d+)`, \"g\");\n\n const results = reg.exec(log);\n if (!results || results.length !== 2) {\n return logger.logWithError(`simulate log fail to match key\", key: ${key}`);\n }\n\n return results[1];\n}\n\nexport interface ProgramAddress {\n publicKey: PublicKey;\n nonce: number;\n}\nexport function findProgramAddress(\n seeds: Array<Buffer | Uint8Array>,\n programId: PublicKey,\n): {\n publicKey: PublicKey;\n nonce: number;\n} {\n const [publicKey, nonce] = PublicKey.findProgramAddressSync(seeds, programId);\n return { publicKey, nonce };\n}\n\nexport async function simulateTransaction(\n connection: Connection,\n transactions: Transaction[],\n batchRequest?: boolean,\n): Promise<any[]> {\n let results: any[] = [];\n if (batchRequest) {\n const getLatestBlockhash = await connection.getLatestBlockhash();\n\n const encodedTransactions: string[] = [];\n for (const transaction of transactions) {\n transaction.recentBlockhash = getLatestBlockhash.blockhash;\n transaction.lastValidBlockHeight = getLatestBlockhash.lastValidBlockHeight;\n\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n const message = transaction._compile();\n const signData = message.serialize();\n\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n const wireTransaction = transaction._serialize(signData);\n const encodedTransaction = wireTransaction.toString(\"base64\");\n\n encodedTransactions.push(encodedTransaction);\n }\n\n const batch = encodedTransactions.map((keys) => {\n const args = connection._buildArgs([keys], undefined, \"base64\");\n return {\n methodName: \"simulateTransaction\",\n args,\n };\n });\n\n const reqData: { methodName: string; args: any[] }[][] = [];\n const itemReqIndex = 20;\n for (let i = 0; i < Math.ceil(batch.length / itemReqIndex); i++) {\n reqData.push(batch.slice(i * itemReqIndex, (i + 1) * itemReqIndex));\n }\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n results = await (\n await Promise.all(\n reqData.map(async (i) => (await (connection as any)._rpcBatchRequest(i)).map((ii) => ii.result.value)),\n )\n ).flat();\n } else {\n try {\n results = await Promise.all(\n transactions.map(async (transaction) => await (await connection.simulateTransaction(transaction)).value),\n );\n } catch (error) {\n if (error instanceof Error) {\n logger.logWithError(\"failed to get info for multiple accounts\", \"RPC_ERROR\", {\n message: error.message,\n });\n }\n }\n }\n\n return results;\n}\n\nexport function checkLegacyTxSize({\n instructions,\n payer,\n signers,\n}: {\n instructions: TransactionInstruction[];\n payer: PublicKey;\n signers: PublicKey[];\n}): boolean {\n return forecastTransactionSize(instructions, [payer, ...signers]);\n}\n\nexport function checkV0TxSize({\n instructions,\n payer,\n lookupTableAddressAccount,\n recentBlockhash = Keypair.generate().publicKey.toString(),\n}: {\n instructions: TransactionInstruction[];\n payer: PublicKey;\n lookupTableAddressAccount?: CacheLTA;\n recentBlockhash?: string;\n}): boolean {\n const transactionMessage = new TransactionMessage({\n payerKey: payer,\n recentBlockhash,\n instructions,\n });\n\n const messageV0 = transactionMessage.compileToV0Message(Object.values(lookupTableAddressAccount ?? {}));\n try {\n const buildLength = Buffer.from(new VersionedTransaction(messageV0).serialize()).toString(\"base64\").length;\n return buildLength < MAX_BASE64_SIZE;\n } catch (error) {\n return false;\n }\n}\n\nlet epochInfoCache: { time: number; data?: EpochInfo } = {\n time: 0,\n data: undefined,\n};\n\nexport async function getEpochInfo(connection: Connection): Promise<EpochInfo> {\n if (!epochInfoCache.data || (Date.now() - epochInfoCache.time) / 1000 > 30) {\n const data = await connection.getEpochInfo();\n epochInfoCache = {\n time: Date.now(),\n data,\n };\n return data;\n } else {\n return epochInfoCache.data;\n }\n}\n\nexport const toBuffer = (arr: Buffer | Uint8Array | Array<number>): Buffer => {\n if (Buffer.isBuffer(arr)) {\n return arr;\n } else if (arr instanceof Uint8Array) {\n return Buffer.from(arr.buffer, arr.byteOffset, arr.byteLength);\n } else {\n return Buffer.from(arr);\n }\n};\n\nexport function printSimulate(transactions: Transaction[] | VersionedTransaction[]): string[] {\n const allBase64: string[] = [];\n transactions.forEach((transaction) => {\n if (transaction instanceof Transaction) {\n if (!transaction.recentBlockhash) transaction.recentBlockhash = TOKEN_PROGRAM_ID.toBase58();\n if (!transaction.feePayer) transaction.feePayer = Keypair.generate().publicKey;\n }\n let serialized = transaction.serialize({ requireAllSignatures: false, verifySignatures: false });\n if (transaction instanceof VersionedTransaction) serialized = toBuffer(serialized);\n const base64 = serialized.toString(\"base64\");\n allBase64.push(base64);\n });\n console.log(\"simulate tx string:\", allBase64);\n\n return allBase64;\n}\n","import { Connection, PublicKey, AddressLookupTableAccount } from \"@solana/web3.js\";\nimport { getMultipleAccountsInfo } from \"../accountInfo\";\n\nexport interface CacheLTA {\n [key: string]: AddressLookupTableAccount;\n}\n\nexport async function getMultipleLookupTableInfo({\n connection,\n address,\n}: {\n connection: Connection;\n address: PublicKey[];\n}): Promise<CacheLTA> {\n const dataInfos = await getMultipleAccountsInfo(\n connection,\n [...new Set<string>(address.map((i) => i.toString()))].map((i) => new PublicKey(i)),\n );\n\n const outDict: CacheLTA = {};\n for (let i = 0; i < address.length; i++) {\n const info = dataInfos[i];\n const key = address[i];\n if (!info) continue;\n const lookupAccount = new AddressLookupTableAccount({\n key,\n state: AddressLookupTableAccount.deserialize(info.data),\n });\n outDict[key.toString()] = lookupAccount;\n LOOKUP_TABLE_CACHE[key.toString()] = lookupAccount;\n }\n\n return outDict;\n}\n\nexport const LOOKUP_TABLE_CACHE: CacheLTA = {\n \"2immgwYNHBbyVQKVGCEkgWpi53bLwWNRMB5G2nbgYV17\": new AddressLookupTableAccount({\n key: new PublicKey(\"2immgwYNHBbyVQKVGCEkgWpi53bLwWNRMB5G2nbgYV17\"),\n state: AddressLookupTableAccount.deserialize(\n Buffer.from(\n \"AQAAAP//////////d49+DAAAAAAAAQZMWvw7GUNJdaccNBVnb57OKakxL2BHLYvhRwVILRsgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMGRm/lIRcy/+ytunLDm+e8jOW7xfcSayxDmzpAAAAABt324ddloZPZy+FGzut5rBy0he1fWzeROoz1hX7/AKkG3fbh7nWP3hhCXbzkbM3athr8TYO5DSf+vfko2KGL/AVKU1D4XciC1hSlVnJ4iilt3x6rq9CmBniISTL07vagBqfVFxksXFEhjMlMPUrxf1ja7gibof1E49vZigAAAAAGp9UXGMd0yShWY5hpHV62i164o5tLbVxzVVshAAAAAIyXJY9OJInxuz0QKRSODYMLWhOZ2v8QhASOe9jb6fhZC3BlsePRfEU4nVJ/awTDzVi4bHMaoP21SbbRvAP4KUbIScv+6Yw2LHF/6K0ZjUPibbSWXCirYPGuuVl7zT789IUPLW4CpHr4JNCatp3ELXDLKMv6JJ+37le50lbBJ2LvDQdRqCgtphMF/imcN7mY5YRx2xE1A3MQ+L4QRaYK9u4GRfZP3LsAd00a+IkCpA22UNQMKdq5BFbJuwuOLqc8zxCTDlqxBG8J0HcxtfogQHDK06ukzfaXiNDKAob1MqBHS9lJxDYCwz8gd5DtFqNSTKG5l1zxIaKpDP/sffi2is1H9aKveyXSu5StXElYRl9SD5As0DHE4N0GLnf84/siiKXVyp4Ez121kLcUui/jLLFZEz/BwZK3Ilf9B9OcsEAeDMKAy2vjGSxQODgBz0QwGA+eP4ZjIjrIAQaXENv31QfLlOdXSRCkaybRniDHF4C8YcwhcvsqrOVuTP4B2Na+9wLdtrB31uz2rtlFI5kahdsnp/d1SrASDInYCtTYtdoke4kX+hoKWcEWM4Tle8pTUkUVv4BxS6fje/EzKBE4Qu9N9LMnrw/JNO0hqMVB4rk/2ou4AB1loQ7FZoPwut2o4KZB+0p9xnbrQKw038qjpHar+PyDwvxBRcu5hpHw3dguezeWv+IwvgW5icu8EGkhGa9AkFPPJT7VMSFb8xowveU=\",\n \"base64\",\n ),\n ),\n }),\n};\n","import { AccountInfo, Commitment, Connection, PublicKey } from \"@solana/web3.js\";\nimport { getTransferFeeConfig, unpackMint } from \"@solana/spl-token\";\nimport { chunkArray } from \"./\";\nimport { createLogger } from \"./logger\";\nimport { ReturnTypeFetchMultipleMintInfos } from \"../raydium/type\";\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}\n\nconst logger = createLogger(\"Raydium_accountInfo_util\");\n\nexport async function getMultipleAccountsInfo(\n connection: Connection,\n publicKeys: PublicKey[],\n config?: GetMultipleAccountsInfoConfig,\n): Promise<(AccountInfo<Buffer> | null)[]> {\n const { batchRequest, commitment = \"confirmed\" } = {\n batchRequest: false,\n ...config,\n };\n\n const chunkedKeys = chunkArray(publicKeys, 100);\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}: {\n connection: Connection;\n mints: PublicKey[];\n}): Promise<ReturnTypeFetchMultipleMintInfos> {\n if (mints.length === 0) return {};\n const mintInfos = await getMultipleAccountsInfoWithCustomFlags(\n connection,\n mints.map((i) => ({ pubkey: i })),\n );\n\n const mintK: ReturnTypeFetchMultipleMintInfos = {};\n for (const i of mintInfos) {\n const t = unpackMint(i.pubkey, i.accountInfo, i.accountInfo?.owner);\n mintK[i.pubkey.toString()] = {\n ...t,\n feeConfig: getTransferFeeConfig(t) ?? undefined,\n };\n }\n\n return mintK;\n}\n","/**\n * https://youmightnotneed.com/lodash/\n */\n\nexport function chunkArray<T>(arr: T[], chunkSize = 1, cache: T[][] = []): T[][] {\n const tmp = [...arr];\n if (chunkSize <= 0) return cache;\n while (tmp.length) cache.push(tmp.splice(0, chunkSize));\n return cache;\n}\n\nexport function intersection<T>(arr: T[], ...args: T[][]): T[] {\n return arr.filter((item) => args.every((arr) => arr.includes(item)));\n}\n\nexport function xor<T>(arr: T[], ...args: T[][]): T[] {\n return arr.filter((item) => args.every((arr) => !arr.includes(item)));\n}\n\nexport function uniq<T>(arr: T[]): T[] {\n return [...new Set(arr)];\n}\n","import { PublicKey } from \"@solana/web3.js\";\n\n// raydium\nexport const FARM_PROGRAM_ID_V3 = new PublicKey(\"EhhTKczWMGQt46ynNeRX1WfeagwwJd7ufHvCDjRxjo5Q\");\n// \"fusion\"\nexport const FARM_PROGRAM_ID_V5 = new PublicKey(\"9KEPoZmtHUrBbhWN1v1KWLMkkvwY6WLtAVUCPRtRjP4z\");\n// echosystem\nexport const FARM_PROGRAM_ID_V6 = new PublicKey(\"FarmqiPv5eAj3j1GMdMCMUGXqPUvmquZtMy86QH6rzhG\");\n\nexport const UTIL1216 = new PublicKey(\"CLaimxFqjHzgTJtAGHU47NPhg6qrc5sCnpC4tBLyABQS\");\n\nexport const OPEN_BOOK_PROGRAM = new PublicKey(\"srmqPvymJeFKQ4zGQed1GFppgkRHL9kaELCbyksJtPX\");\nexport const SERUM_PROGRAM_ID_V3 = new PublicKey(\"9xQeWvG816bUx9EPjHmaT23yvVM2ZWbrrpZb9PusVFin\");\n\nexport const AMM_V4 = new PublicKey(\"675kPX9MHTjS2zt1qfr1NYHuzeLXfQM9H24wFSUt1Mp8\");\nexport const AMM_STABLE = new PublicKey(\"5quBtoiQqxF9Jv6KYKctB59NT3gtJD2Y65kdnB1Uev3h\");\nexport const CLMM_PROGRAM_ID = new PublicKey(\"CAMMCzo5YL8w4VFF8KVHrK22GGUsp5VTaW7grrKgrWqK\");\nexport const Router = new PublicKey(\"routeUGWgWzqBWFcrCfv8tritsqukccJPu3q5GPP3xS\");\nexport const FEE_DESTINATION_ID = new PublicKey(\"7YttLkHDoNj9wyDur5pM1ejNaAvT9X4eqaYcHQqtj2G5\");\n\nexport const IDO_PROGRAM_ID_V1 = new PublicKey(\"6FJon3QE27qgPVggARueB22hLvoh22VzJpXv4rBEoSLF\");\nexport const IDO_PROGRAM_ID_V2 = new PublicKey(\"CC12se5To1CdEuw7fDS27B7Geo5jJyL7t5UK2B44NgiH\");\nexport const IDO_PROGRAM_ID_V3 = new PublicKey(\"9HzJyW1qZsEiSfMUf6L2jo3CcTKAyBmSyKdwQeYisHrC\");\nexport const IDO_PROGRAM_ID_V4 = new PublicKey(\"DropEU8AvevN3UrXWXTMuz3rqnMczQVNjq3kcSdW2SQi\");\n\nexport const CREATE_CPMM_POOL_PROGRAM = new PublicKey(\"CPMMoo8L3F4NbTegBCKVNunggL7H1ZpdTHKxQB5qKP1C\");\nexport const CREATE_CPMM_POOL_AUTH = new PublicKey(\"GpMZbSM2GgvTKHJirzeGfMFoaZ8UR2X7F4v8vHTvxFbL\");\nexport const CREATE_CPMM_POOL_FEE_ACC = new PublicKey(\"DNXgeM9EiiaAbaWvwjHj9fQQLAX5ZsfHyvmYUNRAdNC8\");\n\nexport const DEV_CREATE_CPMM_POOL_PROGRAM = new PublicKey(\"CPMDWBwJDtYax9qW7AyRuVC19Cc4L4Vcy4n2BHAbHkCW\");\nexport const DEV_CREATE_CPMM_POOL_AUTH = new PublicKey(\"7rQ1QFNosMkUCuh7Z7fPbTHvh73b68sQYdirycEzJVuw\");\nexport const DEV_CREATE_CPMM_POOL_FEE_ACC = new PublicKey(\"G11FKBRaAkHAKuLCgLM6K6NUc9rTjPAznRCjZifrTQe2\");\n\nexport const IDO_ALL_PROGRAM = {\n IDO_PROGRAM_ID_V1,\n IDO_PROGRAM_ID_V2,\n IDO_PROGRAM_ID_V3,\n IDO_PROGRAM_ID_V4,\n};\n\nexport const ALL_PROGRAM_ID = {\n AMM_V4,\n AMM_STABLE,\n CLMM_PROGRAM_ID,\n\n FARM_PROGRAM_ID_V3,\n FARM_PROGRAM_ID_V5,\n FARM_PROGRAM_ID_V6,\n\n OPEN_BOOK_PROGRAM,\n SERUM_PROGRAM_ID_V3,\n\n UTIL1216,\n\n Router,\n\n CREATE_CPMM_POOL_PROGRAM,\n CREATE_CPMM_POOL_AUTH,\n CREATE_CPMM_POOL_FEE_ACC,\n};\n\nexport type ProgramIdConfig = Partial<typeof ALL_PROGRAM_ID>;\n\nexport const DEVNET_PROGRAM_ID = {\n SERUM_MARKET: PublicKey.default,\n OPENBOOK_MARKET: new PublicKey(\"EoTcMgcDRTJVZDMZWBoU6rhYHZfkNTVEAfz3uUJRcYGj\"),\n\n UTIL1216: PublicKey.default,\n\n FarmV3: new PublicKey(\"85BFyr98MbCUU9MVTEgzx1nbhWACbJqLzho6zd6DZcWL\"),\n FarmV5: new PublicKey(\"EcLzTrNg9V7qhcdyXDe2qjtPkiGzDM2UbdRaeaadU5r2\"),\n FarmV6: new PublicKey(\"Farm2hJLcqPtPg8M4rR6DMrsRNc5TPm5Cs4bVQrMe2T7\"),\n\n AmmV4: new PublicKey(\"HWy1jotHpo6UqeQxx49dpYYdQB8wj9Qk9MdxwjLvDHB8\"),\n AmmStable: new PublicKey(\"DDg4VmQaJV9ogWce7LpcjBA9bv22wRp5uaTPa5pGjijF\"),\n\n CLMM: new PublicKey(\"devi51mZmdwUJGU9hjN27vEz64Gps7uUefqxg27EAtH\"),\n\n Router: new PublicKey(\"BVChZ3XFEwTMUk1o9i3HAf91H6mFxSwa5X2wFAWhYPhU\"),\n\n CREATE_CPMM_POOL_PROGRAM: DEV_CREATE_CPMM_POOL_PROGRAM,\n CREATE_CPMM_POOL_AUTH: DEV_CREATE_CPMM_POOL_AUTH,\n CREATE_CPMM_POOL_FEE_ACC: DEV_CREATE_CPMM_POOL_FEE_ACC,\n\n FEE_DESTINATION_ID: new PublicKey(\"3XMrhbv989VxAMi3DErLV9eJht1pHppW5LbKxe9fkEFR\"),\n};\n","import { PublicKey } from \"@solana/web3.js\";\n\nimport { findProgramAddress } from \"./txTool/txUtils\";\nimport { TOKEN_PROGRAM_ID } from \"@solana/spl-token\";\n\nexport function getATAAddress(\n owner: PublicKey,\n mint: PublicKey,\n programId?: PublicKey,\n): {\n publicKey: PublicKey;\n nonce: number;\n} {\n return findProgramAddress(\n [owner.toBuffer(), (programId ?? TOKEN_PROGRAM_ID).toBuffer(), mint.toBuffer()],\n new PublicKey(\"ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL\"),\n );\n}\n","import { EpochInfo } from \"@solana/web3.js\";\nimport { TransferFeeConfig, TransferFee } from \"@solana/spl-token\";\nimport BN from \"bn.js\";\n\nimport { GetTransferAmountFee } from \"../raydium/type\";\nimport { TransferFeeDataBaseType } from \"../api/type\";\n\nconst POINT = 10_000;\nexport function getTransferAmountFee(\n amount: BN,\n feeConfig: TransferFeeConfig | undefined,\n epochInfo: EpochInfo,\n addFee: boolean,\n): GetTransferAmountFee {\n if (feeConfig === undefined) {\n return {\n amount,\n fee: undefined,\n expirationTime: undefined,\n };\n }\n\n const nowFeeConfig: TransferFee =\n epochInfo.epoch < feeConfig.newerTransferFee.epoch ? feeConfig.olderTransferFee : feeConfig.newerTransferFee;\n const maxFee = new BN(nowFeeConfig.maximumFee.toString());\n const expirationTime: number | undefined =\n epochInfo.epoch < feeConfig.newerTransferFee.epoch\n ? ((Number(feeConfig.newerTransferFee.epoch) * epochInfo.slotsInEpoch - epochInfo.absoluteSlot) * 400) / 1000\n : undefined;\n\n if (addFee) {\n if (nowFeeConfig.transferFeeBasisPoints === POINT) {\n const nowMaxFee = new BN(nowFeeConfig.maximumFee.toString());\n return {\n amount: amount.add(nowMaxFee),\n fee: nowMaxFee,\n expirationTime,\n };\n } else {\n const _TAmount = BNDivCeil(amount.mul(new BN(POINT)), new BN(POINT - nowFeeConfig.transferFeeBasisPoints));\n\n const nowMaxFee = new BN(nowFeeConfig.maximumFee.toString());\n const TAmount = _TAmount.sub(amount).gt(nowMaxFee) ? amount.add(nowMaxFee) : _TAmount;\n\n const _fee = BNDivCeil(TAmount.mul(new BN(nowFeeConfig.transferFeeBasisPoints)), new BN(POINT));\n const fee = _fee.gt(maxFee) ? maxFee : _fee;\n return {\n amount: TAmount,\n fee,\n expirationTime,\n };\n }\n } else {\n const _fee = BNDivCeil(amount.mul(new BN(nowFeeConfig.transferFeeBasisPoints)), new BN(POINT));\n const fee = _fee.gt(maxFee) ? maxFee : _fee;\n\n return {\n amount,\n fee,\n expirationTime,\n };\n }\n}\n\nexport function getTransferAmountFeeV2(\n amount: BN,\n _feeConfig: TransferFeeDataBaseType | undefined,\n epochInfo: EpochInfo,\n addFee: boolean,\n): GetTransferAmountFee {\n if (_feeConfig === undefined) {\n return {\n amount,\n fee: undefined,\n expirationTime: undefined,\n };\n }\n const feeConfig = {\n ..._feeConfig,\n olderTransferFee: {\n epoch: BigInt(_feeConfig.olderTransferFee.epoch),\n maximumFee: BigInt(_feeConfig.olderTransferFee.maximumFee),\n transferFeeBasisPoints: _feeConfig.olderTransferFee.transferFeeBasisPoints,\n },\n newerTransferFee: {\n epoch: BigInt(_feeConfig.newerTransferFee.epoch),\n maximumFee: BigInt(_feeConfig.newerTransferFee.maximumFee),\n transferFeeBasisPoints: _feeConfig.newerTransferFee.transferFeeBasisPoints,\n },\n };\n\n const nowFeeConfig: TransferFee =\n epochInfo.epoch < feeConfig.newerTransferFee.epoch ? feeConfig.olderTransferFee : feeConfig.newerTransferFee;\n const maxFee = new BN(nowFeeConfig.maximumFee.toString());\n const expirationTime: number | undefined =\n epochInfo.epoch < feeConfig.newerTransferFee.epoch\n ? ((Number(feeConfig.newerTransferFee.epoch) * epochInfo.slotsInEpoch - epochInfo.absoluteSlot) * 400) / 1000\n : undefined;\n\n if (addFee) {\n if (nowFeeConfig.transferFeeBasisPoints === POINT) {\n const nowMaxFee = new BN(nowFeeConfig.maximumFee.toString());\n return {\n amount: amount.add(nowMaxFee),\n fee: nowMaxFee,\n expirationTime,\n };\n } else {\n const _TAmount = BNDivCeil(amount.mul(new BN(POINT)), new BN(POINT - nowFeeConfig.transferFeeBasisPoints));\n\n const nowMaxFee = new BN(nowFeeConfig.maximumFee.toString());\n const TAmount = _TAmount.sub(amount).gt(nowMaxFee) ? amount.add(nowMaxFee) : _TAmount;\n\n const _fee = BNDivCeil(TAmount.mul(new BN(nowFeeConfig.transferFeeBasisPoints)), new BN(POINT));\n const fee = _fee.gt(maxFee) ? maxFee : _fee;\n return {\n amount: TAmount,\n fee,\n expirationTime,\n };\n }\n } else {\n const _fee = BNDivCeil(amount.mul(new BN(nowFeeConfig.transferFeeBasisPoints)), new BN(POINT));\n const fee = _fee.gt(maxFee) ? maxFee : _fee;\n\n return {\n amount,\n fee,\n expirationTime,\n };\n }\n}\n\nexport function minExpirationTime(\n expirationTime1: number | undefined,\n expirationTime2: number | undefined,\n): number | undefined {\n if (expirationTime1 === undefined) return expirationTime2;\n if (expirationTime2 === undefined) return expirationTime1;\n\n return Math.min(expirationTime1, expirationTime2);\n}\n\nexport function BNDivCeil(bn1: BN, bn2: BN): BN {\n const { div, mod } = bn1.divmod(bn2);\n\n if (mod.gt(new BN(0))) {\n return div.add(new BN(1));\n } else {\n return div;\n }\n}\n","import { PublicKey } from \"@solana/web3.js\";\n\nimport { createLogger, Logger } from \"../common/logger\";\nimport { TxBuilder } from \"../common/txTool/txTool\";\n\nimport { Raydium } from \"./\";\n\nexport interface ModuleBaseProps {\n scope: Raydium;\n moduleName: string;\n}\n\nconst joinMsg = (...args: (string | number | Record<string, any>)[]): string =>\n args\n .map((arg) => {\n try {\n return typeof arg === \"object\" ? JSON.stringify(arg) : arg;\n } catch {\n return arg;\n }\n })\n .join(\", \");\nexport default class ModuleBase {\n public scope: Raydium;\n private disabled = false;\n protected logger: Logger;\n\n constructor({ scope, moduleName }: ModuleBaseProps) {\n this.scope = scope;\n this.logger = createLogger(moduleName);\n }\n\n protected createTxBuilder(feePayer?: PublicKey): TxBuilder {\n this.scope.checkOwner();\n return new TxBuilder({\n connection: this.scope.connection,\n feePayer: feePayer || this.scope.ownerPubKey,\n cluster: this.scope.cluster,\n owner: this.scope.owner,\n signAllTransactions: this.scope.signAllTransactions,\n });\n }\n\n public logDebug(...args: (string | number | Record<string, any>)[]): void {\n this.logger.debug(joinMsg(args));\n }\n\n public logInfo(...args: (string | number | Record<string, any>)[]): void {\n this.logger.info(joinMsg(args));\n }\n\n public logAndCreateError(...args: (string | number | Record<string, any>)[]): void {\n const message = joinMsg(args);\n // this.logger.error(message);\n throw new Error(message);\n }\n\n public checkDisabled(): void {\n if (this.disabled || !this.scope) this.logAndCreateError(\"module not working\");\n }\n}\n","import {\n createInitializeAccountInstruction,\n createCloseAccountInstruction,\n createTransferInstruction,\n TOKEN_PROGRAM_ID,\n} from \"@solana/spl-token\";\nimport { Commitment, Connection, PublicKey, Signer, SystemProgram, TransactionInstruction } from \"@solana/web3.js\";\nimport BN from \"bn.js\";\nimport { generatePubKey } from \"./util\";\nimport { BigNumberish, parseBigNumberish } from \"@/common\";\nimport { AddInstructionParam } from \"@/common/txTool/txTool\";\nimport { InstructionType } from \"@/common/txTool/txType\";\nimport { TOKEN_WSOL } from \"../token/constant\";\n\nimport { splAccountLayout } from \"./layout\";\n\nexport function initTokenAccountInstruction(params: {\n mint: PublicKey;\n tokenAccount: PublicKey;\n owner: PublicKey;\n programId?: PublicKey;\n}): TransactionInstruction {\n const { mint, tokenAccount, owner, programId = TOKEN_PROGRAM_ID } = params;\n return createInitializeAccountInstruction(tokenAccount, mint, owner, programId);\n}\n\nexport function closeAccountInstruction(params: {\n tokenAccount: PublicKey;\n payer: PublicKey;\n multiSigners?: Signer[];\n owner: PublicKey;\n programId?: PublicKey;\n}): TransactionInstruction {\n const { tokenAccount, payer, multiSigners = [], owner, programId = TOKEN_PROGRAM_ID } = params;\n return createCloseAccountInstruction(tokenAccount, payer, owner, multiSigners, programId);\n}\n\ninterface CreateWSolTokenAccount {\n connection: Connection;\n payer: PublicKey;\n owner: PublicKey;\n amount: BigNumberish;\n commitment?: Commitment;\n skipCloseAccount?: boolean;\n}\n/**\n * WrappedNative account = wsol account\n */\nexport async function createWSolAccountInstructions(params: CreateWSolTokenAccount): Promise<\n AddInstructionParam & {\n addresses: { newAccount: PublicKey };\n }\n> {\n const { connection, amount, commitment, payer, owner, skipCloseAccount } = params;\n\n const balanceNeeded = await connection.getMinimumBalanceForRentExemption(splAccountLayout.span, commitment);\n const lamports = parseBigNumberish(amount).add(new BN(balanceNeeded));\n const newAccount = generatePubKey({ fromPublicKey: payer, programId: TOKEN_PROGRAM_ID });\n\n return {\n addresses: { newAccount: newAccount.publicKey },\n signers: [],\n instructions: [\n SystemProgram.createAccountWithSeed({\n fromPubkey: payer,\n basePubkey: payer,\n seed: newAccount.seed,\n newAccountPubkey: newAccount.publicKey,\n lamports: lamports.toNumber(),\n space: splAccountLayout.span,\n programId: TOKEN_PROGRAM_ID,\n }),\n initTokenAccountInstruction({\n mint: new PublicKey(TOKEN_WSOL.address),\n tokenAccount: newAccount.publicKey,\n owner,\n programId: TOKEN_PROGRAM_ID,\n }),\n ],\n instructionTypes: [InstructionType.CreateAccount, InstructionType.InitAccount],\n endInstructionTypes: skipCloseAccount ? [] : [InstructionType.CloseAccount],\n endInstructions: skipCloseAccount\n ? []\n : [\n closeAccountInstruction({\n tokenAccount: newAccount.publicKey,\n payer,\n owner,\n }),\n ],\n };\n}\n\nexport function makeTransferInstruction({\n source,\n destination,\n owner,\n amount,\n multiSigners = [],\n tokenProgram = TOKEN_PROGRAM_ID,\n}: {\n source: PublicKey;\n destination: PublicKey;\n owner: PublicKey;\n amount: BigNumberish;\n multiSigners?: Signer[];\n tokenProgram?: PublicKey;\n}): TransactionInstruction {\n return createTransferInstruction(source, destination, owner, BigInt(String(amount)), multiSigners, tokenProgram);\n}\n","import { AccountInfo, PublicKey, RpcResponseAndContext, Keypair, GetProgramAccountsResponse } from \"@solana/web3.js\";\nimport { TOKEN_PROGRAM_ID } from \"@solana/spl-token\";\nimport BN from \"bn.js\";\nimport { createLogger, getATAAddress } from \"@/common\";\n\nimport { splAccountLayout } from \"./layout\";\nimport { TokenAccount, TokenAccountRaw } from \"./types\";\nimport { sha256 } from \"@noble/hashes/sha256\";\n\nconst logger = createLogger(\"Raydium_Util\");\n\nexport interface ParseTokenAccount {\n owner: PublicKey;\n solAccountResp?: AccountInfo<Buffer> | null;\n tokenAccountResp: RpcResponseAndContext<GetProgramAccountsResponse>;\n}\n\nexport function parseTokenAccountResp({ owner, solAccountResp, tokenAccountResp }: ParseTokenAccount): {\n tokenAccounts: TokenAccount[];\n tokenAccountRawInfos: TokenAccountRaw[];\n} {\n const tokenAccounts: TokenAccount[] = [];\n const tokenAccountRawInfos: TokenAccountRaw[] = [];\n\n for (const { pubkey, account } of tokenAccountResp.value) {\n const accountInfo = splAccountLayout.decode(account.data);\n const { mint, amount } = accountInfo;\n tokenAccounts.push({\n publicKey: pubkey,\n mint,\n amount,\n isAssociated: getATAAddress(owner, mint, account.owner).publicKey.equals(pubkey),\n isNative: false,\n programId: account.owner,\n });\n // todo programId should get from api\n tokenAccountRawInfos.push({ pubkey, accountInfo, programId: account.owner });\n }\n\n if (solAccountResp) {\n tokenAccounts.push({\n mint: PublicKey.default,\n amount: new BN(solAccountResp.lamports),\n isNative: true,\n programId: solAccountResp.owner,\n });\n }\n\n return {\n tokenAccounts,\n tokenAccountRawInfos,\n };\n}\n\nexport function generatePubKey({\n fromPublicKey,\n programId = TOKEN_PROGRAM_ID,\n}: {\n fromPublicKey: PublicKey;\n programId: PublicKey;\n}): { publicKey: PublicKey; seed: string } {\n const seed = Keypair.generate().publicKey.toBase58().slice(0, 32);\n const publicKey = createWithSeed(fromPublicKey, seed, programId);\n return { publicKey, seed };\n}\n\nfunction createWithSeed(fromPublicKey: PublicKey, seed: string, programId: PublicKey): PublicKey {\n const buffer = Buffer.concat([fromPublicKey.toBuffer(), Buffer.from(seed), programId.toBuffer()]);\n const publicKeyBytes = sha256(buffer);\n return new PublicKey(publicKeyBytes);\n}\n","import { PublicKey } from \"@solana/web3.js\";\nimport BN, { isBN } from \"bn.js\";\n\nimport {\n bits,\n blob,\n Blob,\n Layout,\n offset as _offset,\n seq as _seq,\n Structure as _Structure,\n u32 as _u32,\n u8 as _u8,\n UInt,\n union as _union,\n Union as _Union,\n} from \"./buffer-layout\";\n\nexport * from \"./buffer-layout\";\nexport { blob };\n\nexport class BNLayout<P extends string = \"\"> extends Layout<BN, P> {\n blob: Layout<Buffer>;\n signed: boolean;\n\n constructor(span: number, signed: boolean, property?: P) {\n //@ts-expect-error type wrong for super()'s type different from extends, but it desn't matter\n super(span, property);\n this.blob = blob(span);\n this.signed = signed;\n }\n\n /** @override */\n decode(b: Buffer, offset = 0): BN {\n const num = new BN(this.blob.decode(b, offset), 10, \"le\");\n if (this.signed) {\n return num.fromTwos(this.span * 8).clone();\n }\n return num;\n }\n\n /** @override */\n encode(src: BN, b: Buffer, offset = 0): number {\n if (typeof src === \"number\") src = new BN(src); // src will pass a number accidently in union\n if (this.signed) {\n src = src.toTwos(this.span * 8);\n }\n return this.blob.encode(src.toArrayLike(Buffer, \"le\", this.span), b, offset);\n }\n}\n\nexport class WideBits<P extends string = \"\"> extends Layout<Record<string, boolean>, P> {\n _lower: any;\n _upper: any;\n // TODO: unknown\n constructor(property?: P) {\n //@ts-expect-error type wrong for super()'s type different from extends , but it desn't matter\n super(8, property);\n this._lower = bits(_u32(), false);\n this._upper = bits(_u32(), false);\n }\n\n addBoolean(property: string): void {\n if (this._lower.fields.length < 32) {\n this._lower.addBoolean(property);\n } else {\n this._upper.addBoolean(property);\n }\n }\n\n decode(b: Buffer, offset = 0): Record<string, boolean> {\n const lowerDecoded = this._lower.decode(b, offset);\n const upperDecoded = this._upper.decode(b, offset + this._lower.span);\n return { ...lowerDecoded, ...upperDecoded };\n }\n\n encode(src: any /* TEMP */, b: Buffer, offset = 0): any {\n return this._lower.encode(src, b, offset) + this._upper.encode(src, b, offset + this._lower.span);\n }\n}\n\nexport function u8<P extends string = \"\">(property?: P): UInt<number, P> {\n return new UInt(1, property);\n}\n\nexport function u32<P extends string = \"\">(property?: P): UInt<number, P> {\n return new UInt(4, property);\n}\n\nexport function u64<P extends string = \"\">(property?: P): BNLayout<P> {\n return new BNLayout(8, false, property);\n}\n\nexport function u128<P extends string = \"\">(property?: P): BNLayout<P> {\n return new BNLayout(16, false, property);\n}\n\nexport function i8<P extends string = \"\">(property?: P): BNLayout<P> {\n return new BNLayout(1, true, property);\n}\n\nexport function i64<P extends string = \"\">(property?: P): BNLayout<P> {\n return new BNLayout(8, true, property);\n}\n\nexport function i128<P extends string = \"\">(property?: P): BNLayout<P> {\n return new BNLayout(16, true, property);\n}\n\nexport class WrappedLayout<T, U, P extends string = \"\"> extends Layout<U, P> {\n layout: Layout<T>;\n decoder: (data: T) => U;\n encoder: (src: U) => T;\n\n constructor(layout: Layout<T>, decoder: (data: T) => U, encoder: (src: U) => T, property?: P) {\n //@ts-expect-error type wrong for super()'s type different from extends , but it desn't matter\n super(layout.span, property);\n this.layout = layout;\n this.decoder = decoder;\n this.encoder = encoder;\n }\n\n decode(b: Buffer, offset?: number): U {\n return this.decoder(this.layout.decode(b, offset));\n }\n\n encode(src: U, b: Buffer, offset?: number): number {\n return this.layout.encode(this.encoder(src), b, offset);\n }\n\n getSpan(b: Buffer, offset?: number): number {\n return this.layout.getSpan(b, offset);\n }\n}\n\nexport function publicKey<P extends string = \"\">(property?: P): Layout<PublicKey, P> {\n return new WrappedLayout(\n blob(32),\n (b: Buffer) => new PublicKey(b),\n (key: PublicKey) => key.toBuffer(),\n property,\n );\n}\n\nexport class OptionLayout<T, P> extends Layout<T | null, P> {\n layout: Layout<T>;\n discriminator: Layout<number>;\n\n constructor(layout: Layout<T>, property?: P) {\n //@ts-expect-error type wrong for super()'s type different from extends , but it desn't matter\n super(-1, property);\n this.layout = layout;\n this.discriminator = _u8();\n }\n\n encode(src: T | null, b: Buffer, offset = 0): number {\n if (src === null || src === undefined) {\n return this.discriminator.encode(0, b, offset);\n }\n this.discriminator.encode(1, b, offset);\n return this.layout.encode(src, b, offset + 1) + 1;\n }\n\n decode(b: Buffer, offset = 0): T | null {\n const discriminator = this.discriminator.decode(b, offset);\n if (discriminator === 0) {\n return null;\n } else if (discriminator === 1) {\n return this.layout.decode(b, offset + 1);\n }\n throw new Error(\"Invalid option \" + this.property);\n }\n\n getSpan(b: Buffer, offset = 0): number {\n const discriminator = this.discriminator.decode(b, offset);\n if (discriminator === 0) {\n return 1;\n } else if (discriminator === 1) {\n return this.layout.getSpan(b, offset + 1) + 1;\n }\n throw new Error(\"Invalid option \" + this.property);\n }\n}\n\nexport function option<T, P extends string = \"\">(layout: Layout<T>, property?: P): Layout<T | null, P> {\n return new OptionLayout<T, P>(layout, property);\n}\n\nexport function bool<P extends string = \"\">(property?: P): Layout<boolean, P> {\n return new WrappedLayout(_u8(), decodeBool, encodeBool, property);\n}\n\nexport function decodeBool(value: number): boolean {\n if (value === 0) {\n return false;\n } else if (value === 1) {\n return true;\n }\n throw new Error(\"Invalid bool: \" + value);\n}\n\nexport function encodeBool(value: boolean): number {\n return value ? 1 : 0;\n}\n\nexport function vec<T, P extends string = \"\">(elementLayout: Layout<T>, property?: P): Layout<T[], P> {\n const length = _u32(\"length\");\n const layout: Layout<{ values: T[] }> = struct([\n length,\n seq(elementLayout, _offset(length, -length.span), \"values\"),\n ]) as any; // Something I don't know\n return new WrappedLayout(\n layout,\n ({ values }) => values,\n (values) => ({ values }),\n property,\n );\n}\n\nexport function tagged<T, P extends string = \"\">(tag: BN, layout: Layout<T>, property?: P): Layout<T, P> {\n const wrappedLayout: Layout<{ tag: BN; data: T }> = struct([u64(\"tag\"), layout.replicate(\"data\")]) as any; // Something I don't know\n\n function decodeTag({ tag: receivedTag, data }: { tag: BN; data: T }): T {\n if (!receivedTag.eq(tag)) {\n throw new Error(\"Invalid tag, expected: \" + tag.toString(\"hex\") + \", got: \" + receivedTag.toString(\"hex\"));\n }\n return data;\n }\n\n return new WrappedLayout(wrappedLayout, decodeTag, (data) => ({ tag, data }), property);\n}\n\nexport function vecU8<P extends string = \"\">(property?: P): Layout<Buffer, P> {\n const length = _u32(\"length\");\n const layout: Layout<{ data: Buffer }> = struct([length, blob(_offset(length, -length.span), \"data\")]) as any; // Something I don't know\n return new WrappedLayout(\n layout,\n ({ data }) => data,\n (data) => ({ data }),\n property,\n );\n}\n\nexport function str<P extends string = \"\">(property?: P): Layout<string, P> {\n return new WrappedLayout(\n vecU8(),\n (data) => data.toString(\"utf-8\"),\n (s) => Buffer.from(s, \"utf-8\"),\n property,\n );\n}\n\nexport interface EnumLayout<T, P extends string = \"\"> extends Layout<T, P> {\n registry: Record<string, Layout<any>>;\n}\n\nexport function rustEnum<T, P extends string = \"\">(variants: Layout<any>[], property?: P): EnumLayout<T, P> {\n const unionLayout = _union(_u8(), property);\n variants.forEach((variant, index) => unionLayout.addVariant(index, variant, variant.property));\n return unionLayout as any; // ?why use UnionLayout? This must be a fault\n}\n\nexport function array<T, P extends string = \"\">(\n elementLayout: Layout<T>,\n length: number,\n property?: P,\n): Layout<T[], P> {\n const layout = struct([seq(elementLayout, length, \"values\")]) as any as Layout<{ values: T[] }>; // Something I don't know\n return new WrappedLayout(\n layout,\n ({ values }) => values,\n (values) => ({ values }),\n property,\n );\n}\n\nexport class Structure<T, P, D> extends _Structure<T, P, D> {\n /** @override */\n decode(b: Buffer, offset?: number): D {\n return super.decode(b, offset);\n }\n}\n\nexport function struct<T, P extends string = \"\">(\n fields: T,\n property?: P,\n decodePrefixes?: boolean,\n): T extends Layout<infer Value, infer Property>[]\n ? Structure<\n Value,\n P,\n {\n [K in Exclude<Extract<Property, string>, \"\">]: Extract<T[number], Layout<any, K>> extends Layout<infer V, any>\n ? V\n : any;\n }\n >\n : any {\n //@ts-expect-error this type is not quite satisfied the define, but, never no need to worry about.\n return new Structure(fields, property, decodePrefixes);\n}\n\nexport type GetLayoutSchemaFromStructure<T extends Structure<any, any, any>> = T extends Structure<any, any, infer S>\n ? S\n : any;\nexport type GetStructureFromLayoutSchema<S> = Structure<any, any, S>;\n\nexport class Union<Schema> extends _Union<Schema> {\n encodeInstruction(instruction: any): Buffer {\n const instructionMaxSpan = Math.max(...Object.values(this.registry).map((r) => r.span));\n const b = Buffer.alloc(instructionMaxSpan);\n return b.slice(0, this.encode(instruction, b));\n }\n\n decodeInstruction(instruction: any): Partial<Schema> {\n return this.decode(instruction);\n }\n}\nexport function union<UnionSchema extends { [key: string]: any } = any>(\n discr: any,\n defaultLayout?: any,\n property?: string,\n): Union<UnionSchema> {\n return new Union(discr, defaultLayout, property);\n}\n\nclass Zeros extends Blob {\n decode(b: Buffer, offset: number): Buffer {\n const slice = super.decode(b, offset);\n if (!slice.every((v) => v === 0)) {\n throw new Error(\"nonzero padding bytes\");\n }\n return slice;\n }\n}\n\nexport function zeros(length: number): Zeros {\n return new Zeros(length);\n}\n\nexport function seq<T, P extends string = \"\", AnotherP extends string = \"\">(\n elementLayout: Layout<T, P>,\n count: number | BN | Layout<BN | number, P>,\n property?: AnotherP,\n): Layout<T[], AnotherP> {\n let parsedCount: number;\n const superCount =\n typeof count === \"number\"\n ? count\n : isBN(count)\n ? count.toNumber()\n : new Proxy(count as unknown as Layout<number> /* pretend to be Layout<number> */, {\n get(target, property): any {\n if (!parsedCount) {\n // get count in targetLayout. note that count may be BN\n const countProperty = Reflect.get(target, \"count\");\n\n // let targetLayout's property:count be a number\n parsedCount = isBN(countProperty) ? countProperty.toNumber() : countProperty;\n\n // record the count\n Reflect.set(target, \"count\", parsedCount);\n }\n return Reflect.get(target, property);\n },\n set(target, property, value): any {\n if (property === \"count\") {\n parsedCount = value;\n }\n return Reflect.set(target, property, value);\n },\n });\n\n // @ts-expect-error force type\n return _seq(elementLayout, superCount, property);\n}\n","import {\n bits as _bits,\n BitStructure as _BitStructure,\n blob as _blob,\n Blob as _Blob,\n cstr as _cstr,\n f32 as _f32,\n f32be as _f32be,\n f64 as _f64,\n f64be as _f64be,\n greedy as _greedy,\n Layout as _Layout,\n ns64 as _ns64,\n ns64be as _ns64be,\n nu64 as _nu64,\n nu64be as _nu64be,\n offset as _offset,\n s16 as _s16,\n s16be as _s16be,\n s24 as _s24,\n s24be as _s24be,\n s32 as _s32,\n s32be as _s32be,\n s40 as _s40,\n s40be as _s40be,\n s48 as _s48,\n s48be as _s48be,\n s8 as _s8,\n seq as _seq,\n struct as _struct,\n Structure as _Structure,\n u16 as _u16,\n u16be as _u16be,\n u24 as _u24,\n u24be as _u24be,\n u32 as _u32,\n u32be as _u32be,\n u40 as _u40,\n u40be as _u40be,\n u48 as _u48,\n u48be as _u48be,\n u8 as _u8,\n UInt as _UInt,\n union as _union,\n Union as _Union,\n unionLayoutDiscriminator as _unionLayoutDiscriminator,\n utf8 as _utf8,\n} from \"@solana/buffer-layout\";\n\n//#region ------------------- Layout -------------------\nexport interface Layout<T = any, P = \"\"> {\n span: number;\n property?: P;\n decode(b: Buffer, offset?: number): T;\n encode(src: T, b: Buffer, offset?: number): number;\n getSpan(b: Buffer, offset?: number): number;\n replicate<AP extends string>(name: AP): Layout<T, AP>;\n}\nexport interface LayoutConstructor {\n new <T, P>(): Layout<T, P>; // for class extends syntex\n new <T, P>(span?: T, property?: P): Layout<T, P>;\n readonly prototype: Layout;\n}\nexport const Layout = _Layout as unknown as LayoutConstructor;\n//#endregion\n\n//#region ------------------- Structure -------------------\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nexport interface Structure<T = any, P = \"\", DecodeSchema extends { [key: string]: any } = any>\n extends Layout<DecodeSchema, P> {\n span: number;\n decode(b: Buffer, offset?: number): DecodeSchema;\n layoutFor<AP extends string>(property: AP): Layout<DecodeSchema[AP]>;\n offsetOf<AP extends string>(property: AP): number;\n}\ninterface StructureConstructor {\n new <T = any, P = \"\", DecodeSchema extends { [key: string]: any } = any>(): Structure<T, P, DecodeSchema>;\n new <T = any, P = \"\", DecodeSchema extends { [key: string]: any } = any>(\n fields: T,\n property?: P,\n decodePrefixes?: boolean,\n ): Structure<T, P, DecodeSchema>;\n}\nexport const Structure = _Structure as unknown as StructureConstructor;\n//#endregion\n\n//#region ------------------- Union -------------------\nexport interface Union<UnionSchema extends { [key: string]: any } = any> extends Layout {\n registry: object;\n decode(b: Buffer, offset?: number): Partial<UnionSchema>;\n addVariant(\n variant: number,\n layout: Structure<any, any, Partial<UnionSchema>> | Layout<any, keyof UnionSchema>,\n property?: string,\n ): any /* TEMP: code in Layout.js 1809 */;\n}\ninterface UnionConstructor {\n new <UnionSchema extends { [key: string]: any } = any>(): Union<UnionSchema>;\n new <UnionSchema extends { [key: string]: any } = any>(\n discr: Layout<any, any>,\n defaultLayout: Layout<any, any>,\n property?: string,\n ): Union<UnionSchema>;\n}\nexport const Union = _Union as unknown as UnionConstructor;\n//#endregion\n\n//#region ------------------- BitStructure -------------------\nexport type BitStructure<T = unknown /* TEMP */, P = \"\"> = Layout<T, P>;\ninterface BitStructureConstructor {\n new (...params: any[]): BitStructure;\n}\nexport const BitStructure = _BitStructure as BitStructureConstructor;\n//#endregion\n\n//#region ------------------- UInt -------------------\nexport type UInt<T = any, P = \"\"> = Layout<T, P>;\ninterface UIntConstructor {\n new <T, P>(span?: T, property?: P): UInt<T, P>;\n}\nexport const UInt = _UInt as UIntConstructor;\n//#endregion\n\n//#region ------------------- Blob -------------------\nexport type Blob<P extends string = \"\"> = Layout<Buffer, P>;\ninterface BlobConstructor {\n new (...params: ConstructorParameters<LayoutConstructor>): Blob;\n}\nexport const Blob = _Blob as unknown as BlobConstructor;\n//#endregion\n\nexport const greedy = _greedy as <P extends string = \"\">(elementSpan?: number, property?: P) => Layout<number, P>;\nexport const u8 = _u8 as <P extends string = \"\">(property?: P) => Layout<number, P>;\nexport const u16 = _u16 as <P extends string = \"\">(property?: P) => Layout<number, P>;\nexport const u24 = _u24 as <P extends string = \"\">(property?: P) => Layout<number, P>;\nexport const u32 = _u32 as <P extends string = \"\">(property?: P) => Layout<number, P>;\nexport const u40 = _u40 as <P extends string = \"\">(property?: P) => Layout<number, P>;\nexport const u48 = _u48 as <P extends string = \"\">(property?: P) => Layout<number, P>;\nexport const nu64 = _nu64 as <P extends string = \"\">(property?: P) => Layout<number, P>;\nexport const u16be = _u16be as <P extends string = \"\">(property?: P) => Layout<number, P>;\nexport const u24be = _u24be as <P extends string = \"\">(property?: P) => Layout<number, P>;\nexport const u32be = _u32be as <P extends string = \"\">(property?: P) => Layout<number, P>;\nexport const u40be = _u40be as <P extends string = \"\">(property?: P) => Layout<number, P>;\nexport const u48be = _u48be as <P extends string = \"\">(property?: P) => Layout<number, P>;\nexport const nu64be = _nu64be as <P extends string = \"\">(property?: P) => Layout<number, P>;\nexport const s8 = _s8 as <P extends string = \"\">(property?: P) => Layout<number, P>;\nexport const s16 = _s16 as <P extends string = \"\">(property?: P) => Layout<number, P>;\nexport const s24 = _s24 as <P extends string = \"\">(property?: P) => Layout<number, P>;\nexport const s32 = _s32 as <P extends string = \"\">(property?: P) => Layout<number, P>;\nexport const s40 = _s40 as <P extends string = \"\">(property?: P) => Layout<number, P>;\nexport const s48 = _s48 as <P extends string = \"\">(property?: P) => Layout<number, P>;\nexport const ns64 = _ns64 as <P extends string = \"\">(property?: P) => Layout<number, P>;\nexport const s16be = _s16be as <P extends string = \"\">(property?: P) => Layout<number, P>;\nexport const s24be = _s24be as <P extends string = \"\">(property?: P) => Layout<number, P>;\nexport const s32be = _s32be as <P extends string = \"\">(property?: P) => Layout<number, P>;\nexport const s40be = _s40be as <P extends string = \"\">(property?: P) => Layout<number, P>;\nexport const s48be = _s48be as <P extends string = \"\">(property?: P) => Layout<number, P>;\nexport const ns64be = _ns64be as <P extends string = \"\">(property?: P) => Layout<number, P>;\nexport const f32 = _f32 as <P extends string = \"\">(property?: P) => Layout<number, P>;\nexport const f32be = _f32be as <P extends string = \"\">(property?: P) => Layout<number, P>;\nexport const f64 = _f64 as <P extends string = \"\">(property?: P) => Layout<number, P>;\nexport const f64be = _f64be as <P extends string = \"\">(property?: P) => Layout<number, P>;\n\nexport const struct = _struct as <T, P extends string = \"\">(\n fields: T,\n property?: P,\n decodePrefixes?: boolean,\n) => T extends Layout<infer Value, infer Property>[]\n ? Structure<\n Value,\n P,\n {\n [K in Exclude<Extract<Property, string>, \"\">]: Extract<T[number], Layout<any, K>> extends Layout<infer V, any>\n ? V\n : any;\n }\n >\n : any;\n\nexport const seq = _seq as unknown as <T, P>(\n elementLayout: Layout<T, string>,\n count: number | Layout<number, string>,\n property?: P,\n) => Layout<T[]>;\nexport const union = _union as <UnionSchema extends { [key: string]: any } = any>(\n discr: Layout<any, any>,\n defaultLayout?: any,\n property?: string,\n) => Union<UnionSchema>;\nexport const unionLayoutDiscriminator = _unionLayoutDiscriminator as <P extends string = \"\">(\n layout: Layout<any, P>,\n property?: P,\n) => any;\nexport const blob = _blob as unknown as <P extends string = \"\">(\n length: number | Layout<number, P>,\n property?: P,\n) => Blob<P>;\nexport const cstr = _cstr as <P extends string = \"\">(property?: P) => Layout<string, P>;\nexport const utf8 = _utf8 as <P extends string = \"\">(maxSpan: number, property?: P) => Layout<string, P>;\nexport const bits = _bits as unknown as <T, P extends string = \"\">(\n word: Layout<T>,\n msb?: boolean,\n property?: P,\n) => BitStructure<T, P>; // TODO: not quite sure\nexport const offset = _offset as unknown as <T, P extends string = \"\">(\n layout: Layout<T, P>,\n offset?: number,\n property?: P,\n) => Layout<T, P>;\n\nexport type GetStructureSchema<T extends Structure> = T extends Structure<any, any, infer S> ? S : unknown;\n","import { publicKey, struct, u32, u64, u8 } from \"@/marshmallow\";\n\nexport const splAccountLayout = struct([\n publicKey(\"mint\"),\n publicKey(\"owner\"),\n u64(\"amount\"),\n u32(\"delegateOption\"),\n publicKey(\"delegate\"),\n u8(\"state\"),\n u32(\"isNativeOption\"),\n u64(\"isNative\"),\n u64(\"delegatedAmount\"),\n u32(\"closeAuthorityOption\"),\n publicKey(\"closeAuthority\"),\n]);\n",null,null,null,null],"mappings":"8kCAAA,wDAAA,MAKO,6BACP,GAA6E,2BCN7E,OAAyB,kBACzB,GAAkB,oBAClB,GAAgB,+BAChB,WAAM,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AI,EAAqB,CACvB,GAAM,GAAU,KAAM,MAAK,MAAM,WAAW,eAAe,CAAG,EAC9D,GAAI,IAAY,KACd,EAAa,KAAK,CAAa,UAE/B,IAAQ,MAAM,OAAO,kBAAgB,GACrC,gBAAc,OAAO,EAAQ,IAAI,EAAE,KAAK,OAAO,CAAI,GACnD,gBAAc,OAAO,EAAQ,IAAI,EAAE,MAAM,OAAO,KAAK,MAAM,WAAW,GAItE,KAAM,OAAM,mCAAmC,EAAK,SAAS,WAAW,EAAI,SAAS,GAAG,CAE5F,KACE,GAAa,KAAK,CAAa,EAGjC,MAAO,CACL,aAAc,EACd,eACA,iBAAkB,CAAC,EAAgB,SAAS,CAC9C,CACF,CAEA,MAAO,CAAE,cAAa,CACxB,MAEa,qBAAoB,EAMwC,CACvE,GAAM,CAAE,OAAM,YAAY,mBAAkB,SAAQ,gBAAe,sBAAuB,EACtF,EACE,EAAY,KAAK,gBAAgB,EAEvC,GAAI,EAAK,OAAO,GAAI,cAAU,EAAQ,CAAC,GAAK,EAAe,CAEzD,GAAyD,QAAM,MAAK,mBAAmB,CACrF,KAAM,KACN,OAAQ,GAAU,EAClB,OACA,sBAAuB,GACvB,WACF,CAAC,EANO,cAAc,GAAmC,EAAjB,KAAiB,EAAjB,CAAhC,iBAOR,EAAe,EACf,EAAU,eAAe,CAAY,CACvC,SACE,EAAe,KAAM,MAAK,uBAAuB,CAC/C,OACA,eAAgB,GAChB,WACF,CAAC,EACG,CAAC,GAAgB,EAAoB,CACvC,GAAyD,QAAM,MAAK,MAAM,QAAQ,mBAAmB,CACnG,KAAM,KACN,OAAQ,EACR,OACA,sBAAuB,GACvB,WACF,CAAC,EANO,cAAc,GAAmC,EAAjB,KAAiB,EAAjB,CAAhC,iBAOR,EAAe,EACf,EAAU,eAAe,CAAY,CACvC,CAGF,MAAO,IAAE,gBAAiB,EAAU,UACtC,CACF","names":[]}
1
+ {"version":3,"sources":["../../../src/raydium/account/account.ts","../../../src/common/logger.ts","../../../src/common/utility.ts","../../../src/module/amount.ts","../../../src/common/bignumber.ts","../../../node_modules/decimal.js/decimal.mjs","../../../src/module/token.ts","../../../src/common/pubKey.ts","../../../src/raydium/token/constant.ts","../../../src/module/fraction.ts","../../../src/module/formatter.ts","../../../src/module/price.ts","../../../src/module/currency.ts","../../../src/module/percent.ts","../../../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/raydium/moduleBase.ts","../../../src/raydium/account/instruction.ts","../../../src/raydium/account/util.ts","../../../src/marshmallow/index.ts","../../../src/marshmallow/buffer-layout.ts","../../../src/raydium/account/layout.ts","../../../node_modules/@noble/hashes/src/_assert.ts","../../../node_modules/@noble/hashes/src/utils.ts","../../../node_modules/@noble/hashes/src/_md.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\";\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\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 async fetchWalletTokenAccounts(config?: { forceUpdate?: boolean; commitment?: Commitment }): Promise<{\n tokenAccounts: TokenAccount[];\n tokenAccountRawInfos: TokenAccountRaw[];\n }> {\n if (this._clientOwnedToken || (!config?.forceUpdate && this._tokenAccounts.length)) {\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._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) => (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 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 {\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(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 }): 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\";\nimport dayjs from \"dayjs\";\nimport utc from \"dayjs/plugin/utc\";\ndayjs.extend(utc);\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 dayjs().utc().format(\"YYYY/MM/DD HH:mm:ss UTC\");\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 { PublicKey } from \"@solana/web3.js\";\nimport BN from \"bn.js\";\n\nimport { Fraction, Percent, Price, Token, TokenAmount } from \"../module\";\nimport { ReplaceType } from \"../raydium/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 // @ts-expect-error no need type for inner code\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;\n}\n","import _Big from \"big.js\";\nimport BN from \"bn.js\";\n\nimport { BigNumberish, BN_TEN, parseBigNumberish, Rounding } from \"../common/bignumber\";\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(\"Raydium_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 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 \"../raydium/token/type\";\nimport { ReplaceType } from \"../raydium/type\";\nimport { createLogger } from \"./logger\";\nimport { mul } from \"./fractionUtil\";\nimport { notInnerObject } from \"./utility\";\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;\nexport type Numberish = number | string | bigint | Fraction | BN;\n\nconst MAX_SAFE = 0x1fffffffffffff;\n\nexport function parseBigNumberish(value: BigNumberish): BN {\n const logger = createLogger(\"Raydium_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\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}\n\nexport function recursivelyDecimalToFraction<T>(info: T): ReplaceType<T, Decimal, Fraction> {\n // @ts-expect-error no need type for inner code\n return isDecimal(info)\n ? decimalToFraction(info as any)\n : Array.isArray(info)\n ? info.map((k) => recursivelyDecimalToFraction(k))\n : notInnerObject(info)\n ? Object.fromEntries(Object.entries(info as any).map(([k, v]) => [k, recursivelyDecimalToFraction(v)]))\n : info;\n}\n","/*\r\n * decimal.js v10.3.1\r\n * An arbitrary-precision Decimal type for JavaScript.\r\n * https://github.com/MikeMcl/decimal.js\r\n * Copyright (c) 2021 Michael Mclaughlin <M8ch88l@gmail.com>\r\n * MIT Licence\r\n */\r\n\r\n\r\n// ----------------------------------- EDITABLE DEFAULTS ------------------------------------ //\r\n\r\n\r\n // The maximum exponent magnitude.\r\n // The limit on the value of `toExpNeg`, `toExpPos`, `minE` and `maxE`.\r\nvar EXP_LIMIT = 9e15, // 0 to 9e15\r\n\r\n // The limit on the value of `precision`, and on the value of the first argument to\r\n // `toDecimalPlaces`, `toExponential`, `toFixed`, `toPrecision` and `toSignificantDigits`.\r\n MAX_DIGITS = 1e9, // 0 to 1e9\r\n\r\n // Base conversion alphabet.\r\n NUMERALS = '0123456789abcdef',\r\n\r\n // The natural logarithm of 10 (1025 digits).\r\n LN10 = '2.3025850929940456840179914546843642076011014886287729760333279009675726096773524802359972050895982983419677840422862486334095254650828067566662873690987816894829072083255546808437998948262331985283935053089653777326288461633662222876982198867465436674744042432743651550489343149393914796194044002221051017141748003688084012647080685567743216228355220114804663715659121373450747856947683463616792101806445070648000277502684916746550586856935673420670581136429224554405758925724208241314695689016758940256776311356919292033376587141660230105703089634572075440370847469940168269282808481184289314848524948644871927809676271275775397027668605952496716674183485704422507197965004714951050492214776567636938662976979522110718264549734772662425709429322582798502585509785265383207606726317164309505995087807523710333101197857547331541421808427543863591778117054309827482385045648019095610299291824318237525357709750539565187697510374970888692180205189339507238539205144634197265287286965110862571492198849978748873771345686209167058',\r\n\r\n // Pi (1025 digits).\r\n PI = '3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679821480865132823066470938446095505822317253594081284811174502841027019385211055596446229489549303819644288109756659334461284756482337867831652712019091456485669234603486104543266482133936072602491412737245870066063155881748815209209628292540917153643678925903600113305305488204665213841469519415116094330572703657595919530921861173819326117931051185480744623799627495673518857527248912279381830119491298336733624406566430860213949463952247371907021798609437027705392171762931767523846748184676694051320005681271452635608277857713427577896091736371787214684409012249534301465495853710507922796892589235420199561121290219608640344181598136297747713099605187072113499999983729780499510597317328160963185950244594553469083026425223082533446850352619311881710100031378387528865875332083814206171776691473035982534904287554687311595628638823537875937519577818577805321712268066130019278766111959092164201989380952572010654858632789',\r\n\r\n\r\n // The initial configuration properties of the Decimal constructor.\r\n DEFAULTS = {\r\n\r\n // These values must be integers within the stated ranges (inclusive).\r\n // Most of these values can be changed at run-time using the `Decimal.config` method.\r\n\r\n // The maximum number of significant digits of the result of a calculation or base conversion.\r\n // E.g. `Decimal.config({ precision: 20 });`\r\n precision: 20, // 1 to MAX_DIGITS\r\n\r\n // The rounding mode used when rounding to `precision`.\r\n //\r\n // ROUND_UP 0 Away from zero.\r\n // ROUND_DOWN 1 Towards zero.\r\n // ROUND_CEIL 2 Towards +Infinity.\r\n // ROUND_FLOOR 3 Towards -Infinity.\r\n // ROUND_HALF_UP 4 Towards nearest neighbour. If equidistant, up.\r\n // ROUND_HALF_DOWN 5 Towards nearest neighbour. If equidistant, down.\r\n // ROUND_HALF_EVEN 6 Towards nearest neighbour. If equidistant, towards even neighbour.\r\n // ROUND_HALF_CEIL 7 Towards nearest neighbour. If equidistant, towards +Infinity.\r\n // ROUND_HALF_FLOOR 8 Towards nearest neighbour. If equidistant, towards -Infinity.\r\n //\r\n // E.g.\r\n // `Decimal.rounding = 4;`\r\n // `Decimal.rounding = Decimal.ROUND_HALF_UP;`\r\n rounding: 4, // 0 to 8\r\n\r\n // The modulo mode used when calculating the modulus: a mod n.\r\n // The quotient (q = a / n) is calculated according to the corresponding rounding mode.\r\n // The remainder (r) is calculated as: r = a - n * q.\r\n //\r\n // UP 0 The remainder is positive if the dividend is negative, else is negative.\r\n // DOWN 1 The remainder has the same sign as the dividend (JavaScript %).\r\n // FLOOR 3 The remainder has the same sign as the divisor (Python %).\r\n // HALF_EVEN 6 The IEEE 754 remainder function.\r\n // EUCLID 9 Euclidian division. q = sign(n) * floor(a / abs(n)). Always positive.\r\n //\r\n // Truncated division (1), floored division (3), the IEEE 754 remainder (6), and Euclidian\r\n // division (9) are commonly used for the modulus operation. The other rounding modes can also\r\n // be used, but they may not give useful results.\r\n modulo: 1, // 0 to 9\r\n\r\n // The exponent value at and beneath which `toString` returns exponential notation.\r\n // JavaScript numbers: -7\r\n toExpNeg: -7, // 0 to -EXP_LIMIT\r\n\r\n // The exponent value at and above which `toString` returns exponential notation.\r\n // JavaScript numbers: 21\r\n toExpPos: 21, // 0 to EXP_LIMIT\r\n\r\n // The minimum exponent value, beneath which underflow to zero occurs.\r\n // JavaScript numbers: -324 (5e-324)\r\n minE: -EXP_LIMIT, // -1 to -EXP_LIMIT\r\n\r\n // The maximum exponent value, above which overflow to Infinity occurs.\r\n // JavaScript numbers: 308 (1.7976931348623157e+308)\r\n maxE: EXP_LIMIT, // 1 to EXP_LIMIT\r\n\r\n // Whether to use cryptographically-secure random number generation, if available.\r\n crypto: false // true/false\r\n },\r\n\r\n\r\n// ----------------------------------- END OF EDITABLE DEFAULTS ------------------------------- //\r\n\r\n\r\n inexact, quadrant,\r\n external = true,\r\n\r\n decimalError = '[DecimalError] ',\r\n invalidArgument = decimalError + 'Invalid argument: ',\r\n precisionLimitExceeded = decimalError + 'Precision limit exceeded',\r\n cryptoUnavailable = decimalError + 'crypto unavailable',\r\n tag = '[object Decimal]',\r\n\r\n mathfloor = Math.floor,\r\n mathpow = Math.pow,\r\n\r\n isBinary = /^0b([01]+(\\.[01]*)?|\\.[01]+)(p[+-]?\\d+)?$/i,\r\n isHex = /^0x([0-9a-f]+(\\.[0-9a-f]*)?|\\.[0-9a-f]+)(p[+-]?\\d+)?$/i,\r\n isOctal = /^0o([0-7]+(\\.[0-7]*)?|\\.[0-7]+)(p[+-]?\\d+)?$/i,\r\n isDecimal = /^(\\d+(\\.\\d*)?|\\.\\d+)(e[+-]?\\d+)?$/i,\r\n\r\n BASE = 1e7,\r\n LOG_BASE = 7,\r\n MAX_SAFE_INTEGER = 9007199254740991,\r\n\r\n LN10_PRECISION = LN10.length - 1,\r\n PI_PRECISION = PI.length - 1,\r\n\r\n // Decimal.prototype object\r\n P = { toStringTag: tag };\r\n\r\n\r\n// Decimal prototype methods\r\n\r\n\r\n/*\r\n * absoluteValue abs\r\n * ceil\r\n * clampedTo clamp\r\n * comparedTo cmp\r\n * cosine cos\r\n * cubeRoot cbrt\r\n * decimalPlaces dp\r\n * dividedBy div\r\n * dividedToIntegerBy divToInt\r\n * equals eq\r\n * floor\r\n * greaterThan gt\r\n * greaterThanOrEqualTo gte\r\n * hyperbolicCosine cosh\r\n * hyperbolicSine sinh\r\n * hyperbolicTangent tanh\r\n * inverseCosine acos\r\n * inverseHyperbolicCosine acosh\r\n * inverseHyperbolicSine asinh\r\n * inverseHyperbolicTangent atanh\r\n * inverseSine asin\r\n * inverseTangent atan\r\n * isFinite\r\n * isInteger isInt\r\n * isNaN\r\n * isNegative isNeg\r\n * isPositive isPos\r\n * isZero\r\n * lessThan lt\r\n * lessThanOrEqualTo lte\r\n * logarithm log\r\n * [maximum] [max]\r\n * [minimum] [min]\r\n * minus sub\r\n * modulo mod\r\n * naturalExponential exp\r\n * naturalLogarithm ln\r\n * negated neg\r\n * plus add\r\n * precision sd\r\n * round\r\n * sine sin\r\n * squareRoot sqrt\r\n * tangent tan\r\n * times mul\r\n * toBinary\r\n * toDecimalPlaces toDP\r\n * toExponential\r\n * toFixed\r\n * toFraction\r\n * toHexadecimal toHex\r\n * toNearest\r\n * toNumber\r\n * toOctal\r\n * toPower pow\r\n * toPrecision\r\n * toSignificantDigits toSD\r\n * toString\r\n * truncated trunc\r\n * valueOf toJSON\r\n */\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is the absolute value of this Decimal.\r\n *\r\n */\r\nP.absoluteValue = P.abs = function () {\r\n var x = new this.constructor(this);\r\n if (x.s < 0) x.s = 1;\r\n return finalise(x);\r\n};\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is the value of this Decimal rounded to a whole number in the\r\n * direction of positive Infinity.\r\n *\r\n */\r\nP.ceil = function () {\r\n return finalise(new this.constructor(this), this.e + 1, 2);\r\n};\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is the value of this Decimal clamped to the range\r\n * delineated by `min` and `max`.\r\n *\r\n * min {number|string|Decimal}\r\n * max {number|string|Decimal}\r\n *\r\n */\r\nP.clampedTo = P.clamp = function (min, max) {\r\n var k,\r\n x = this,\r\n Ctor = x.constructor;\r\n min = new Ctor(min);\r\n max = new Ctor(max);\r\n if (!min.s || !max.s) return new Ctor(NaN);\r\n if (min.gt(max)) throw Error(invalidArgument + max);\r\n k = x.cmp(min);\r\n return k < 0 ? min : x.cmp(max) > 0 ? max : new Ctor(x);\r\n};\r\n\r\n\r\n/*\r\n * Return\r\n * 1 if the value of this Decimal is greater than the value of `y`,\r\n * -1 if the value of this Decimal is less than the value of `y`,\r\n * 0 if they have the same value,\r\n * NaN if the value of either Decimal is NaN.\r\n *\r\n */\r\nP.comparedTo = P.cmp = function (y) {\r\n var i, j, xdL, ydL,\r\n x = this,\r\n xd = x.d,\r\n yd = (y = new x.constructor(y)).d,\r\n xs = x.s,\r\n ys = y.s;\r\n\r\n // Either NaN or ±Infinity?\r\n if (!xd || !yd) {\r\n return !xs || !ys ? NaN : xs !== ys ? xs : xd === yd ? 0 : !xd ^ xs < 0 ? 1 : -1;\r\n }\r\n\r\n // Either zero?\r\n if (!xd[0] || !yd[0]) return xd[0] ? xs : yd[0] ? -ys : 0;\r\n\r\n // Signs differ?\r\n if (xs !== ys) return xs;\r\n\r\n // Compare exponents.\r\n if (x.e !== y.e) return x.e > y.e ^ xs < 0 ? 1 : -1;\r\n\r\n xdL = xd.length;\r\n ydL = yd.length;\r\n\r\n // Compare digit by digit.\r\n for (i = 0, j = xdL < ydL ? xdL : ydL; i < j; ++i) {\r\n if (xd[i] !== yd[i]) return xd[i] > yd[i] ^ xs < 0 ? 1 : -1;\r\n }\r\n\r\n // Compare lengths.\r\n return xdL === ydL ? 0 : xdL > ydL ^ xs < 0 ? 1 : -1;\r\n};\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is the cosine of the value in radians of this Decimal.\r\n *\r\n * Domain: [-Infinity, Infinity]\r\n * Range: [-1, 1]\r\n *\r\n * cos(0) = 1\r\n * cos(-0) = 1\r\n * cos(Infinity) = NaN\r\n * cos(-Infinity) = NaN\r\n * cos(NaN) = NaN\r\n *\r\n */\r\nP.cosine = P.cos = function () {\r\n var pr, rm,\r\n x = this,\r\n Ctor = x.constructor;\r\n\r\n if (!x.d) return new Ctor(NaN);\r\n\r\n // cos(0) = cos(-0) = 1\r\n if (!x.d[0]) return new Ctor(1);\r\n\r\n pr = Ctor.precision;\r\n rm = Ctor.rounding;\r\n Ctor.precision = pr + Math.max(x.e, x.sd()) + LOG_BASE;\r\n Ctor.rounding = 1;\r\n\r\n x = cosine(Ctor, toLessThanHalfPi(Ctor, x));\r\n\r\n Ctor.precision = pr;\r\n Ctor.rounding = rm;\r\n\r\n return finalise(quadrant == 2 || quadrant == 3 ? x.neg() : x, pr, rm, true);\r\n};\r\n\r\n\r\n/*\r\n *\r\n * Return a new Decimal whose value is the cube root of the value of this Decimal, rounded to\r\n * `precision` significant digits using rounding mode `rounding`.\r\n *\r\n * cbrt(0) = 0\r\n * cbrt(-0) = -0\r\n * cbrt(1) = 1\r\n * cbrt(-1) = -1\r\n * cbrt(N) = N\r\n * cbrt(-I) = -I\r\n * cbrt(I) = I\r\n *\r\n * Math.cbrt(x) = (x < 0 ? -Math.pow(-x, 1/3) : Math.pow(x, 1/3))\r\n *\r\n */\r\nP.cubeRoot = P.cbrt = function () {\r\n var e, m, n, r, rep, s, sd, t, t3, t3plusx,\r\n x = this,\r\n Ctor = x.constructor;\r\n\r\n if (!x.isFinite() || x.isZero()) return new Ctor(x);\r\n external = false;\r\n\r\n // Initial estimate.\r\n s = x.s * mathpow(x.s * x, 1 / 3);\r\n\r\n // Math.cbrt underflow/overflow?\r\n // Pass x to Math.pow as integer, then adjust the exponent of the result.\r\n if (!s || Math.abs(s) == 1 / 0) {\r\n n = digitsToString(x.d);\r\n e = x.e;\r\n\r\n // Adjust n exponent so it is a multiple of 3 away from x exponent.\r\n if (s = (e - n.length + 1) % 3) n += (s == 1 || s == -2 ? '0' : '00');\r\n s = mathpow(n, 1 / 3);\r\n\r\n // Rarely, e may be one less than the result exponent value.\r\n e = mathfloor((e + 1) / 3) - (e % 3 == (e < 0 ? -1 : 2));\r\n\r\n if (s == 1 / 0) {\r\n n = '5e' + e;\r\n } else {\r\n n = s.toExponential();\r\n n = n.slice(0, n.indexOf('e') + 1) + e;\r\n }\r\n\r\n r = new Ctor(n);\r\n r.s = x.s;\r\n } else {\r\n r = new Ctor(s.toString());\r\n }\r\n\r\n sd = (e = Ctor.precision) + 3;\r\n\r\n // Halley's method.\r\n // TODO? Compare Newton's method.\r\n for (;;) {\r\n t = r;\r\n t3 = t.times(t).times(t);\r\n t3plusx = t3.plus(x);\r\n r = divide(t3plusx.plus(x).times(t), t3plusx.plus(t3), sd + 2, 1);\r\n\r\n // TODO? Replace with for-loop and checkRoundingDigits.\r\n if (digitsToString(t.d).slice(0, sd) === (n = digitsToString(r.d)).slice(0, sd)) {\r\n n = n.slice(sd - 3, sd + 1);\r\n\r\n // The 4th rounding digit may be in error by -1 so if the 4 rounding digits are 9999 or 4999\r\n // , i.e. approaching a rounding boundary, continue the iteration.\r\n if (n == '9999' || !rep && n == '4999') {\r\n\r\n // On the first iteration only, check to see if rounding up gives the exact result as the\r\n // nines may infinitely repeat.\r\n if (!rep) {\r\n finalise(t, e + 1, 0);\r\n\r\n if (t.times(t).times(t).eq(x)) {\r\n r = t;\r\n break;\r\n }\r\n }\r\n\r\n sd += 4;\r\n rep = 1;\r\n } else {\r\n\r\n // If the rounding digits are null, 0{0,4} or 50{0,3}, check for an exact result.\r\n // If not, then there are further digits and m will be truthy.\r\n if (!+n || !+n.slice(1) && n.charAt(0) == '5') {\r\n\r\n // Truncate to the first rounding digit.\r\n finalise(r, e + 1, 1);\r\n m = !r.times(r).times(r).eq(x);\r\n }\r\n\r\n break;\r\n }\r\n }\r\n }\r\n\r\n external = true;\r\n\r\n return finalise(r, e, Ctor.rounding, m);\r\n};\r\n\r\n\r\n/*\r\n * Return the number of decimal places of the value of this Decimal.\r\n *\r\n */\r\nP.decimalPlaces = P.dp = function () {\r\n var w,\r\n d = this.d,\r\n n = NaN;\r\n\r\n if (d) {\r\n w = d.length - 1;\r\n n = (w - mathfloor(this.e / LOG_BASE)) * LOG_BASE;\r\n\r\n // Subtract the number of trailing zeros of the last word.\r\n w = d[w];\r\n if (w) for (; w % 10 == 0; w /= 10) n--;\r\n if (n < 0) n = 0;\r\n }\r\n\r\n return n;\r\n};\r\n\r\n\r\n/*\r\n * n / 0 = I\r\n * n / N = N\r\n * n / I = 0\r\n * 0 / n = 0\r\n * 0 / 0 = N\r\n * 0 / N = N\r\n * 0 / I = 0\r\n * N / n = N\r\n * N / 0 = N\r\n * N / N = N\r\n * N / I = N\r\n * I / n = I\r\n * I / 0 = I\r\n * I / N = N\r\n * I / I = N\r\n *\r\n * Return a new Decimal whose value is the value of this Decimal divided by `y`, rounded to\r\n * `precision` significant digits using rounding mode `rounding`.\r\n *\r\n */\r\nP.dividedBy = P.div = function (y) {\r\n return divide(this, new this.constructor(y));\r\n};\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is the integer part of dividing the value of this Decimal\r\n * by the value of `y`, rounded to `precision` significant digits using rounding mode `rounding`.\r\n *\r\n */\r\nP.dividedToIntegerBy = P.divToInt = function (y) {\r\n var x = this,\r\n Ctor = x.constructor;\r\n return finalise(divide(x, new Ctor(y), 0, 1, 1), Ctor.precision, Ctor.rounding);\r\n};\r\n\r\n\r\n/*\r\n * Return true if the value of this Decimal is equal to the value of `y`, otherwise return false.\r\n *\r\n */\r\nP.equals = P.eq = function (y) {\r\n return this.cmp(y) === 0;\r\n};\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is the value of this Decimal rounded to a whole number in the\r\n * direction of negative Infinity.\r\n *\r\n */\r\nP.floor = function () {\r\n return finalise(new this.constructor(this), this.e + 1, 3);\r\n};\r\n\r\n\r\n/*\r\n * Return true if the value of this Decimal is greater than the value of `y`, otherwise return\r\n * false.\r\n *\r\n */\r\nP.greaterThan = P.gt = function (y) {\r\n return this.cmp(y) > 0;\r\n};\r\n\r\n\r\n/*\r\n * Return true if the value of this Decimal is greater than or equal to the value of `y`,\r\n * otherwise return false.\r\n *\r\n */\r\nP.greaterThanOrEqualTo = P.gte = function (y) {\r\n var k = this.cmp(y);\r\n return k == 1 || k === 0;\r\n};\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is the hyperbolic cosine of the value in radians of this\r\n * Decimal.\r\n *\r\n * Domain: [-Infinity, Infinity]\r\n * Range: [1, Infinity]\r\n *\r\n * cosh(x) = 1 + x^2/2! + x^4/4! + x^6/6! + ...\r\n *\r\n * cosh(0) = 1\r\n * cosh(-0) = 1\r\n * cosh(Infinity) = Infinity\r\n * cosh(-Infinity) = Infinity\r\n * cosh(NaN) = NaN\r\n *\r\n * x time taken (ms) result\r\n * 1000 9 9.8503555700852349694e+433\r\n * 10000 25 4.4034091128314607936e+4342\r\n * 100000 171 1.4033316802130615897e+43429\r\n * 1000000 3817 1.5166076984010437725e+434294\r\n * 10000000 abandoned after 2 minute wait\r\n *\r\n * TODO? Compare performance of cosh(x) = 0.5 * (exp(x) + exp(-x))\r\n *\r\n */\r\nP.hyperbolicCosine = P.cosh = function () {\r\n var k, n, pr, rm, len,\r\n x = this,\r\n Ctor = x.constructor,\r\n one = new Ctor(1);\r\n\r\n if (!x.isFinite()) return new Ctor(x.s ? 1 / 0 : NaN);\r\n if (x.isZero()) return one;\r\n\r\n pr = Ctor.precision;\r\n rm = Ctor.rounding;\r\n Ctor.precision = pr + Math.max(x.e, x.sd()) + 4;\r\n Ctor.rounding = 1;\r\n len = x.d.length;\r\n\r\n // Argument reduction: cos(4x) = 1 - 8cos^2(x) + 8cos^4(x) + 1\r\n // i.e. cos(x) = 1 - cos^2(x/4)(8 - 8cos^2(x/4))\r\n\r\n // Estimate the optimum number of times to use the argument reduction.\r\n // TODO? Estimation reused from cosine() and may not be optimal here.\r\n if (len < 32) {\r\n k = Math.ceil(len / 3);\r\n n = (1 / tinyPow(4, k)).toString();\r\n } else {\r\n k = 16;\r\n n = '2.3283064365386962890625e-10';\r\n }\r\n\r\n x = taylorSeries(Ctor, 1, x.times(n), new Ctor(1), true);\r\n\r\n // Reverse argument reduction\r\n var cosh2_x,\r\n i = k,\r\n d8 = new Ctor(8);\r\n for (; i--;) {\r\n cosh2_x = x.times(x);\r\n x = one.minus(cosh2_x.times(d8.minus(cosh2_x.times(d8))));\r\n }\r\n\r\n return finalise(x, Ctor.precision = pr, Ctor.rounding = rm, true);\r\n};\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is the hyperbolic sine of the value in radians of this\r\n * Decimal.\r\n *\r\n * Domain: [-Infinity, Infinity]\r\n * Range: [-Infinity, Infinity]\r\n *\r\n * sinh(x) = x + x^3/3! + x^5/5! + x^7/7! + ...\r\n *\r\n * sinh(0) = 0\r\n * sinh(-0) = -0\r\n * sinh(Infinity) = Infinity\r\n * sinh(-Infinity) = -Infinity\r\n * sinh(NaN) = NaN\r\n *\r\n * x time taken (ms)\r\n * 10 2 ms\r\n * 100 5 ms\r\n * 1000 14 ms\r\n * 10000 82 ms\r\n * 100000 886 ms 1.4033316802130615897e+43429\r\n * 200000 2613 ms\r\n * 300000 5407 ms\r\n * 400000 8824 ms\r\n * 500000 13026 ms 8.7080643612718084129e+217146\r\n * 1000000 48543 ms\r\n *\r\n * TODO? Compare performance of sinh(x) = 0.5 * (exp(x) - exp(-x))\r\n *\r\n */\r\nP.hyperbolicSine = P.sinh = function () {\r\n var k, pr, rm, len,\r\n x = this,\r\n Ctor = x.constructor;\r\n\r\n if (!x.isFinite() || x.isZero()) return new Ctor(x);\r\n\r\n pr = Ctor.precision;\r\n rm = Ctor.rounding;\r\n Ctor.precision = pr + Math.max(x.e, x.sd()) + 4;\r\n Ctor.rounding = 1;\r\n len = x.d.length;\r\n\r\n if (len < 3) {\r\n x = taylorSeries(Ctor, 2, x, x, true);\r\n } else {\r\n\r\n // Alternative argument reduction: sinh(3x) = sinh(x)(3 + 4sinh^2(x))\r\n // i.e. sinh(x) = sinh(x/3)(3 + 4sinh^2(x/3))\r\n // 3 multiplications and 1 addition\r\n\r\n // Argument reduction: sinh(5x) = sinh(x)(5 + sinh^2(x)(20 + 16sinh^2(x)))\r\n // i.e. sinh(x) = sinh(x/5)(5 + sinh^2(x/5)(20 + 16sinh^2(x/5)))\r\n // 4 multiplications and 2 additions\r\n\r\n // Estimate the optimum number of times to use the argument reduction.\r\n k = 1.4 * Math.sqrt(len);\r\n k = k > 16 ? 16 : k | 0;\r\n\r\n x = x.times(1 / tinyPow(5, k));\r\n x = taylorSeries(Ctor, 2, x, x, true);\r\n\r\n // Reverse argument reduction\r\n var sinh2_x,\r\n d5 = new Ctor(5),\r\n d16 = new Ctor(16),\r\n d20 = new Ctor(20);\r\n for (; k--;) {\r\n sinh2_x = x.times(x);\r\n x = x.times(d5.plus(sinh2_x.times(d16.times(sinh2_x).plus(d20))));\r\n }\r\n }\r\n\r\n Ctor.precision = pr;\r\n Ctor.rounding = rm;\r\n\r\n return finalise(x, pr, rm, true);\r\n};\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is the hyperbolic tangent of the value in radians of this\r\n * Decimal.\r\n *\r\n * Domain: [-Infinity, Infinity]\r\n * Range: [-1, 1]\r\n *\r\n * tanh(x) = sinh(x) / cosh(x)\r\n *\r\n * tanh(0) = 0\r\n * tanh(-0) = -0\r\n * tanh(Infinity) = 1\r\n * tanh(-Infinity) = -1\r\n * tanh(NaN) = NaN\r\n *\r\n */\r\nP.hyperbolicTangent = P.tanh = function () {\r\n var pr, rm,\r\n x = this,\r\n Ctor = x.constructor;\r\n\r\n if (!x.isFinite()) return new Ctor(x.s);\r\n if (x.isZero()) return new Ctor(x);\r\n\r\n pr = Ctor.precision;\r\n rm = Ctor.rounding;\r\n Ctor.precision = pr + 7;\r\n Ctor.rounding = 1;\r\n\r\n return divide(x.sinh(), x.cosh(), Ctor.precision = pr, Ctor.rounding = rm);\r\n};\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is the arccosine (inverse cosine) in radians of the value of\r\n * this Decimal.\r\n *\r\n * Domain: [-1, 1]\r\n * Range: [0, pi]\r\n *\r\n * acos(x) = pi/2 - asin(x)\r\n *\r\n * acos(0) = pi/2\r\n * acos(-0) = pi/2\r\n * acos(1) = 0\r\n * acos(-1) = pi\r\n * acos(1/2) = pi/3\r\n * acos(-1/2) = 2*pi/3\r\n * acos(|x| > 1) = NaN\r\n * acos(NaN) = NaN\r\n *\r\n */\r\nP.inverseCosine = P.acos = function () {\r\n var halfPi,\r\n x = this,\r\n Ctor = x.constructor,\r\n k = x.abs().cmp(1),\r\n pr = Ctor.precision,\r\n rm = Ctor.rounding;\r\n\r\n if (k !== -1) {\r\n return k === 0\r\n // |x| is 1\r\n ? x.isNeg() ? getPi(Ctor, pr, rm) : new Ctor(0)\r\n // |x| > 1 or x is NaN\r\n : new Ctor(NaN);\r\n }\r\n\r\n if (x.isZero()) return getPi(Ctor, pr + 4, rm).times(0.5);\r\n\r\n // TODO? Special case acos(0.5) = pi/3 and acos(-0.5) = 2*pi/3\r\n\r\n Ctor.precision = pr + 6;\r\n Ctor.rounding = 1;\r\n\r\n x = x.asin();\r\n halfPi = getPi(Ctor, pr + 4, rm).times(0.5);\r\n\r\n Ctor.precision = pr;\r\n Ctor.rounding = rm;\r\n\r\n return halfPi.minus(x);\r\n};\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is the inverse of the hyperbolic cosine in radians of the\r\n * value of this Decimal.\r\n *\r\n * Domain: [1, Infinity]\r\n * Range: [0, Infinity]\r\n *\r\n * acosh(x) = ln(x + sqrt(x^2 - 1))\r\n *\r\n * acosh(x < 1) = NaN\r\n * acosh(NaN) = NaN\r\n * acosh(Infinity) = Infinity\r\n * acosh(-Infinity) = NaN\r\n * acosh(0) = NaN\r\n * acosh(-0) = NaN\r\n * acosh(1) = 0\r\n * acosh(-1) = NaN\r\n *\r\n */\r\nP.inverseHyperbolicCosine = P.acosh = function () {\r\n var pr, rm,\r\n x = this,\r\n Ctor = x.constructor;\r\n\r\n if (x.lte(1)) return new Ctor(x.eq(1) ? 0 : NaN);\r\n if (!x.isFinite()) return new Ctor(x);\r\n\r\n pr = Ctor.precision;\r\n rm = Ctor.rounding;\r\n Ctor.precision = pr + Math.max(Math.abs(x.e), x.sd()) + 4;\r\n Ctor.rounding = 1;\r\n external = false;\r\n\r\n x = x.times(x).minus(1).sqrt().plus(x);\r\n\r\n external = true;\r\n Ctor.precision = pr;\r\n Ctor.rounding = rm;\r\n\r\n return x.ln();\r\n};\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is the inverse of the hyperbolic sine in radians of the value\r\n * of this Decimal.\r\n *\r\n * Domain: [-Infinity, Infinity]\r\n * Range: [-Infinity, Infinity]\r\n *\r\n * asinh(x) = ln(x + sqrt(x^2 + 1))\r\n *\r\n * asinh(NaN) = NaN\r\n * asinh(Infinity) = Infinity\r\n * asinh(-Infinity) = -Infinity\r\n * asinh(0) = 0\r\n * asinh(-0) = -0\r\n *\r\n */\r\nP.inverseHyperbolicSine = P.asinh = function () {\r\n var pr, rm,\r\n x = this,\r\n Ctor = x.constructor;\r\n\r\n if (!x.isFinite() || x.isZero()) return new Ctor(x);\r\n\r\n pr = Ctor.precision;\r\n rm = Ctor.rounding;\r\n Ctor.precision = pr + 2 * Math.max(Math.abs(x.e), x.sd()) + 6;\r\n Ctor.rounding = 1;\r\n external = false;\r\n\r\n x = x.times(x).plus(1).sqrt().plus(x);\r\n\r\n external = true;\r\n Ctor.precision = pr;\r\n Ctor.rounding = rm;\r\n\r\n return x.ln();\r\n};\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is the inverse of the hyperbolic tangent in radians of the\r\n * value of this Decimal.\r\n *\r\n * Domain: [-1, 1]\r\n * Range: [-Infinity, Infinity]\r\n *\r\n * atanh(x) = 0.5 * ln((1 + x) / (1 - x))\r\n *\r\n * atanh(|x| > 1) = NaN\r\n * atanh(NaN) = NaN\r\n * atanh(Infinity) = NaN\r\n * atanh(-Infinity) = NaN\r\n * atanh(0) = 0\r\n * atanh(-0) = -0\r\n * atanh(1) = Infinity\r\n * atanh(-1) = -Infinity\r\n *\r\n */\r\nP.inverseHyperbolicTangent = P.atanh = function () {\r\n var pr, rm, wpr, xsd,\r\n x = this,\r\n Ctor = x.constructor;\r\n\r\n if (!x.isFinite()) return new Ctor(NaN);\r\n if (x.e >= 0) return new Ctor(x.abs().eq(1) ? x.s / 0 : x.isZero() ? x : NaN);\r\n\r\n pr = Ctor.precision;\r\n rm = Ctor.rounding;\r\n xsd = x.sd();\r\n\r\n if (Math.max(xsd, pr) < 2 * -x.e - 1) return finalise(new Ctor(x), pr, rm, true);\r\n\r\n Ctor.precision = wpr = xsd - x.e;\r\n\r\n x = divide(x.plus(1), new Ctor(1).minus(x), wpr + pr, 1);\r\n\r\n Ctor.precision = pr + 4;\r\n Ctor.rounding = 1;\r\n\r\n x = x.ln();\r\n\r\n Ctor.precision = pr;\r\n Ctor.rounding = rm;\r\n\r\n return x.times(0.5);\r\n};\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is the arcsine (inverse sine) in radians of the value of this\r\n * Decimal.\r\n *\r\n * Domain: [-Infinity, Infinity]\r\n * Range: [-pi/2, pi/2]\r\n *\r\n * asin(x) = 2*atan(x/(1 + sqrt(1 - x^2)))\r\n *\r\n * asin(0) = 0\r\n * asin(-0) = -0\r\n * asin(1/2) = pi/6\r\n * asin(-1/2) = -pi/6\r\n * asin(1) = pi/2\r\n * asin(-1) = -pi/2\r\n * asin(|x| > 1) = NaN\r\n * asin(NaN) = NaN\r\n *\r\n * TODO? Compare performance of Taylor series.\r\n *\r\n */\r\nP.inverseSine = P.asin = function () {\r\n var halfPi, k,\r\n pr, rm,\r\n x = this,\r\n Ctor = x.constructor;\r\n\r\n if (x.isZero()) return new Ctor(x);\r\n\r\n k = x.abs().cmp(1);\r\n pr = Ctor.precision;\r\n rm = Ctor.rounding;\r\n\r\n if (k !== -1) {\r\n\r\n // |x| is 1\r\n if (k === 0) {\r\n halfPi = getPi(Ctor, pr + 4, rm).times(0.5);\r\n halfPi.s = x.s;\r\n return halfPi;\r\n }\r\n\r\n // |x| > 1 or x is NaN\r\n return new Ctor(NaN);\r\n }\r\n\r\n // TODO? Special case asin(1/2) = pi/6 and asin(-1/2) = -pi/6\r\n\r\n Ctor.precision = pr + 6;\r\n Ctor.rounding = 1;\r\n\r\n x = x.div(new Ctor(1).minus(x.times(x)).sqrt().plus(1)).atan();\r\n\r\n Ctor.precision = pr;\r\n Ctor.rounding = rm;\r\n\r\n return x.times(2);\r\n};\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is the arctangent (inverse tangent) in radians of the value\r\n * of this Decimal.\r\n *\r\n * Domain: [-Infinity, Infinity]\r\n * Range: [-pi/2, pi/2]\r\n *\r\n * atan(x) = x - x^3/3 + x^5/5 - x^7/7 + ...\r\n *\r\n * atan(0) = 0\r\n * atan(-0) = -0\r\n * atan(1) = pi/4\r\n * atan(-1) = -pi/4\r\n * atan(Infinity) = pi/2\r\n * atan(-Infinity) = -pi/2\r\n * atan(NaN) = NaN\r\n *\r\n */\r\nP.inverseTangent = P.atan = function () {\r\n var i, j, k, n, px, t, r, wpr, x2,\r\n x = this,\r\n Ctor = x.constructor,\r\n pr = Ctor.precision,\r\n rm = Ctor.rounding;\r\n\r\n if (!x.isFinite()) {\r\n if (!x.s) return new Ctor(NaN);\r\n if (pr + 4 <= PI_PRECISION) {\r\n r = getPi(Ctor, pr + 4, rm).times(0.5);\r\n r.s = x.s;\r\n return r;\r\n }\r\n } else if (x.isZero()) {\r\n return new Ctor(x);\r\n } else if (x.abs().eq(1) && pr + 4 <= PI_PRECISION) {\r\n r = getPi(Ctor, pr + 4, rm).times(0.25);\r\n r.s = x.s;\r\n return r;\r\n }\r\n\r\n Ctor.precision = wpr = pr + 10;\r\n Ctor.rounding = 1;\r\n\r\n // TODO? if (x >= 1 && pr <= PI_PRECISION) atan(x) = halfPi * x.s - atan(1 / x);\r\n\r\n // Argument reduction\r\n // Ensure |x| < 0.42\r\n // atan(x) = 2 * atan(x / (1 + sqrt(1 + x^2)))\r\n\r\n k = Math.min(28, wpr / LOG_BASE + 2 | 0);\r\n\r\n for (i = k; i; --i) x = x.div(x.times(x).plus(1).sqrt().plus(1));\r\n\r\n external = false;\r\n\r\n j = Math.ceil(wpr / LOG_BASE);\r\n n = 1;\r\n x2 = x.times(x);\r\n r = new Ctor(x);\r\n px = x;\r\n\r\n // atan(x) = x - x^3/3 + x^5/5 - x^7/7 + ...\r\n for (; i !== -1;) {\r\n px = px.times(x2);\r\n t = r.minus(px.div(n += 2));\r\n\r\n px = px.times(x2);\r\n r = t.plus(px.div(n += 2));\r\n\r\n if (r.d[j] !== void 0) for (i = j; r.d[i] === t.d[i] && i--;);\r\n }\r\n\r\n if (k) r = r.times(2 << (k - 1));\r\n\r\n external = true;\r\n\r\n return finalise(r, Ctor.precision = pr, Ctor.rounding = rm, true);\r\n};\r\n\r\n\r\n/*\r\n * Return true if the value of this Decimal is a finite number, otherwise return false.\r\n *\r\n */\r\nP.isFinite = function () {\r\n return !!this.d;\r\n};\r\n\r\n\r\n/*\r\n * Return true if the value of this Decimal is an integer, otherwise return false.\r\n *\r\n */\r\nP.isInteger = P.isInt = function () {\r\n return !!this.d && mathfloor(this.e / LOG_BASE) > this.d.length - 2;\r\n};\r\n\r\n\r\n/*\r\n * Return true if the value of this Decimal is NaN, otherwise return false.\r\n *\r\n */\r\nP.isNaN = function () {\r\n return !this.s;\r\n};\r\n\r\n\r\n/*\r\n * Return true if the value of this Decimal is negative, otherwise return false.\r\n *\r\n */\r\nP.isNegative = P.isNeg = function () {\r\n return this.s < 0;\r\n};\r\n\r\n\r\n/*\r\n * Return true if the value of this Decimal is positive, otherwise return false.\r\n *\r\n */\r\nP.isPositive = P.isPos = function () {\r\n return this.s > 0;\r\n};\r\n\r\n\r\n/*\r\n * Return true if the value of this Decimal is 0 or -0, otherwise return false.\r\n *\r\n */\r\nP.isZero = function () {\r\n return !!this.d && this.d[0] === 0;\r\n};\r\n\r\n\r\n/*\r\n * Return true if the value of this Decimal is less than `y`, otherwise return false.\r\n *\r\n */\r\nP.lessThan = P.lt = function (y) {\r\n return this.cmp(y) < 0;\r\n};\r\n\r\n\r\n/*\r\n * Return true if the value of this Decimal is less than or equal to `y`, otherwise return false.\r\n *\r\n */\r\nP.lessThanOrEqualTo = P.lte = function (y) {\r\n return this.cmp(y) < 1;\r\n};\r\n\r\n\r\n/*\r\n * Return the logarithm of the value of this Decimal to the specified base, rounded to `precision`\r\n * significant digits using rounding mode `rounding`.\r\n *\r\n * If no base is specified, return log[10](arg).\r\n *\r\n * log[base](arg) = ln(arg) / ln(base)\r\n *\r\n * The result will always be correctly rounded if the base of the log is 10, and 'almost always'\r\n * otherwise:\r\n *\r\n * Depending on the rounding mode, the result may be incorrectly rounded if the first fifteen\r\n * rounding digits are [49]99999999999999 or [50]00000000000000. In that case, the maximum error\r\n * between the result and the correctly rounded result will be one ulp (unit in the last place).\r\n *\r\n * log[-b](a) = NaN\r\n * log[0](a) = NaN\r\n * log[1](a) = NaN\r\n * log[NaN](a) = NaN\r\n * log[Infinity](a) = NaN\r\n * log[b](0) = -Infinity\r\n * log[b](-0) = -Infinity\r\n * log[b](-a) = NaN\r\n * log[b](1) = 0\r\n * log[b](Infinity) = Infinity\r\n * log[b](NaN) = NaN\r\n *\r\n * [base] {number|string|Decimal} The base of the logarithm.\r\n *\r\n */\r\nP.logarithm = P.log = function (base) {\r\n var isBase10, d, denominator, k, inf, num, sd, r,\r\n arg = this,\r\n Ctor = arg.constructor,\r\n pr = Ctor.precision,\r\n rm = Ctor.rounding,\r\n guard = 5;\r\n\r\n // Default base is 10.\r\n if (base == null) {\r\n base = new Ctor(10);\r\n isBase10 = true;\r\n } else {\r\n base = new Ctor(base);\r\n d = base.d;\r\n\r\n // Return NaN if base is negative, or non-finite, or is 0 or 1.\r\n if (base.s < 0 || !d || !d[0] || base.eq(1)) return new Ctor(NaN);\r\n\r\n isBase10 = base.eq(10);\r\n }\r\n\r\n d = arg.d;\r\n\r\n // Is arg negative, non-finite, 0 or 1?\r\n if (arg.s < 0 || !d || !d[0] || arg.eq(1)) {\r\n return new Ctor(d && !d[0] ? -1 / 0 : arg.s != 1 ? NaN : d ? 0 : 1 / 0);\r\n }\r\n\r\n // The result will have a non-terminating decimal expansion if base is 10 and arg is not an\r\n // integer power of 10.\r\n if (isBase10) {\r\n if (d.length > 1) {\r\n inf = true;\r\n } else {\r\n for (k = d[0]; k % 10 === 0;) k /= 10;\r\n inf = k !== 1;\r\n }\r\n }\r\n\r\n external = false;\r\n sd = pr + guard;\r\n num = naturalLogarithm(arg, sd);\r\n denominator = isBase10 ? getLn10(Ctor, sd + 10) : naturalLogarithm(base, sd);\r\n\r\n // The result will have 5 rounding digits.\r\n r = divide(num, denominator, sd, 1);\r\n\r\n // If at a rounding boundary, i.e. the result's rounding digits are [49]9999 or [50]0000,\r\n // calculate 10 further digits.\r\n //\r\n // If the result is known to have an infinite decimal expansion, repeat this until it is clear\r\n // that the result is above or below the boundary. Otherwise, if after calculating the 10\r\n // further digits, the last 14 are nines, round up and assume the result is exact.\r\n // Also assume the result is exact if the last 14 are zero.\r\n //\r\n // Example of a result that will be incorrectly rounded:\r\n // log[1048576](4503599627370502) = 2.60000000000000009610279511444746...\r\n // The above result correctly rounded using ROUND_CEIL to 1 decimal place should be 2.7, but it\r\n // will be given as 2.6 as there are 15 zeros immediately after the requested decimal place, so\r\n // the exact result would be assumed to be 2.6, which rounded using ROUND_CEIL to 1 decimal\r\n // place is still 2.6.\r\n if (checkRoundingDigits(r.d, k = pr, rm)) {\r\n\r\n do {\r\n sd += 10;\r\n num = naturalLogarithm(arg, sd);\r\n denominator = isBase10 ? getLn10(Ctor, sd + 10) : naturalLogarithm(base, sd);\r\n r = divide(num, denominator, sd, 1);\r\n\r\n if (!inf) {\r\n\r\n // Check for 14 nines from the 2nd rounding digit, as the first may be 4.\r\n if (+digitsToString(r.d).slice(k + 1, k + 15) + 1 == 1e14) {\r\n r = finalise(r, pr + 1, 0);\r\n }\r\n\r\n break;\r\n }\r\n } while (checkRoundingDigits(r.d, k += 10, rm));\r\n }\r\n\r\n external = true;\r\n\r\n return finalise(r, pr, rm);\r\n};\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is the maximum of the arguments and the value of this Decimal.\r\n *\r\n * arguments {number|string|Decimal}\r\n *\r\nP.max = function () {\r\n Array.prototype.push.call(arguments, this);\r\n return maxOrMin(this.constructor, arguments, 'lt');\r\n};\r\n */\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is the minimum of the arguments and the value of this Decimal.\r\n *\r\n * arguments {number|string|Decimal}\r\n *\r\nP.min = function () {\r\n Array.prototype.push.call(arguments, this);\r\n return maxOrMin(this.constructor, arguments, 'gt');\r\n};\r\n */\r\n\r\n\r\n/*\r\n * n - 0 = n\r\n * n - N = N\r\n * n - I = -I\r\n * 0 - n = -n\r\n * 0 - 0 = 0\r\n * 0 - N = N\r\n * 0 - I = -I\r\n * N - n = N\r\n * N - 0 = N\r\n * N - N = N\r\n * N - I = N\r\n * I - n = I\r\n * I - 0 = I\r\n * I - N = N\r\n * I - I = N\r\n *\r\n * Return a new Decimal whose value is the value of this Decimal minus `y`, rounded to `precision`\r\n * significant digits using rounding mode `rounding`.\r\n *\r\n */\r\nP.minus = P.sub = function (y) {\r\n var d, e, i, j, k, len, pr, rm, xd, xe, xLTy, yd,\r\n x = this,\r\n Ctor = x.constructor;\r\n\r\n y = new Ctor(y);\r\n\r\n // If either is not finite...\r\n if (!x.d || !y.d) {\r\n\r\n // Return NaN if either is NaN.\r\n if (!x.s || !y.s) y = new Ctor(NaN);\r\n\r\n // Return y negated if x is finite and y is ±Infinity.\r\n else if (x.d) y.s = -y.s;\r\n\r\n // Return x if y is finite and x is ±Infinity.\r\n // Return x if both are ±Infinity with different signs.\r\n // Return NaN if both are ±Infinity with the same sign.\r\n else y = new Ctor(y.d || x.s !== y.s ? x : NaN);\r\n\r\n return y;\r\n }\r\n\r\n // If signs differ...\r\n if (x.s != y.s) {\r\n y.s = -y.s;\r\n return x.plus(y);\r\n }\r\n\r\n xd = x.d;\r\n yd = y.d;\r\n pr = Ctor.precision;\r\n rm = Ctor.rounding;\r\n\r\n // If either is zero...\r\n if (!xd[0] || !yd[0]) {\r\n\r\n // Return y negated if x is zero and y is non-zero.\r\n if (yd[0]) y.s = -y.s;\r\n\r\n // Return x if y is zero and x is non-zero.\r\n else if (xd[0]) y = new Ctor(x);\r\n\r\n // Return zero if both are zero.\r\n // From IEEE 754 (2008) 6.3: 0 - 0 = -0 - -0 = -0 when rounding to -Infinity.\r\n else return new Ctor(rm === 3 ? -0 : 0);\r\n\r\n return external ? finalise(y, pr, rm) : y;\r\n }\r\n\r\n // x and y are finite, non-zero numbers with the same sign.\r\n\r\n // Calculate base 1e7 exponents.\r\n e = mathfloor(y.e / LOG_BASE);\r\n xe = mathfloor(x.e / LOG_BASE);\r\n\r\n xd = xd.slice();\r\n k = xe - e;\r\n\r\n // If base 1e7 exponents differ...\r\n if (k) {\r\n xLTy = k < 0;\r\n\r\n if (xLTy) {\r\n d = xd;\r\n k = -k;\r\n len = yd.length;\r\n } else {\r\n d = yd;\r\n e = xe;\r\n len = xd.length;\r\n }\r\n\r\n // Numbers with massively different exponents would result in a very high number of\r\n // zeros needing to be prepended, but this can be avoided while still ensuring correct\r\n // rounding by limiting the number of zeros to `Math.ceil(pr / LOG_BASE) + 2`.\r\n i = Math.max(Math.ceil(pr / LOG_BASE), len) + 2;\r\n\r\n if (k > i) {\r\n k = i;\r\n d.length = 1;\r\n }\r\n\r\n // Prepend zeros to equalise exponents.\r\n d.reverse();\r\n for (i = k; i--;) d.push(0);\r\n d.reverse();\r\n\r\n // Base 1e7 exponents equal.\r\n } else {\r\n\r\n // Check digits to determine which is the bigger number.\r\n\r\n i = xd.length;\r\n len = yd.length;\r\n xLTy = i < len;\r\n if (xLTy) len = i;\r\n\r\n for (i = 0; i < len; i++) {\r\n if (xd[i] != yd[i]) {\r\n xLTy = xd[i] < yd[i];\r\n break;\r\n }\r\n }\r\n\r\n k = 0;\r\n }\r\n\r\n if (xLTy) {\r\n d = xd;\r\n xd = yd;\r\n yd = d;\r\n y.s = -y.s;\r\n }\r\n\r\n len = xd.length;\r\n\r\n // Append zeros to `xd` if shorter.\r\n // Don't add zeros to `yd` if shorter as subtraction only needs to start at `yd` length.\r\n for (i = yd.length - len; i > 0; --i) xd[len++] = 0;\r\n\r\n // Subtract yd from xd.\r\n for (i = yd.length; i > k;) {\r\n\r\n if (xd[--i] < yd[i]) {\r\n for (j = i; j && xd[--j] === 0;) xd[j] = BASE - 1;\r\n --xd[j];\r\n xd[i] += BASE;\r\n }\r\n\r\n xd[i] -= yd[i];\r\n }\r\n\r\n // Remove trailing zeros.\r\n for (; xd[--len] === 0;) xd.pop();\r\n\r\n // Remove leading zeros and adjust exponent accordingly.\r\n for (; xd[0] === 0; xd.shift()) --e;\r\n\r\n // Zero?\r\n if (!xd[0]) return new Ctor(rm === 3 ? -0 : 0);\r\n\r\n y.d = xd;\r\n y.e = getBase10Exponent(xd, e);\r\n\r\n return external ? finalise(y, pr, rm) : y;\r\n};\r\n\r\n\r\n/*\r\n * n % 0 = N\r\n * n % N = N\r\n * n % I = n\r\n * 0 % n = 0\r\n * -0 % n = -0\r\n * 0 % 0 = N\r\n * 0 % N = N\r\n * 0 % I = 0\r\n * N % n = N\r\n * N % 0 = N\r\n * N % N = N\r\n * N % I = N\r\n * I % n = N\r\n * I % 0 = N\r\n * I % N = N\r\n * I % I = N\r\n *\r\n * Return a new Decimal whose value is the value of this Decimal modulo `y`, rounded to\r\n * `precision` significant digits using rounding mode `rounding`.\r\n *\r\n * The result depends on the modulo mode.\r\n *\r\n */\r\nP.modulo = P.mod = function (y) {\r\n var q,\r\n x = this,\r\n Ctor = x.constructor;\r\n\r\n y = new Ctor(y);\r\n\r\n // Return NaN if x is ±Infinity or NaN, or y is NaN or ±0.\r\n if (!x.d || !y.s || y.d && !y.d[0]) return new Ctor(NaN);\r\n\r\n // Return x if y is ±Infinity or x is ±0.\r\n if (!y.d || x.d && !x.d[0]) {\r\n return finalise(new Ctor(x), Ctor.precision, Ctor.rounding);\r\n }\r\n\r\n // Prevent rounding of intermediate calculations.\r\n external = false;\r\n\r\n if (Ctor.modulo == 9) {\r\n\r\n // Euclidian division: q = sign(y) * floor(x / abs(y))\r\n // result = x - q * y where 0 <= result < abs(y)\r\n q = divide(x, y.abs(), 0, 3, 1);\r\n q.s *= y.s;\r\n } else {\r\n q = divide(x, y, 0, Ctor.modulo, 1);\r\n }\r\n\r\n q = q.times(y);\r\n\r\n external = true;\r\n\r\n return x.minus(q);\r\n};\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is the natural exponential of the value of this Decimal,\r\n * i.e. the base e raised to the power the value of this Decimal, rounded to `precision`\r\n * significant digits using rounding mode `rounding`.\r\n *\r\n */\r\nP.naturalExponential = P.exp = function () {\r\n return naturalExponential(this);\r\n};\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is the natural logarithm of the value of this Decimal,\r\n * rounded to `precision` significant digits using rounding mode `rounding`.\r\n *\r\n */\r\nP.naturalLogarithm = P.ln = function () {\r\n return naturalLogarithm(this);\r\n};\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is the value of this Decimal negated, i.e. as if multiplied by\r\n * -1.\r\n *\r\n */\r\nP.negated = P.neg = function () {\r\n var x = new this.constructor(this);\r\n x.s = -x.s;\r\n return finalise(x);\r\n};\r\n\r\n\r\n/*\r\n * n + 0 = n\r\n * n + N = N\r\n * n + I = I\r\n * 0 + n = n\r\n * 0 + 0 = 0\r\n * 0 + N = N\r\n * 0 + I = I\r\n * N + n = N\r\n * N + 0 = N\r\n * N + N = N\r\n * N + I = N\r\n * I + n = I\r\n * I + 0 = I\r\n * I + N = N\r\n * I + I = I\r\n *\r\n * Return a new Decimal whose value is the value of this Decimal plus `y`, rounded to `precision`\r\n * significant digits using rounding mode `rounding`.\r\n *\r\n */\r\nP.plus = P.add = function (y) {\r\n var carry, d, e, i, k, len, pr, rm, xd, yd,\r\n x = this,\r\n Ctor = x.constructor;\r\n\r\n y = new Ctor(y);\r\n\r\n // If either is not finite...\r\n if (!x.d || !y.d) {\r\n\r\n // Return NaN if either is NaN.\r\n if (!x.s || !y.s) y = new Ctor(NaN);\r\n\r\n // Return x if y is finite and x is ±Infinity.\r\n // Return x if both are ±Infinity with the same sign.\r\n // Return NaN if both are ±Infinity with different signs.\r\n // Return y if x is finite and y is ±Infinity.\r\n else if (!x.d) y = new Ctor(y.d || x.s === y.s ? x : NaN);\r\n\r\n return y;\r\n }\r\n\r\n // If signs differ...\r\n if (x.s != y.s) {\r\n y.s = -y.s;\r\n return x.minus(y);\r\n }\r\n\r\n xd = x.d;\r\n yd = y.d;\r\n pr = Ctor.precision;\r\n rm = Ctor.rounding;\r\n\r\n // If either is zero...\r\n if (!xd[0] || !yd[0]) {\r\n\r\n // Return x if y is zero.\r\n // Return y if y is non-zero.\r\n if (!yd[0]) y = new Ctor(x);\r\n\r\n return external ? finalise(y, pr, rm) : y;\r\n }\r\n\r\n // x and y are finite, non-zero numbers with the same sign.\r\n\r\n // Calculate base 1e7 exponents.\r\n k = mathfloor(x.e / LOG_BASE);\r\n e = mathfloor(y.e / LOG_BASE);\r\n\r\n xd = xd.slice();\r\n i = k - e;\r\n\r\n // If base 1e7 exponents differ...\r\n if (i) {\r\n\r\n if (i < 0) {\r\n d = xd;\r\n i = -i;\r\n len = yd.length;\r\n } else {\r\n d = yd;\r\n e = k;\r\n len = xd.length;\r\n }\r\n\r\n // Limit number of zeros prepended to max(ceil(pr / LOG_BASE), len) + 1.\r\n k = Math.ceil(pr / LOG_BASE);\r\n len = k > len ? k + 1 : len + 1;\r\n\r\n if (i > len) {\r\n i = len;\r\n d.length = 1;\r\n }\r\n\r\n // Prepend zeros to equalise exponents. Note: Faster to use reverse then do unshifts.\r\n d.reverse();\r\n for (; i--;) d.push(0);\r\n d.reverse();\r\n }\r\n\r\n len = xd.length;\r\n i = yd.length;\r\n\r\n // If yd is longer than xd, swap xd and yd so xd points to the longer array.\r\n if (len - i < 0) {\r\n i = len;\r\n d = yd;\r\n yd = xd;\r\n xd = d;\r\n }\r\n\r\n // Only start adding at yd.length - 1 as the further digits of xd can be left as they are.\r\n for (carry = 0; i;) {\r\n carry = (xd[--i] = xd[i] + yd[i] + carry) / BASE | 0;\r\n xd[i] %= BASE;\r\n }\r\n\r\n if (carry) {\r\n xd.unshift(carry);\r\n ++e;\r\n }\r\n\r\n // Remove trailing zeros.\r\n // No need to check for zero, as +x + +y != 0 && -x + -y != 0\r\n for (len = xd.length; xd[--len] == 0;) xd.pop();\r\n\r\n y.d = xd;\r\n y.e = getBase10Exponent(xd, e);\r\n\r\n return external ? finalise(y, pr, rm) : y;\r\n};\r\n\r\n\r\n/*\r\n * Return the number of significant digits of the value of this Decimal.\r\n *\r\n * [z] {boolean|number} Whether to count integer-part trailing zeros: true, false, 1 or 0.\r\n *\r\n */\r\nP.precision = P.sd = function (z) {\r\n var k,\r\n x = this;\r\n\r\n if (z !== void 0 && z !== !!z && z !== 1 && z !== 0) throw Error(invalidArgument + z);\r\n\r\n if (x.d) {\r\n k = getPrecision(x.d);\r\n if (z && x.e + 1 > k) k = x.e + 1;\r\n } else {\r\n k = NaN;\r\n }\r\n\r\n return k;\r\n};\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is the value of this Decimal rounded to a whole number using\r\n * rounding mode `rounding`.\r\n *\r\n */\r\nP.round = function () {\r\n var x = this,\r\n Ctor = x.constructor;\r\n\r\n return finalise(new Ctor(x), x.e + 1, Ctor.rounding);\r\n};\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is the sine of the value in radians of this Decimal.\r\n *\r\n * Domain: [-Infinity, Infinity]\r\n * Range: [-1, 1]\r\n *\r\n * sin(x) = x - x^3/3! + x^5/5! - ...\r\n *\r\n * sin(0) = 0\r\n * sin(-0) = -0\r\n * sin(Infinity) = NaN\r\n * sin(-Infinity) = NaN\r\n * sin(NaN) = NaN\r\n *\r\n */\r\nP.sine = P.sin = function () {\r\n var pr, rm,\r\n x = this,\r\n Ctor = x.constructor;\r\n\r\n if (!x.isFinite()) return new Ctor(NaN);\r\n if (x.isZero()) return new Ctor(x);\r\n\r\n pr = Ctor.precision;\r\n rm = Ctor.rounding;\r\n Ctor.precision = pr + Math.max(x.e, x.sd()) + LOG_BASE;\r\n Ctor.rounding = 1;\r\n\r\n x = sine(Ctor, toLessThanHalfPi(Ctor, x));\r\n\r\n Ctor.precision = pr;\r\n Ctor.rounding = rm;\r\n\r\n return finalise(quadrant > 2 ? x.neg() : x, pr, rm, true);\r\n};\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is the square root of this Decimal, rounded to `precision`\r\n * significant digits using rounding mode `rounding`.\r\n *\r\n * sqrt(-n) = N\r\n * sqrt(N) = N\r\n * sqrt(-I) = N\r\n * sqrt(I) = I\r\n * sqrt(0) = 0\r\n * sqrt(-0) = -0\r\n *\r\n */\r\nP.squareRoot = P.sqrt = function () {\r\n var m, n, sd, r, rep, t,\r\n x = this,\r\n d = x.d,\r\n e = x.e,\r\n s = x.s,\r\n Ctor = x.constructor;\r\n\r\n // Negative/NaN/Infinity/zero?\r\n if (s !== 1 || !d || !d[0]) {\r\n return new Ctor(!s || s < 0 && (!d || d[0]) ? NaN : d ? x : 1 / 0);\r\n }\r\n\r\n external = false;\r\n\r\n // Initial estimate.\r\n s = Math.sqrt(+x);\r\n\r\n // Math.sqrt underflow/overflow?\r\n // Pass x to Math.sqrt as integer, then adjust the exponent of the result.\r\n if (s == 0 || s == 1 / 0) {\r\n n = digitsToString(d);\r\n\r\n if ((n.length + e) % 2 == 0) n += '0';\r\n s = Math.sqrt(n);\r\n e = mathfloor((e + 1) / 2) - (e < 0 || e % 2);\r\n\r\n if (s == 1 / 0) {\r\n n = '5e' + e;\r\n } else {\r\n n = s.toExponential();\r\n n = n.slice(0, n.indexOf('e') + 1) + e;\r\n }\r\n\r\n r = new Ctor(n);\r\n } else {\r\n r = new Ctor(s.toString());\r\n }\r\n\r\n sd = (e = Ctor.precision) + 3;\r\n\r\n // Newton-Raphson iteration.\r\n for (;;) {\r\n t = r;\r\n r = t.plus(divide(x, t, sd + 2, 1)).times(0.5);\r\n\r\n // TODO? Replace with for-loop and checkRoundingDigits.\r\n if (digitsToString(t.d).slice(0, sd) === (n = digitsToString(r.d)).slice(0, sd)) {\r\n n = n.slice(sd - 3, sd + 1);\r\n\r\n // The 4th rounding digit may be in error by -1 so if the 4 rounding digits are 9999 or\r\n // 4999, i.e. approaching a rounding boundary, continue the iteration.\r\n if (n == '9999' || !rep && n == '4999') {\r\n\r\n // On the first iteration only, check to see if rounding up gives the exact result as the\r\n // nines may infinitely repeat.\r\n if (!rep) {\r\n finalise(t, e + 1, 0);\r\n\r\n if (t.times(t).eq(x)) {\r\n r = t;\r\n break;\r\n }\r\n }\r\n\r\n sd += 4;\r\n rep = 1;\r\n } else {\r\n\r\n // If the rounding digits are null, 0{0,4} or 50{0,3}, check for an exact result.\r\n // If not, then there are further digits and m will be truthy.\r\n if (!+n || !+n.slice(1) && n.charAt(0) == '5') {\r\n\r\n // Truncate to the first rounding digit.\r\n finalise(r, e + 1, 1);\r\n m = !r.times(r).eq(x);\r\n }\r\n\r\n break;\r\n }\r\n }\r\n }\r\n\r\n external = true;\r\n\r\n return finalise(r, e, Ctor.rounding, m);\r\n};\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is the tangent of the value in radians of this Decimal.\r\n *\r\n * Domain: [-Infinity, Infinity]\r\n * Range: [-Infinity, Infinity]\r\n *\r\n * tan(0) = 0\r\n * tan(-0) = -0\r\n * tan(Infinity) = NaN\r\n * tan(-Infinity) = NaN\r\n * tan(NaN) = NaN\r\n *\r\n */\r\nP.tangent = P.tan = function () {\r\n var pr, rm,\r\n x = this,\r\n Ctor = x.constructor;\r\n\r\n if (!x.isFinite()) return new Ctor(NaN);\r\n if (x.isZero()) return new Ctor(x);\r\n\r\n pr = Ctor.precision;\r\n rm = Ctor.rounding;\r\n Ctor.precision = pr + 10;\r\n Ctor.rounding = 1;\r\n\r\n x = x.sin();\r\n x.s = 1;\r\n x = divide(x, new Ctor(1).minus(x.times(x)).sqrt(), pr + 10, 0);\r\n\r\n Ctor.precision = pr;\r\n Ctor.rounding = rm;\r\n\r\n return finalise(quadrant == 2 || quadrant == 4 ? x.neg() : x, pr, rm, true);\r\n};\r\n\r\n\r\n/*\r\n * n * 0 = 0\r\n * n * N = N\r\n * n * I = I\r\n * 0 * n = 0\r\n * 0 * 0 = 0\r\n * 0 * N = N\r\n * 0 * I = N\r\n * N * n = N\r\n * N * 0 = N\r\n * N * N = N\r\n * N * I = N\r\n * I * n = I\r\n * I * 0 = N\r\n * I * N = N\r\n * I * I = I\r\n *\r\n * Return a new Decimal whose value is this Decimal times `y`, rounded to `precision` significant\r\n * digits using rounding mode `rounding`.\r\n *\r\n */\r\nP.times = P.mul = function (y) {\r\n var carry, e, i, k, r, rL, t, xdL, ydL,\r\n x = this,\r\n Ctor = x.constructor,\r\n xd = x.d,\r\n yd = (y = new Ctor(y)).d;\r\n\r\n y.s *= x.s;\r\n\r\n // If either is NaN, ±Infinity or ±0...\r\n if (!xd || !xd[0] || !yd || !yd[0]) {\r\n\r\n return new Ctor(!y.s || xd && !xd[0] && !yd || yd && !yd[0] && !xd\r\n\r\n // Return NaN if either is NaN.\r\n // Return NaN if x is ±0 and y is ±Infinity, or y is ±0 and x is ±Infinity.\r\n ? NaN\r\n\r\n // Return ±Infinity if either is ±Infinity.\r\n // Return ±0 if either is ±0.\r\n : !xd || !yd ? y.s / 0 : y.s * 0);\r\n }\r\n\r\n e = mathfloor(x.e / LOG_BASE) + mathfloor(y.e / LOG_BASE);\r\n xdL = xd.length;\r\n ydL = yd.length;\r\n\r\n // Ensure xd points to the longer array.\r\n if (xdL < ydL) {\r\n r = xd;\r\n xd = yd;\r\n yd = r;\r\n rL = xdL;\r\n xdL = ydL;\r\n ydL = rL;\r\n }\r\n\r\n // Initialise the result array with zeros.\r\n r = [];\r\n rL = xdL + ydL;\r\n for (i = rL; i--;) r.push(0);\r\n\r\n // Multiply!\r\n for (i = ydL; --i >= 0;) {\r\n carry = 0;\r\n for (k = xdL + i; k > i;) {\r\n t = r[k] + yd[i] * xd[k - i - 1] + carry;\r\n r[k--] = t % BASE | 0;\r\n carry = t / BASE | 0;\r\n }\r\n\r\n r[k] = (r[k] + carry) % BASE | 0;\r\n }\r\n\r\n // Remove trailing zeros.\r\n for (; !r[--rL];) r.pop();\r\n\r\n if (carry) ++e;\r\n else r.shift();\r\n\r\n y.d = r;\r\n y.e = getBase10Exponent(r, e);\r\n\r\n return external ? finalise(y, Ctor.precision, Ctor.rounding) : y;\r\n};\r\n\r\n\r\n/*\r\n * Return a string representing the value of this Decimal in base 2, round to `sd` significant\r\n * digits using rounding mode `rm`.\r\n *\r\n * If the optional `sd` argument is present then return binary exponential notation.\r\n *\r\n * [sd] {number} Significant digits. Integer, 1 to MAX_DIGITS inclusive.\r\n * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.\r\n *\r\n */\r\nP.toBinary = function (sd, rm) {\r\n return toStringBinary(this, 2, sd, rm);\r\n};\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is the value of this Decimal rounded to a maximum of `dp`\r\n * decimal places using rounding mode `rm` or `rounding` if `rm` is omitted.\r\n *\r\n * If `dp` is omitted, return a new Decimal whose value is the value of this Decimal.\r\n *\r\n * [dp] {number} Decimal places. Integer, 0 to MAX_DIGITS inclusive.\r\n * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.\r\n *\r\n */\r\nP.toDecimalPlaces = P.toDP = function (dp, rm) {\r\n var x = this,\r\n Ctor = x.constructor;\r\n\r\n x = new Ctor(x);\r\n if (dp === void 0) return x;\r\n\r\n checkInt32(dp, 0, MAX_DIGITS);\r\n\r\n if (rm === void 0) rm = Ctor.rounding;\r\n else checkInt32(rm, 0, 8);\r\n\r\n return finalise(x, dp + x.e + 1, rm);\r\n};\r\n\r\n\r\n/*\r\n * Return a string representing the value of this Decimal in exponential notation rounded to\r\n * `dp` fixed decimal places using rounding mode `rounding`.\r\n *\r\n * [dp] {number} Decimal places. Integer, 0 to MAX_DIGITS inclusive.\r\n * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.\r\n *\r\n */\r\nP.toExponential = function (dp, rm) {\r\n var str,\r\n x = this,\r\n Ctor = x.constructor;\r\n\r\n if (dp === void 0) {\r\n str = finiteToString(x, true);\r\n } else {\r\n checkInt32(dp, 0, MAX_DIGITS);\r\n\r\n if (rm === void 0) rm = Ctor.rounding;\r\n else checkInt32(rm, 0, 8);\r\n\r\n x = finalise(new Ctor(x), dp + 1, rm);\r\n str = finiteToString(x, true, dp + 1);\r\n }\r\n\r\n return x.isNeg() && !x.isZero() ? '-' + str : str;\r\n};\r\n\r\n\r\n/*\r\n * Return a string representing the value of this Decimal in normal (fixed-point) notation to\r\n * `dp` fixed decimal places and rounded using rounding mode `rm` or `rounding` if `rm` is\r\n * omitted.\r\n *\r\n * As with JavaScript numbers, (-0).toFixed(0) is '0', but e.g. (-0.00001).toFixed(0) is '-0'.\r\n *\r\n * [dp] {number} Decimal places. Integer, 0 to MAX_DIGITS inclusive.\r\n * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.\r\n *\r\n * (-0).toFixed(0) is '0', but (-0.1).toFixed(0) is '-0'.\r\n * (-0).toFixed(1) is '0.0', but (-0.01).toFixed(1) is '-0.0'.\r\n * (-0).toFixed(3) is '0.000'.\r\n * (-0.5).toFixed(0) is '-0'.\r\n *\r\n */\r\nP.toFixed = function (dp, rm) {\r\n var str, y,\r\n x = this,\r\n Ctor = x.constructor;\r\n\r\n if (dp === void 0) {\r\n str = finiteToString(x);\r\n } else {\r\n checkInt32(dp, 0, MAX_DIGITS);\r\n\r\n if (rm === void 0) rm = Ctor.rounding;\r\n else checkInt32(rm, 0, 8);\r\n\r\n y = finalise(new Ctor(x), dp + x.e + 1, rm);\r\n str = finiteToString(y, false, dp + y.e + 1);\r\n }\r\n\r\n // To determine whether to add the minus sign look at the value before it was rounded,\r\n // i.e. look at `x` rather than `y`.\r\n return x.isNeg() && !x.isZero() ? '-' + str : str;\r\n};\r\n\r\n\r\n/*\r\n * Return an array representing the value of this Decimal as a simple fraction with an integer\r\n * numerator and an integer denominator.\r\n *\r\n * The denominator will be a positive non-zero value less than or equal to the specified maximum\r\n * denominator. If a maximum denominator is not specified, the denominator will be the lowest\r\n * value necessary to represent the number exactly.\r\n *\r\n * [maxD] {number|string|Decimal} Maximum denominator. Integer >= 1 and < Infinity.\r\n *\r\n */\r\nP.toFraction = function (maxD) {\r\n var d, d0, d1, d2, e, k, n, n0, n1, pr, q, r,\r\n x = this,\r\n xd = x.d,\r\n Ctor = x.constructor;\r\n\r\n if (!xd) return new Ctor(x);\r\n\r\n n1 = d0 = new Ctor(1);\r\n d1 = n0 = new Ctor(0);\r\n\r\n d = new Ctor(d1);\r\n e = d.e = getPrecision(xd) - x.e - 1;\r\n k = e % LOG_BASE;\r\n d.d[0] = mathpow(10, k < 0 ? LOG_BASE + k : k);\r\n\r\n if (maxD == null) {\r\n\r\n // d is 10**e, the minimum max-denominator needed.\r\n maxD = e > 0 ? d : n1;\r\n } else {\r\n n = new Ctor(maxD);\r\n if (!n.isInt() || n.lt(n1)) throw Error(invalidArgument + n);\r\n maxD = n.gt(d) ? (e > 0 ? d : n1) : n;\r\n }\r\n\r\n external = false;\r\n n = new Ctor(digitsToString(xd));\r\n pr = Ctor.precision;\r\n Ctor.precision = e = xd.length * LOG_BASE * 2;\r\n\r\n for (;;) {\r\n q = divide(n, d, 0, 1, 1);\r\n d2 = d0.plus(q.times(d1));\r\n if (d2.cmp(maxD) == 1) break;\r\n d0 = d1;\r\n d1 = d2;\r\n d2 = n1;\r\n n1 = n0.plus(q.times(d2));\r\n n0 = d2;\r\n d2 = d;\r\n d = n.minus(q.times(d2));\r\n n = d2;\r\n }\r\n\r\n d2 = divide(maxD.minus(d0), d1, 0, 1, 1);\r\n n0 = n0.plus(d2.times(n1));\r\n d0 = d0.plus(d2.times(d1));\r\n n0.s = n1.s = x.s;\r\n\r\n // Determine which fraction is closer to x, n0/d0 or n1/d1?\r\n r = divide(n1, d1, e, 1).minus(x).abs().cmp(divide(n0, d0, e, 1).minus(x).abs()) < 1\r\n ? [n1, d1] : [n0, d0];\r\n\r\n Ctor.precision = pr;\r\n external = true;\r\n\r\n return r;\r\n};\r\n\r\n\r\n/*\r\n * Return a string representing the value of this Decimal in base 16, round to `sd` significant\r\n * digits using rounding mode `rm`.\r\n *\r\n * If the optional `sd` argument is present then return binary exponential notation.\r\n *\r\n * [sd] {number} Significant digits. Integer, 1 to MAX_DIGITS inclusive.\r\n * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.\r\n *\r\n */\r\nP.toHexadecimal = P.toHex = function (sd, rm) {\r\n return toStringBinary(this, 16, sd, rm);\r\n};\r\n\r\n\r\n/*\r\n * Returns a new Decimal whose value is the nearest multiple of `y` in the direction of rounding\r\n * mode `rm`, or `Decimal.rounding` if `rm` is omitted, to the value of this Decimal.\r\n *\r\n * The return value will always have the same sign as this Decimal, unless either this Decimal\r\n * or `y` is NaN, in which case the return value will be also be NaN.\r\n *\r\n * The return value is not affected by the value of `precision`.\r\n *\r\n * y {number|string|Decimal} The magnitude to round to a multiple of.\r\n * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.\r\n *\r\n * 'toNearest() rounding mode not an integer: {rm}'\r\n * 'toNearest() rounding mode out of range: {rm}'\r\n *\r\n */\r\nP.toNearest = function (y, rm) {\r\n var x = this,\r\n Ctor = x.constructor;\r\n\r\n x = new Ctor(x);\r\n\r\n if (y == null) {\r\n\r\n // If x is not finite, return x.\r\n if (!x.d) return x;\r\n\r\n y = new Ctor(1);\r\n rm = Ctor.rounding;\r\n } else {\r\n y = new Ctor(y);\r\n if (rm === void 0) {\r\n rm = Ctor.rounding;\r\n } else {\r\n checkInt32(rm, 0, 8);\r\n }\r\n\r\n // If x is not finite, return x if y is not NaN, else NaN.\r\n if (!x.d) return y.s ? x : y;\r\n\r\n // If y is not finite, return Infinity with the sign of x if y is Infinity, else NaN.\r\n if (!y.d) {\r\n if (y.s) y.s = x.s;\r\n return y;\r\n }\r\n }\r\n\r\n // If y is not zero, calculate the nearest multiple of y to x.\r\n if (y.d[0]) {\r\n external = false;\r\n x = divide(x, y, 0, rm, 1).times(y);\r\n external = true;\r\n finalise(x);\r\n\r\n // If y is zero, return zero with the sign of x.\r\n } else {\r\n y.s = x.s;\r\n x = y;\r\n }\r\n\r\n return x;\r\n};\r\n\r\n\r\n/*\r\n * Return the value of this Decimal converted to a number primitive.\r\n * Zero keeps its sign.\r\n *\r\n */\r\nP.toNumber = function () {\r\n return +this;\r\n};\r\n\r\n\r\n/*\r\n * Return a string representing the value of this Decimal in base 8, round to `sd` significant\r\n * digits using rounding mode `rm`.\r\n *\r\n * If the optional `sd` argument is present then return binary exponential notation.\r\n *\r\n * [sd] {number} Significant digits. Integer, 1 to MAX_DIGITS inclusive.\r\n * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.\r\n *\r\n */\r\nP.toOctal = function (sd, rm) {\r\n return toStringBinary(this, 8, sd, rm);\r\n};\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is the value of this Decimal raised to the power `y`, rounded\r\n * to `precision` significant digits using rounding mode `rounding`.\r\n *\r\n * ECMAScript compliant.\r\n *\r\n * pow(x, NaN) = NaN\r\n * pow(x, ±0) = 1\r\n\r\n * pow(NaN, non-zero) = NaN\r\n * pow(abs(x) > 1, +Infinity) = +Infinity\r\n * pow(abs(x) > 1, -Infinity) = +0\r\n * pow(abs(x) == 1, ±Infinity) = NaN\r\n * pow(abs(x) < 1, +Infinity) = +0\r\n * pow(abs(x) < 1, -Infinity) = +Infinity\r\n * pow(+Infinity, y > 0) = +Infinity\r\n * pow(+Infinity, y < 0) = +0\r\n * pow(-Infinity, odd integer > 0) = -Infinity\r\n * pow(-Infinity, even integer > 0) = +Infinity\r\n * pow(-Infinity, odd integer < 0) = -0\r\n * pow(-Infinity, even integer < 0) = +0\r\n * pow(+0, y > 0) = +0\r\n * pow(+0, y < 0) = +Infinity\r\n * pow(-0, odd integer > 0) = -0\r\n * pow(-0, even integer > 0) = +0\r\n * pow(-0, odd integer < 0) = -Infinity\r\n * pow(-0, even integer < 0) = +Infinity\r\n * pow(finite x < 0, finite non-integer) = NaN\r\n *\r\n * For non-integer or very large exponents pow(x, y) is calculated using\r\n *\r\n * x^y = exp(y*ln(x))\r\n *\r\n * Assuming the first 15 rounding digits are each equally likely to be any digit 0-9, the\r\n * probability of an incorrectly rounded result\r\n * P([49]9{14} | [50]0{14}) = 2 * 0.2 * 10^-14 = 4e-15 = 1/2.5e+14\r\n * i.e. 1 in 250,000,000,000,000\r\n *\r\n * If a result is incorrectly rounded the maximum error will be 1 ulp (unit in last place).\r\n *\r\n * y {number|string|Decimal} The power to which to raise this Decimal.\r\n *\r\n */\r\nP.toPower = P.pow = function (y) {\r\n var e, k, pr, r, rm, s,\r\n x = this,\r\n Ctor = x.constructor,\r\n yn = +(y = new Ctor(y));\r\n\r\n // Either ±Infinity, NaN or ±0?\r\n if (!x.d || !y.d || !x.d[0] || !y.d[0]) return new Ctor(mathpow(+x, yn));\r\n\r\n x = new Ctor(x);\r\n\r\n if (x.eq(1)) return x;\r\n\r\n pr = Ctor.precision;\r\n rm = Ctor.rounding;\r\n\r\n if (y.eq(1)) return finalise(x, pr, rm);\r\n\r\n // y exponent\r\n e = mathfloor(y.e / LOG_BASE);\r\n\r\n // If y is a small integer use the 'exponentiation by squaring' algorithm.\r\n if (e >= y.d.length - 1 && (k = yn < 0 ? -yn : yn) <= MAX_SAFE_INTEGER) {\r\n r = intPow(Ctor, x, k, pr);\r\n return y.s < 0 ? new Ctor(1).div(r) : finalise(r, pr, rm);\r\n }\r\n\r\n s = x.s;\r\n\r\n // if x is negative\r\n if (s < 0) {\r\n\r\n // if y is not an integer\r\n if (e < y.d.length - 1) return new Ctor(NaN);\r\n\r\n // Result is positive if x is negative and the last digit of integer y is even.\r\n if ((y.d[e] & 1) == 0) s = 1;\r\n\r\n // if x.eq(-1)\r\n if (x.e == 0 && x.d[0] == 1 && x.d.length == 1) {\r\n x.s = s;\r\n return x;\r\n }\r\n }\r\n\r\n // Estimate result exponent.\r\n // x^y = 10^e, where e = y * log10(x)\r\n // log10(x) = log10(x_significand) + x_exponent\r\n // log10(x_significand) = ln(x_significand) / ln(10)\r\n k = mathpow(+x, yn);\r\n e = k == 0 || !isFinite(k)\r\n ? mathfloor(yn * (Math.log('0.' + digitsToString(x.d)) / Math.LN10 + x.e + 1))\r\n : new Ctor(k + '').e;\r\n\r\n // Exponent estimate may be incorrect e.g. x: 0.999999999999999999, y: 2.29, e: 0, r.e: -1.\r\n\r\n // Overflow/underflow?\r\n if (e > Ctor.maxE + 1 || e < Ctor.minE - 1) return new Ctor(e > 0 ? s / 0 : 0);\r\n\r\n external = false;\r\n Ctor.rounding = x.s = 1;\r\n\r\n // Estimate the extra guard digits needed to ensure five correct rounding digits from\r\n // naturalLogarithm(x). Example of failure without these extra digits (precision: 10):\r\n // new Decimal(2.32456).pow('2087987436534566.46411')\r\n // should be 1.162377823e+764914905173815, but is 1.162355823e+764914905173815\r\n k = Math.min(12, (e + '').length);\r\n\r\n // r = x^y = exp(y*ln(x))\r\n r = naturalExponential(y.times(naturalLogarithm(x, pr + k)), pr);\r\n\r\n // r may be Infinity, e.g. (0.9999999999999999).pow(-1e+40)\r\n if (r.d) {\r\n\r\n // Truncate to the required precision plus five rounding digits.\r\n r = finalise(r, pr + 5, 1);\r\n\r\n // If the rounding digits are [49]9999 or [50]0000 increase the precision by 10 and recalculate\r\n // the result.\r\n if (checkRoundingDigits(r.d, pr, rm)) {\r\n e = pr + 10;\r\n\r\n // Truncate to the increased precision plus five rounding digits.\r\n r = finalise(naturalExponential(y.times(naturalLogarithm(x, e + k)), e), e + 5, 1);\r\n\r\n // Check for 14 nines from the 2nd rounding digit (the first rounding digit may be 4 or 9).\r\n if (+digitsToString(r.d).slice(pr + 1, pr + 15) + 1 == 1e14) {\r\n r = finalise(r, pr + 1, 0);\r\n }\r\n }\r\n }\r\n\r\n r.s = s;\r\n external = true;\r\n Ctor.rounding = rm;\r\n\r\n return finalise(r, pr, rm);\r\n};\r\n\r\n\r\n/*\r\n * Return a string representing the value of this Decimal rounded to `sd` significant digits\r\n * using rounding mode `rounding`.\r\n *\r\n * Return exponential notation if `sd` is less than the number of digits necessary to represent\r\n * the integer part of the value in normal notation.\r\n *\r\n * [sd] {number} Significant digits. Integer, 1 to MAX_DIGITS inclusive.\r\n * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.\r\n *\r\n */\r\nP.toPrecision = function (sd, rm) {\r\n var str,\r\n x = this,\r\n Ctor = x.constructor;\r\n\r\n if (sd === void 0) {\r\n str = finiteToString(x, x.e <= Ctor.toExpNeg || x.e >= Ctor.toExpPos);\r\n } else {\r\n checkInt32(sd, 1, MAX_DIGITS);\r\n\r\n if (rm === void 0) rm = Ctor.rounding;\r\n else checkInt32(rm, 0, 8);\r\n\r\n x = finalise(new Ctor(x), sd, rm);\r\n str = finiteToString(x, sd <= x.e || x.e <= Ctor.toExpNeg, sd);\r\n }\r\n\r\n return x.isNeg() && !x.isZero() ? '-' + str : str;\r\n};\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is the value of this Decimal rounded to a maximum of `sd`\r\n * significant digits using rounding mode `rm`, or to `precision` and `rounding` respectively if\r\n * omitted.\r\n *\r\n * [sd] {number} Significant digits. Integer, 1 to MAX_DIGITS inclusive.\r\n * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.\r\n *\r\n * 'toSD() digits out of range: {sd}'\r\n * 'toSD() digits not an integer: {sd}'\r\n * 'toSD() rounding mode not an integer: {rm}'\r\n * 'toSD() rounding mode out of range: {rm}'\r\n *\r\n */\r\nP.toSignificantDigits = P.toSD = function (sd, rm) {\r\n var x = this,\r\n Ctor = x.constructor;\r\n\r\n if (sd === void 0) {\r\n sd = Ctor.precision;\r\n rm = Ctor.rounding;\r\n } else {\r\n checkInt32(sd, 1, MAX_DIGITS);\r\n\r\n if (rm === void 0) rm = Ctor.rounding;\r\n else checkInt32(rm, 0, 8);\r\n }\r\n\r\n return finalise(new Ctor(x), sd, rm);\r\n};\r\n\r\n\r\n/*\r\n * Return a string representing the value of this Decimal.\r\n *\r\n * Return exponential notation if this Decimal has a positive exponent equal to or greater than\r\n * `toExpPos`, or a negative exponent equal to or less than `toExpNeg`.\r\n *\r\n */\r\nP.toString = function () {\r\n var x = this,\r\n Ctor = x.constructor,\r\n str = finiteToString(x, x.e <= Ctor.toExpNeg || x.e >= Ctor.toExpPos);\r\n\r\n return x.isNeg() && !x.isZero() ? '-' + str : str;\r\n};\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is the value of this Decimal truncated to a whole number.\r\n *\r\n */\r\nP.truncated = P.trunc = function () {\r\n return finalise(new this.constructor(this), this.e + 1, 1);\r\n};\r\n\r\n\r\n/*\r\n * Return a string representing the value of this Decimal.\r\n * Unlike `toString`, negative zero will include the minus sign.\r\n *\r\n */\r\nP.valueOf = P.toJSON = function () {\r\n var x = this,\r\n Ctor = x.constructor,\r\n str = finiteToString(x, x.e <= Ctor.toExpNeg || x.e >= Ctor.toExpPos);\r\n\r\n return x.isNeg() ? '-' + str : str;\r\n};\r\n\r\n\r\n// Helper functions for Decimal.prototype (P) and/or Decimal methods, and their callers.\r\n\r\n\r\n/*\r\n * digitsToString P.cubeRoot, P.logarithm, P.squareRoot, P.toFraction, P.toPower,\r\n * finiteToString, naturalExponential, naturalLogarithm\r\n * checkInt32 P.toDecimalPlaces, P.toExponential, P.toFixed, P.toNearest,\r\n * P.toPrecision, P.toSignificantDigits, toStringBinary, random\r\n * checkRoundingDigits P.logarithm, P.toPower, naturalExponential, naturalLogarithm\r\n * convertBase toStringBinary, parseOther\r\n * cos P.cos\r\n * divide P.atanh, P.cubeRoot, P.dividedBy, P.dividedToIntegerBy,\r\n * P.logarithm, P.modulo, P.squareRoot, P.tan, P.tanh, P.toFraction,\r\n * P.toNearest, toStringBinary, naturalExponential, naturalLogarithm,\r\n * taylorSeries, atan2, parseOther\r\n * finalise P.absoluteValue, P.atan, P.atanh, P.ceil, P.cos, P.cosh,\r\n * P.cubeRoot, P.dividedToIntegerBy, P.floor, P.logarithm, P.minus,\r\n * P.modulo, P.negated, P.plus, P.round, P.sin, P.sinh, P.squareRoot,\r\n * P.tan, P.times, P.toDecimalPlaces, P.toExponential, P.toFixed,\r\n * P.toNearest, P.toPower, P.toPrecision, P.toSignificantDigits,\r\n * P.truncated, divide, getLn10, getPi, naturalExponential,\r\n * naturalLogarithm, ceil, floor, round, trunc\r\n * finiteToString P.toExponential, P.toFixed, P.toPrecision, P.toString, P.valueOf,\r\n * toStringBinary\r\n * getBase10Exponent P.minus, P.plus, P.times, parseOther\r\n * getLn10 P.logarithm, naturalLogarithm\r\n * getPi P.acos, P.asin, P.atan, toLessThanHalfPi, atan2\r\n * getPrecision P.precision, P.toFraction\r\n * getZeroString digitsToString, finiteToString\r\n * intPow P.toPower, parseOther\r\n * isOdd toLessThanHalfPi\r\n * maxOrMin max, min\r\n * naturalExponential P.naturalExponential, P.toPower\r\n * naturalLogarithm P.acosh, P.asinh, P.atanh, P.logarithm, P.naturalLogarithm,\r\n * P.toPower, naturalExponential\r\n * nonFiniteToString finiteToString, toStringBinary\r\n * parseDecimal Decimal\r\n * parseOther Decimal\r\n * sin P.sin\r\n * taylorSeries P.cosh, P.sinh, cos, sin\r\n * toLessThanHalfPi P.cos, P.sin\r\n * toStringBinary P.toBinary, P.toHexadecimal, P.toOctal\r\n * truncate intPow\r\n *\r\n * Throws: P.logarithm, P.precision, P.toFraction, checkInt32, getLn10, getPi,\r\n * naturalLogarithm, config, parseOther, random, Decimal\r\n */\r\n\r\n\r\nfunction digitsToString(d) {\r\n var i, k, ws,\r\n indexOfLastWord = d.length - 1,\r\n str = '',\r\n w = d[0];\r\n\r\n if (indexOfLastWord > 0) {\r\n str += w;\r\n for (i = 1; i < indexOfLastWord; i++) {\r\n ws = d[i] + '';\r\n k = LOG_BASE - ws.length;\r\n if (k) str += getZeroString(k);\r\n str += ws;\r\n }\r\n\r\n w = d[i];\r\n ws = w + '';\r\n k = LOG_BASE - ws.length;\r\n if (k) str += getZeroString(k);\r\n } else if (w === 0) {\r\n return '0';\r\n }\r\n\r\n // Remove trailing zeros of last w.\r\n for (; w % 10 === 0;) w /= 10;\r\n\r\n return str + w;\r\n}\r\n\r\n\r\nfunction checkInt32(i, min, max) {\r\n if (i !== ~~i || i < min || i > max) {\r\n throw Error(invalidArgument + i);\r\n }\r\n}\r\n\r\n\r\n/*\r\n * Check 5 rounding digits if `repeating` is null, 4 otherwise.\r\n * `repeating == null` if caller is `log` or `pow`,\r\n * `repeating != null` if caller is `naturalLogarithm` or `naturalExponential`.\r\n */\r\nfunction checkRoundingDigits(d, i, rm, repeating) {\r\n var di, k, r, rd;\r\n\r\n // Get the length of the first word of the array d.\r\n for (k = d[0]; k >= 10; k /= 10) --i;\r\n\r\n // Is the rounding digit in the first word of d?\r\n if (--i < 0) {\r\n i += LOG_BASE;\r\n di = 0;\r\n } else {\r\n di = Math.ceil((i + 1) / LOG_BASE);\r\n i %= LOG_BASE;\r\n }\r\n\r\n // i is the index (0 - 6) of the rounding digit.\r\n // E.g. if within the word 3487563 the first rounding digit is 5,\r\n // then i = 4, k = 1000, rd = 3487563 % 1000 = 563\r\n k = mathpow(10, LOG_BASE - i);\r\n rd = d[di] % k | 0;\r\n\r\n if (repeating == null) {\r\n if (i < 3) {\r\n if (i == 0) rd = rd / 100 | 0;\r\n else if (i == 1) rd = rd / 10 | 0;\r\n r = rm < 4 && rd == 99999 || rm > 3 && rd == 49999 || rd == 50000 || rd == 0;\r\n } else {\r\n r = (rm < 4 && rd + 1 == k || rm > 3 && rd + 1 == k / 2) &&\r\n (d[di + 1] / k / 100 | 0) == mathpow(10, i - 2) - 1 ||\r\n (rd == k / 2 || rd == 0) && (d[di + 1] / k / 100 | 0) == 0;\r\n }\r\n } else {\r\n if (i < 4) {\r\n if (i == 0) rd = rd / 1000 | 0;\r\n else if (i == 1) rd = rd / 100 | 0;\r\n else if (i == 2) rd = rd / 10 | 0;\r\n r = (repeating || rm < 4) && rd == 9999 || !repeating && rm > 3 && rd == 4999;\r\n } else {\r\n r = ((repeating || rm < 4) && rd + 1 == k ||\r\n (!repeating && rm > 3) && rd + 1 == k / 2) &&\r\n (d[di + 1] / k / 1000 | 0) == mathpow(10, i - 3) - 1;\r\n }\r\n }\r\n\r\n return r;\r\n}\r\n\r\n\r\n// Convert string of `baseIn` to an array of numbers of `baseOut`.\r\n// Eg. convertBase('255', 10, 16) returns [15, 15].\r\n// Eg. convertBase('ff', 16, 10) returns [2, 5, 5].\r\nfunction convertBase(str, baseIn, baseOut) {\r\n var j,\r\n arr = [0],\r\n arrL,\r\n i = 0,\r\n strL = str.length;\r\n\r\n for (; i < strL;) {\r\n for (arrL = arr.length; arrL--;) arr[arrL] *= baseIn;\r\n arr[0] += NUMERALS.indexOf(str.charAt(i++));\r\n for (j = 0; j < arr.length; j++) {\r\n if (arr[j] > baseOut - 1) {\r\n if (arr[j + 1] === void 0) arr[j + 1] = 0;\r\n arr[j + 1] += arr[j] / baseOut | 0;\r\n arr[j] %= baseOut;\r\n }\r\n }\r\n }\r\n\r\n return arr.reverse();\r\n}\r\n\r\n\r\n/*\r\n * cos(x) = 1 - x^2/2! + x^4/4! - ...\r\n * |x| < pi/2\r\n *\r\n */\r\nfunction cosine(Ctor, x) {\r\n var k, len, y;\r\n\r\n if (x.isZero()) return x;\r\n\r\n // Argument reduction: cos(4x) = 8*(cos^4(x) - cos^2(x)) + 1\r\n // i.e. cos(x) = 8*(cos^4(x/4) - cos^2(x/4)) + 1\r\n\r\n // Estimate the optimum number of times to use the argument reduction.\r\n len = x.d.length;\r\n if (len < 32) {\r\n k = Math.ceil(len / 3);\r\n y = (1 / tinyPow(4, k)).toString();\r\n } else {\r\n k = 16;\r\n y = '2.3283064365386962890625e-10';\r\n }\r\n\r\n Ctor.precision += k;\r\n\r\n x = taylorSeries(Ctor, 1, x.times(y), new Ctor(1));\r\n\r\n // Reverse argument reduction\r\n for (var i = k; i--;) {\r\n var cos2x = x.times(x);\r\n x = cos2x.times(cos2x).minus(cos2x).times(8).plus(1);\r\n }\r\n\r\n Ctor.precision -= k;\r\n\r\n return x;\r\n}\r\n\r\n\r\n/*\r\n * Perform division in the specified base.\r\n */\r\nvar divide = (function () {\r\n\r\n // Assumes non-zero x and k, and hence non-zero result.\r\n function multiplyInteger(x, k, base) {\r\n var temp,\r\n carry = 0,\r\n i = x.length;\r\n\r\n for (x = x.slice(); i--;) {\r\n temp = x[i] * k + carry;\r\n x[i] = temp % base | 0;\r\n carry = temp / base | 0;\r\n }\r\n\r\n if (carry) x.unshift(carry);\r\n\r\n return x;\r\n }\r\n\r\n function compare(a, b, aL, bL) {\r\n var i, r;\r\n\r\n if (aL != bL) {\r\n r = aL > bL ? 1 : -1;\r\n } else {\r\n for (i = r = 0; i < aL; i++) {\r\n if (a[i] != b[i]) {\r\n r = a[i] > b[i] ? 1 : -1;\r\n break;\r\n }\r\n }\r\n }\r\n\r\n return r;\r\n }\r\n\r\n function subtract(a, b, aL, base) {\r\n var i = 0;\r\n\r\n // Subtract b from a.\r\n for (; aL--;) {\r\n a[aL] -= i;\r\n i = a[aL] < b[aL] ? 1 : 0;\r\n a[aL] = i * base + a[aL] - b[aL];\r\n }\r\n\r\n // Remove leading zeros.\r\n for (; !a[0] && a.length > 1;) a.shift();\r\n }\r\n\r\n return function (x, y, pr, rm, dp, base) {\r\n var cmp, e, i, k, logBase, more, prod, prodL, q, qd, rem, remL, rem0, sd, t, xi, xL, yd0,\r\n yL, yz,\r\n Ctor = x.constructor,\r\n sign = x.s == y.s ? 1 : -1,\r\n xd = x.d,\r\n yd = y.d;\r\n\r\n // Either NaN, Infinity or 0?\r\n if (!xd || !xd[0] || !yd || !yd[0]) {\r\n\r\n return new Ctor(// Return NaN if either NaN, or both Infinity or 0.\r\n !x.s || !y.s || (xd ? yd && xd[0] == yd[0] : !yd) ? NaN :\r\n\r\n // Return ±0 if x is 0 or y is ±Infinity, or return ±Infinity as y is 0.\r\n xd && xd[0] == 0 || !yd ? sign * 0 : sign / 0);\r\n }\r\n\r\n if (base) {\r\n logBase = 1;\r\n e = x.e - y.e;\r\n } else {\r\n base = BASE;\r\n logBase = LOG_BASE;\r\n e = mathfloor(x.e / logBase) - mathfloor(y.e / logBase);\r\n }\r\n\r\n yL = yd.length;\r\n xL = xd.length;\r\n q = new Ctor(sign);\r\n qd = q.d = [];\r\n\r\n // Result exponent may be one less than e.\r\n // The digit array of a Decimal from toStringBinary may have trailing zeros.\r\n for (i = 0; yd[i] == (xd[i] || 0); i++);\r\n\r\n if (yd[i] > (xd[i] || 0)) e--;\r\n\r\n if (pr == null) {\r\n sd = pr = Ctor.precision;\r\n rm = Ctor.rounding;\r\n } else if (dp) {\r\n sd = pr + (x.e - y.e) + 1;\r\n } else {\r\n sd = pr;\r\n }\r\n\r\n if (sd < 0) {\r\n qd.push(1);\r\n more = true;\r\n } else {\r\n\r\n // Convert precision in number of base 10 digits to base 1e7 digits.\r\n sd = sd / logBase + 2 | 0;\r\n i = 0;\r\n\r\n // divisor < 1e7\r\n if (yL == 1) {\r\n k = 0;\r\n yd = yd[0];\r\n sd++;\r\n\r\n // k is the carry.\r\n for (; (i < xL || k) && sd--; i++) {\r\n t = k * base + (xd[i] || 0);\r\n qd[i] = t / yd | 0;\r\n k = t % yd | 0;\r\n }\r\n\r\n more = k || i < xL;\r\n\r\n // divisor >= 1e7\r\n } else {\r\n\r\n // Normalise xd and yd so highest order digit of yd is >= base/2\r\n k = base / (yd[0] + 1) | 0;\r\n\r\n if (k > 1) {\r\n yd = multiplyInteger(yd, k, base);\r\n xd = multiplyInteger(xd, k, base);\r\n yL = yd.length;\r\n xL = xd.length;\r\n }\r\n\r\n xi = yL;\r\n rem = xd.slice(0, yL);\r\n remL = rem.length;\r\n\r\n // Add zeros to make remainder as long as divisor.\r\n for (; remL < yL;) rem[remL++] = 0;\r\n\r\n yz = yd.slice();\r\n yz.unshift(0);\r\n yd0 = yd[0];\r\n\r\n if (yd[1] >= base / 2) ++yd0;\r\n\r\n do {\r\n k = 0;\r\n\r\n // Compare divisor and remainder.\r\n cmp = compare(yd, rem, yL, remL);\r\n\r\n // If divisor < remainder.\r\n if (cmp < 0) {\r\n\r\n // Calculate trial digit, k.\r\n rem0 = rem[0];\r\n if (yL != remL) rem0 = rem0 * base + (rem[1] || 0);\r\n\r\n // k will be how many times the divisor goes into the current remainder.\r\n k = rem0 / yd0 | 0;\r\n\r\n // Algorithm:\r\n // 1. product = divisor * trial digit (k)\r\n // 2. if product > remainder: product -= divisor, k--\r\n // 3. remainder -= product\r\n // 4. if product was < remainder at 2:\r\n // 5. compare new remainder and divisor\r\n // 6. If remainder > divisor: remainder -= divisor, k++\r\n\r\n if (k > 1) {\r\n if (k >= base) k = base - 1;\r\n\r\n // product = divisor * trial digit.\r\n prod = multiplyInteger(yd, k, base);\r\n prodL = prod.length;\r\n remL = rem.length;\r\n\r\n // Compare product and remainder.\r\n cmp = compare(prod, rem, prodL, remL);\r\n\r\n // product > remainder.\r\n if (cmp == 1) {\r\n k--;\r\n\r\n // Subtract divisor from product.\r\n subtract(prod, yL < prodL ? yz : yd, prodL, base);\r\n }\r\n } else {\r\n\r\n // cmp is -1.\r\n // If k is 0, there is no need to compare yd and rem again below, so change cmp to 1\r\n // to avoid it. If k is 1 there is a need to compare yd and rem again below.\r\n if (k == 0) cmp = k = 1;\r\n prod = yd.slice();\r\n }\r\n\r\n prodL = prod.length;\r\n if (prodL < remL) prod.unshift(0);\r\n\r\n // Subtract product from remainder.\r\n subtract(rem, prod, remL, base);\r\n\r\n // If product was < previous remainder.\r\n if (cmp == -1) {\r\n remL = rem.length;\r\n\r\n // Compare divisor and new remainder.\r\n cmp = compare(yd, rem, yL, remL);\r\n\r\n // If divisor < new remainder, subtract divisor from remainder.\r\n if (cmp < 1) {\r\n k++;\r\n\r\n // Subtract divisor from remainder.\r\n subtract(rem, yL < remL ? yz : yd, remL, base);\r\n }\r\n }\r\n\r\n remL = rem.length;\r\n } else if (cmp === 0) {\r\n k++;\r\n rem = [0];\r\n } // if cmp === 1, k will be 0\r\n\r\n // Add the next digit, k, to the result array.\r\n qd[i++] = k;\r\n\r\n // Update the remainder.\r\n if (cmp && rem[0]) {\r\n rem[remL++] = xd[xi] || 0;\r\n } else {\r\n rem = [xd[xi]];\r\n remL = 1;\r\n }\r\n\r\n } while ((xi++ < xL || rem[0] !== void 0) && sd--);\r\n\r\n more = rem[0] !== void 0;\r\n }\r\n\r\n // Leading zero?\r\n if (!qd[0]) qd.shift();\r\n }\r\n\r\n // logBase is 1 when divide is being used for base conversion.\r\n if (logBase == 1) {\r\n q.e = e;\r\n inexact = more;\r\n } else {\r\n\r\n // To calculate q.e, first get the number of digits of qd[0].\r\n for (i = 1, k = qd[0]; k >= 10; k /= 10) i++;\r\n q.e = i + e * logBase - 1;\r\n\r\n finalise(q, dp ? pr + q.e + 1 : pr, rm, more);\r\n }\r\n\r\n return q;\r\n };\r\n})();\r\n\r\n\r\n/*\r\n * Round `x` to `sd` significant digits using rounding mode `rm`.\r\n * Check for over/under-flow.\r\n */\r\n function finalise(x, sd, rm, isTruncated) {\r\n var digits, i, j, k, rd, roundUp, w, xd, xdi,\r\n Ctor = x.constructor;\r\n\r\n // Don't round if sd is null or undefined.\r\n out: if (sd != null) {\r\n xd = x.d;\r\n\r\n // Infinity/NaN.\r\n if (!xd) return x;\r\n\r\n // rd: the rounding digit, i.e. the digit after the digit that may be rounded up.\r\n // w: the word of xd containing rd, a base 1e7 number.\r\n // xdi: the index of w within xd.\r\n // digits: the number of digits of w.\r\n // i: what would be the index of rd within w if all the numbers were 7 digits long (i.e. if\r\n // they had leading zeros)\r\n // j: if > 0, the actual index of rd within w (if < 0, rd is a leading zero).\r\n\r\n // Get the length of the first word of the digits array xd.\r\n for (digits = 1, k = xd[0]; k >= 10; k /= 10) digits++;\r\n i = sd - digits;\r\n\r\n // Is the rounding digit in the first word of xd?\r\n if (i < 0) {\r\n i += LOG_BASE;\r\n j = sd;\r\n w = xd[xdi = 0];\r\n\r\n // Get the rounding digit at index j of w.\r\n rd = w / mathpow(10, digits - j - 1) % 10 | 0;\r\n } else {\r\n xdi = Math.ceil((i + 1) / LOG_BASE);\r\n k = xd.length;\r\n if (xdi >= k) {\r\n if (isTruncated) {\r\n\r\n // Needed by `naturalExponential`, `naturalLogarithm` and `squareRoot`.\r\n for (; k++ <= xdi;) xd.push(0);\r\n w = rd = 0;\r\n digits = 1;\r\n i %= LOG_BASE;\r\n j = i - LOG_BASE + 1;\r\n } else {\r\n break out;\r\n }\r\n } else {\r\n w = k = xd[xdi];\r\n\r\n // Get the number of digits of w.\r\n for (digits = 1; k >= 10; k /= 10) digits++;\r\n\r\n // Get the index of rd within w.\r\n i %= LOG_BASE;\r\n\r\n // Get the index of rd within w, adjusted for leading zeros.\r\n // The number of leading zeros of w is given by LOG_BASE - digits.\r\n j = i - LOG_BASE + digits;\r\n\r\n // Get the rounding digit at index j of w.\r\n rd = j < 0 ? 0 : w / mathpow(10, digits - j - 1) % 10 | 0;\r\n }\r\n }\r\n\r\n // Are there any non-zero digits after the rounding digit?\r\n isTruncated = isTruncated || sd < 0 ||\r\n xd[xdi + 1] !== void 0 || (j < 0 ? w : w % mathpow(10, digits - j - 1));\r\n\r\n // The expression `w % mathpow(10, digits - j - 1)` returns all the digits of w to the right\r\n // of the digit at (left-to-right) index j, e.g. if w is 908714 and j is 2, the expression\r\n // will give 714.\r\n\r\n roundUp = rm < 4\r\n ? (rd || isTruncated) && (rm == 0 || rm == (x.s < 0 ? 3 : 2))\r\n : rd > 5 || rd == 5 && (rm == 4 || isTruncated || rm == 6 &&\r\n\r\n // Check whether the digit to the left of the rounding digit is odd.\r\n ((i > 0 ? j > 0 ? w / mathpow(10, digits - j) : 0 : xd[xdi - 1]) % 10) & 1 ||\r\n rm == (x.s < 0 ? 8 : 7));\r\n\r\n if (sd < 1 || !xd[0]) {\r\n xd.length = 0;\r\n if (roundUp) {\r\n\r\n // Convert sd to decimal places.\r\n sd -= x.e + 1;\r\n\r\n // 1, 0.1, 0.01, 0.001, 0.0001 etc.\r\n xd[0] = mathpow(10, (LOG_BASE - sd % LOG_BASE) % LOG_BASE);\r\n x.e = -sd || 0;\r\n } else {\r\n\r\n // Zero.\r\n xd[0] = x.e = 0;\r\n }\r\n\r\n return x;\r\n }\r\n\r\n // Remove excess digits.\r\n if (i == 0) {\r\n xd.length = xdi;\r\n k = 1;\r\n xdi--;\r\n } else {\r\n xd.length = xdi + 1;\r\n k = mathpow(10, LOG_BASE - i);\r\n\r\n // E.g. 56700 becomes 56000 if 7 is the rounding digit.\r\n // j > 0 means i > number of leading zeros of w.\r\n xd[xdi] = j > 0 ? (w / mathpow(10, digits - j) % mathpow(10, j) | 0) * k : 0;\r\n }\r\n\r\n if (roundUp) {\r\n for (;;) {\r\n\r\n // Is the digit to be rounded up in the first word of xd?\r\n if (xdi == 0) {\r\n\r\n // i will be the length of xd[0] before k is added.\r\n for (i = 1, j = xd[0]; j >= 10; j /= 10) i++;\r\n j = xd[0] += k;\r\n for (k = 1; j >= 10; j /= 10) k++;\r\n\r\n // if i != k the length has increased.\r\n if (i != k) {\r\n x.e++;\r\n if (xd[0] == BASE) xd[0] = 1;\r\n }\r\n\r\n break;\r\n } else {\r\n xd[xdi] += k;\r\n if (xd[xdi] != BASE) break;\r\n xd[xdi--] = 0;\r\n k = 1;\r\n }\r\n }\r\n }\r\n\r\n // Remove trailing zeros.\r\n for (i = xd.length; xd[--i] === 0;) xd.pop();\r\n }\r\n\r\n if (external) {\r\n\r\n // Overflow?\r\n if (x.e > Ctor.maxE) {\r\n\r\n // Infinity.\r\n x.d = null;\r\n x.e = NaN;\r\n\r\n // Underflow?\r\n } else if (x.e < Ctor.minE) {\r\n\r\n // Zero.\r\n x.e = 0;\r\n x.d = [0];\r\n // Ctor.underflow = true;\r\n } // else Ctor.underflow = false;\r\n }\r\n\r\n return x;\r\n}\r\n\r\n\r\nfunction finiteToString(x, isExp, sd) {\r\n if (!x.isFinite()) return nonFiniteToString(x);\r\n var k,\r\n e = x.e,\r\n str = digitsToString(x.d),\r\n len = str.length;\r\n\r\n if (isExp) {\r\n if (sd && (k = sd - len) > 0) {\r\n str = str.charAt(0) + '.' + str.slice(1) + getZeroString(k);\r\n } else if (len > 1) {\r\n str = str.charAt(0) + '.' + str.slice(1);\r\n }\r\n\r\n str = str + (x.e < 0 ? 'e' : 'e+') + x.e;\r\n } else if (e < 0) {\r\n str = '0.' + getZeroString(-e - 1) + str;\r\n if (sd && (k = sd - len) > 0) str += getZeroString(k);\r\n } else if (e >= len) {\r\n str += getZeroString(e + 1 - len);\r\n if (sd && (k = sd - e - 1) > 0) str = str + '.' + getZeroString(k);\r\n } else {\r\n if ((k = e + 1) < len) str = str.slice(0, k) + '.' + str.slice(k);\r\n if (sd && (k = sd - len) > 0) {\r\n if (e + 1 === len) str += '.';\r\n str += getZeroString(k);\r\n }\r\n }\r\n\r\n return str;\r\n}\r\n\r\n\r\n// Calculate the base 10 exponent from the base 1e7 exponent.\r\nfunction getBase10Exponent(digits, e) {\r\n var w = digits[0];\r\n\r\n // Add the number of digits of the first word of the digits array.\r\n for ( e *= LOG_BASE; w >= 10; w /= 10) e++;\r\n return e;\r\n}\r\n\r\n\r\nfunction getLn10(Ctor, sd, pr) {\r\n if (sd > LN10_PRECISION) {\r\n\r\n // Reset global state in case the exception is caught.\r\n external = true;\r\n if (pr) Ctor.precision = pr;\r\n throw Error(precisionLimitExceeded);\r\n }\r\n return finalise(new Ctor(LN10), sd, 1, true);\r\n}\r\n\r\n\r\nfunction getPi(Ctor, sd, rm) {\r\n if (sd > PI_PRECISION) throw Error(precisionLimitExceeded);\r\n return finalise(new Ctor(PI), sd, rm, true);\r\n}\r\n\r\n\r\nfunction getPrecision(digits) {\r\n var w = digits.length - 1,\r\n len = w * LOG_BASE + 1;\r\n\r\n w = digits[w];\r\n\r\n // If non-zero...\r\n if (w) {\r\n\r\n // Subtract the number of trailing zeros of the last word.\r\n for (; w % 10 == 0; w /= 10) len--;\r\n\r\n // Add the number of digits of the first word.\r\n for (w = digits[0]; w >= 10; w /= 10) len++;\r\n }\r\n\r\n return len;\r\n}\r\n\r\n\r\nfunction getZeroString(k) {\r\n var zs = '';\r\n for (; k--;) zs += '0';\r\n return zs;\r\n}\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is the value of Decimal `x` to the power `n`, where `n` is an\r\n * integer of type number.\r\n *\r\n * Implements 'exponentiation by squaring'. Called by `pow` and `parseOther`.\r\n *\r\n */\r\nfunction intPow(Ctor, x, n, pr) {\r\n var isTruncated,\r\n r = new Ctor(1),\r\n\r\n // Max n of 9007199254740991 takes 53 loop iterations.\r\n // Maximum digits array length; leaves [28, 34] guard digits.\r\n k = Math.ceil(pr / LOG_BASE + 4);\r\n\r\n external = false;\r\n\r\n for (;;) {\r\n if (n % 2) {\r\n r = r.times(x);\r\n if (truncate(r.d, k)) isTruncated = true;\r\n }\r\n\r\n n = mathfloor(n / 2);\r\n if (n === 0) {\r\n\r\n // To ensure correct rounding when r.d is truncated, increment the last word if it is zero.\r\n n = r.d.length - 1;\r\n if (isTruncated && r.d[n] === 0) ++r.d[n];\r\n break;\r\n }\r\n\r\n x = x.times(x);\r\n truncate(x.d, k);\r\n }\r\n\r\n external = true;\r\n\r\n return r;\r\n}\r\n\r\n\r\nfunction isOdd(n) {\r\n return n.d[n.d.length - 1] & 1;\r\n}\r\n\r\n\r\n/*\r\n * Handle `max` and `min`. `ltgt` is 'lt' or 'gt'.\r\n */\r\nfunction maxOrMin(Ctor, args, ltgt) {\r\n var y,\r\n x = new Ctor(args[0]),\r\n i = 0;\r\n\r\n for (; ++i < args.length;) {\r\n y = new Ctor(args[i]);\r\n if (!y.s) {\r\n x = y;\r\n break;\r\n } else if (x[ltgt](y)) {\r\n x = y;\r\n }\r\n }\r\n\r\n return x;\r\n}\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is the natural exponential of `x` rounded to `sd` significant\r\n * digits.\r\n *\r\n * Taylor/Maclaurin series.\r\n *\r\n * exp(x) = x^0/0! + x^1/1! + x^2/2! + x^3/3! + ...\r\n *\r\n * Argument reduction:\r\n * Repeat x = x / 32, k += 5, until |x| < 0.1\r\n * exp(x) = exp(x / 2^k)^(2^k)\r\n *\r\n * Previously, the argument was initially reduced by\r\n * exp(x) = exp(r) * 10^k where r = x - k * ln10, k = floor(x / ln10)\r\n * to first put r in the range [0, ln10], before dividing by 32 until |x| < 0.1, but this was\r\n * found to be slower than just dividing repeatedly by 32 as above.\r\n *\r\n * Max integer argument: exp('20723265836946413') = 6.3e+9000000000000000\r\n * Min integer argument: exp('-20723265836946411') = 1.2e-9000000000000000\r\n * (Math object integer min/max: Math.exp(709) = 8.2e+307, Math.exp(-745) = 5e-324)\r\n *\r\n * exp(Infinity) = Infinity\r\n * exp(-Infinity) = 0\r\n * exp(NaN) = NaN\r\n * exp(±0) = 1\r\n *\r\n * exp(x) is non-terminating for any finite, non-zero x.\r\n *\r\n * The result will always be correctly rounded.\r\n *\r\n */\r\nfunction naturalExponential(x, sd) {\r\n var denominator, guard, j, pow, sum, t, wpr,\r\n rep = 0,\r\n i = 0,\r\n k = 0,\r\n Ctor = x.constructor,\r\n rm = Ctor.rounding,\r\n pr = Ctor.precision;\r\n\r\n // 0/NaN/Infinity?\r\n if (!x.d || !x.d[0] || x.e > 17) {\r\n\r\n return new Ctor(x.d\r\n ? !x.d[0] ? 1 : x.s < 0 ? 0 : 1 / 0\r\n : x.s ? x.s < 0 ? 0 : x : 0 / 0);\r\n }\r\n\r\n if (sd == null) {\r\n external = false;\r\n wpr = pr;\r\n } else {\r\n wpr = sd;\r\n }\r\n\r\n t = new Ctor(0.03125);\r\n\r\n // while abs(x) >= 0.1\r\n while (x.e > -2) {\r\n\r\n // x = x / 2^5\r\n x = x.times(t);\r\n k += 5;\r\n }\r\n\r\n // Use 2 * log10(2^k) + 5 (empirically derived) to estimate the increase in precision\r\n // necessary to ensure the first 4 rounding digits are correct.\r\n guard = Math.log(mathpow(2, k)) / Math.LN10 * 2 + 5 | 0;\r\n wpr += guard;\r\n denominator = pow = sum = new Ctor(1);\r\n Ctor.precision = wpr;\r\n\r\n for (;;) {\r\n pow = finalise(pow.times(x), wpr, 1);\r\n denominator = denominator.times(++i);\r\n t = sum.plus(divide(pow, denominator, wpr, 1));\r\n\r\n if (digitsToString(t.d).slice(0, wpr) === digitsToString(sum.d).slice(0, wpr)) {\r\n j = k;\r\n while (j--) sum = finalise(sum.times(sum), wpr, 1);\r\n\r\n // Check to see if the first 4 rounding digits are [49]999.\r\n // If so, repeat the summation with a higher precision, otherwise\r\n // e.g. with precision: 18, rounding: 1\r\n // exp(18.404272462595034083567793919843761) = 98372560.1229999999 (should be 98372560.123)\r\n // `wpr - guard` is the index of first rounding digit.\r\n if (sd == null) {\r\n\r\n if (rep < 3 && checkRoundingDigits(sum.d, wpr - guard, rm, rep)) {\r\n Ctor.precision = wpr += 10;\r\n denominator = pow = t = new Ctor(1);\r\n i = 0;\r\n rep++;\r\n } else {\r\n return finalise(sum, Ctor.precision = pr, rm, external = true);\r\n }\r\n } else {\r\n Ctor.precision = pr;\r\n return sum;\r\n }\r\n }\r\n\r\n sum = t;\r\n }\r\n}\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is the natural logarithm of `x` rounded to `sd` significant\r\n * digits.\r\n *\r\n * ln(-n) = NaN\r\n * ln(0) = -Infinity\r\n * ln(-0) = -Infinity\r\n * ln(1) = 0\r\n * ln(Infinity) = Infinity\r\n * ln(-Infinity) = NaN\r\n * ln(NaN) = NaN\r\n *\r\n * ln(n) (n != 1) is non-terminating.\r\n *\r\n */\r\nfunction naturalLogarithm(y, sd) {\r\n var c, c0, denominator, e, numerator, rep, sum, t, wpr, x1, x2,\r\n n = 1,\r\n guard = 10,\r\n x = y,\r\n xd = x.d,\r\n Ctor = x.constructor,\r\n rm = Ctor.rounding,\r\n pr = Ctor.precision;\r\n\r\n // Is x negative or Infinity, NaN, 0 or 1?\r\n if (x.s < 0 || !xd || !xd[0] || !x.e && xd[0] == 1 && xd.length == 1) {\r\n return new Ctor(xd && !xd[0] ? -1 / 0 : x.s != 1 ? NaN : xd ? 0 : x);\r\n }\r\n\r\n if (sd == null) {\r\n external = false;\r\n wpr = pr;\r\n } else {\r\n wpr = sd;\r\n }\r\n\r\n Ctor.precision = wpr += guard;\r\n c = digitsToString(xd);\r\n c0 = c.charAt(0);\r\n\r\n if (Math.abs(e = x.e) < 1.5e15) {\r\n\r\n // Argument reduction.\r\n // The series converges faster the closer the argument is to 1, so using\r\n // ln(a^b) = b * ln(a), ln(a) = ln(a^b) / b\r\n // multiply the argument by itself until the leading digits of the significand are 7, 8, 9,\r\n // 10, 11, 12 or 13, recording the number of multiplications so the sum of the series can\r\n // later be divided by this number, then separate out the power of 10 using\r\n // ln(a*10^b) = ln(a) + b*ln(10).\r\n\r\n // max n is 21 (gives 0.9, 1.0 or 1.1) (9e15 / 21 = 4.2e14).\r\n //while (c0 < 9 && c0 != 1 || c0 == 1 && c.charAt(1) > 1) {\r\n // max n is 6 (gives 0.7 - 1.3)\r\n while (c0 < 7 && c0 != 1 || c0 == 1 && c.charAt(1) > 3) {\r\n x = x.times(y);\r\n c = digitsToString(x.d);\r\n c0 = c.charAt(0);\r\n n++;\r\n }\r\n\r\n e = x.e;\r\n\r\n if (c0 > 1) {\r\n x = new Ctor('0.' + c);\r\n e++;\r\n } else {\r\n x = new Ctor(c0 + '.' + c.slice(1));\r\n }\r\n } else {\r\n\r\n // The argument reduction method above may result in overflow if the argument y is a massive\r\n // number with exponent >= 1500000000000000 (9e15 / 6 = 1.5e15), so instead recall this\r\n // function using ln(x*10^e) = ln(x) + e*ln(10).\r\n t = getLn10(Ctor, wpr + 2, pr).times(e + '');\r\n x = naturalLogarithm(new Ctor(c0 + '.' + c.slice(1)), wpr - guard).plus(t);\r\n Ctor.precision = pr;\r\n\r\n return sd == null ? finalise(x, pr, rm, external = true) : x;\r\n }\r\n\r\n // x1 is x reduced to a value near 1.\r\n x1 = x;\r\n\r\n // Taylor series.\r\n // ln(y) = ln((1 + x)/(1 - x)) = 2(x + x^3/3 + x^5/5 + x^7/7 + ...)\r\n // where x = (y - 1)/(y + 1) (|x| < 1)\r\n sum = numerator = x = divide(x.minus(1), x.plus(1), wpr, 1);\r\n x2 = finalise(x.times(x), wpr, 1);\r\n denominator = 3;\r\n\r\n for (;;) {\r\n numerator = finalise(numerator.times(x2), wpr, 1);\r\n t = sum.plus(divide(numerator, new Ctor(denominator), wpr, 1));\r\n\r\n if (digitsToString(t.d).slice(0, wpr) === digitsToString(sum.d).slice(0, wpr)) {\r\n sum = sum.times(2);\r\n\r\n // Reverse the argument reduction. Check that e is not 0 because, besides preventing an\r\n // unnecessary calculation, -0 + 0 = +0 and to ensure correct rounding -0 needs to stay -0.\r\n if (e !== 0) sum = sum.plus(getLn10(Ctor, wpr + 2, pr).times(e + ''));\r\n sum = divide(sum, new Ctor(n), wpr, 1);\r\n\r\n // Is rm > 3 and the first 4 rounding digits 4999, or rm < 4 (or the summation has\r\n // been repeated previously) and the first 4 rounding digits 9999?\r\n // If so, restart the summation with a higher precision, otherwise\r\n // e.g. with precision: 12, rounding: 1\r\n // ln(135520028.6126091714265381533) = 18.7246299999 when it should be 18.72463.\r\n // `wpr - guard` is the index of first rounding digit.\r\n if (sd == null) {\r\n if (checkRoundingDigits(sum.d, wpr - guard, rm, rep)) {\r\n Ctor.precision = wpr += guard;\r\n t = numerator = x = divide(x1.minus(1), x1.plus(1), wpr, 1);\r\n x2 = finalise(x.times(x), wpr, 1);\r\n denominator = rep = 1;\r\n } else {\r\n return finalise(sum, Ctor.precision = pr, rm, external = true);\r\n }\r\n } else {\r\n Ctor.precision = pr;\r\n return sum;\r\n }\r\n }\r\n\r\n sum = t;\r\n denominator += 2;\r\n }\r\n}\r\n\r\n\r\n// ±Infinity, NaN.\r\nfunction nonFiniteToString(x) {\r\n // Unsigned.\r\n return String(x.s * x.s / 0);\r\n}\r\n\r\n\r\n/*\r\n * Parse the value of a new Decimal `x` from string `str`.\r\n */\r\nfunction parseDecimal(x, str) {\r\n var e, i, len;\r\n\r\n // Decimal point?\r\n if ((e = str.indexOf('.')) > -1) str = str.replace('.', '');\r\n\r\n // Exponential form?\r\n if ((i = str.search(/e/i)) > 0) {\r\n\r\n // Determine exponent.\r\n if (e < 0) e = i;\r\n e += +str.slice(i + 1);\r\n str = str.substring(0, i);\r\n } else if (e < 0) {\r\n\r\n // Integer.\r\n e = str.length;\r\n }\r\n\r\n // Determine leading zeros.\r\n for (i = 0; str.charCodeAt(i) === 48; i++);\r\n\r\n // Determine trailing zeros.\r\n for (len = str.length; str.charCodeAt(len - 1) === 48; --len);\r\n str = str.slice(i, len);\r\n\r\n if (str) {\r\n len -= i;\r\n x.e = e = e - i - 1;\r\n x.d = [];\r\n\r\n // Transform base\r\n\r\n // e is the base 10 exponent.\r\n // i is where to slice str to get the first word of the digits array.\r\n i = (e + 1) % LOG_BASE;\r\n if (e < 0) i += LOG_BASE;\r\n\r\n if (i < len) {\r\n if (i) x.d.push(+str.slice(0, i));\r\n for (len -= LOG_BASE; i < len;) x.d.push(+str.slice(i, i += LOG_BASE));\r\n str = str.slice(i);\r\n i = LOG_BASE - str.length;\r\n } else {\r\n i -= len;\r\n }\r\n\r\n for (; i--;) str += '0';\r\n x.d.push(+str);\r\n\r\n if (external) {\r\n\r\n // Overflow?\r\n if (x.e > x.constructor.maxE) {\r\n\r\n // Infinity.\r\n x.d = null;\r\n x.e = NaN;\r\n\r\n // Underflow?\r\n } else if (x.e < x.constructor.minE) {\r\n\r\n // Zero.\r\n x.e = 0;\r\n x.d = [0];\r\n // x.constructor.underflow = true;\r\n } // else x.constructor.underflow = false;\r\n }\r\n } else {\r\n\r\n // Zero.\r\n x.e = 0;\r\n x.d = [0];\r\n }\r\n\r\n return x;\r\n}\r\n\r\n\r\n/*\r\n * Parse the value of a new Decimal `x` from a string `str`, which is not a decimal value.\r\n */\r\nfunction parseOther(x, str) {\r\n var base, Ctor, divisor, i, isFloat, len, p, xd, xe;\r\n\r\n if (str.indexOf('_') > -1) {\r\n str = str.replace(/(\\d)_(?=\\d)/g, '$1');\r\n if (isDecimal.test(str)) return parseDecimal(x, str);\r\n } else if (str === 'Infinity' || str === 'NaN') {\r\n if (!+str) x.s = NaN;\r\n x.e = NaN;\r\n x.d = null;\r\n return x;\r\n }\r\n\r\n if (isHex.test(str)) {\r\n base = 16;\r\n str = str.toLowerCase();\r\n } else if (isBinary.test(str)) {\r\n base = 2;\r\n } else if (isOctal.test(str)) {\r\n base = 8;\r\n } else {\r\n throw Error(invalidArgument + str);\r\n }\r\n\r\n // Is there a binary exponent part?\r\n i = str.search(/p/i);\r\n\r\n if (i > 0) {\r\n p = +str.slice(i + 1);\r\n str = str.substring(2, i);\r\n } else {\r\n str = str.slice(2);\r\n }\r\n\r\n // Convert `str` as an integer then divide the result by `base` raised to a power such that the\r\n // fraction part will be restored.\r\n i = str.indexOf('.');\r\n isFloat = i >= 0;\r\n Ctor = x.constructor;\r\n\r\n if (isFloat) {\r\n str = str.replace('.', '');\r\n len = str.length;\r\n i = len - i;\r\n\r\n // log[10](16) = 1.2041... , log[10](88) = 1.9444....\r\n divisor = intPow(Ctor, new Ctor(base), i, i * 2);\r\n }\r\n\r\n xd = convertBase(str, base, BASE);\r\n xe = xd.length - 1;\r\n\r\n // Remove trailing zeros.\r\n for (i = xe; xd[i] === 0; --i) xd.pop();\r\n if (i < 0) return new Ctor(x.s * 0);\r\n x.e = getBase10Exponent(xd, xe);\r\n x.d = xd;\r\n external = false;\r\n\r\n // At what precision to perform the division to ensure exact conversion?\r\n // maxDecimalIntegerPartDigitCount = ceil(log[10](b) * otherBaseIntegerPartDigitCount)\r\n // log[10](2) = 0.30103, log[10](8) = 0.90309, log[10](16) = 1.20412\r\n // E.g. ceil(1.2 * 3) = 4, so up to 4 decimal digits are needed to represent 3 hex int digits.\r\n // maxDecimalFractionPartDigitCount = {Hex:4|Oct:3|Bin:1} * otherBaseFractionPartDigitCount\r\n // Therefore using 4 * the number of digits of str will always be enough.\r\n if (isFloat) x = divide(x, divisor, len * 4);\r\n\r\n // Multiply by the binary exponent part if present.\r\n if (p) x = x.times(Math.abs(p) < 54 ? mathpow(2, p) : Decimal.pow(2, p));\r\n external = true;\r\n\r\n return x;\r\n}\r\n\r\n\r\n/*\r\n * sin(x) = x - x^3/3! + x^5/5! - ...\r\n * |x| < pi/2\r\n *\r\n */\r\nfunction sine(Ctor, x) {\r\n var k,\r\n len = x.d.length;\r\n\r\n if (len < 3) {\r\n return x.isZero() ? x : taylorSeries(Ctor, 2, x, x);\r\n }\r\n\r\n // Argument reduction: sin(5x) = 16*sin^5(x) - 20*sin^3(x) + 5*sin(x)\r\n // i.e. sin(x) = 16*sin^5(x/5) - 20*sin^3(x/5) + 5*sin(x/5)\r\n // and sin(x) = sin(x/5)(5 + sin^2(x/5)(16sin^2(x/5) - 20))\r\n\r\n // Estimate the optimum number of times to use the argument reduction.\r\n k = 1.4 * Math.sqrt(len);\r\n k = k > 16 ? 16 : k | 0;\r\n\r\n x = x.times(1 / tinyPow(5, k));\r\n x = taylorSeries(Ctor, 2, x, x);\r\n\r\n // Reverse argument reduction\r\n var sin2_x,\r\n d5 = new Ctor(5),\r\n d16 = new Ctor(16),\r\n d20 = new Ctor(20);\r\n for (; k--;) {\r\n sin2_x = x.times(x);\r\n x = x.times(d5.plus(sin2_x.times(d16.times(sin2_x).minus(d20))));\r\n }\r\n\r\n return x;\r\n}\r\n\r\n\r\n// Calculate Taylor series for `cos`, `cosh`, `sin` and `sinh`.\r\nfunction taylorSeries(Ctor, n, x, y, isHyperbolic) {\r\n var j, t, u, x2,\r\n i = 1,\r\n pr = Ctor.precision,\r\n k = Math.ceil(pr / LOG_BASE);\r\n\r\n external = false;\r\n x2 = x.times(x);\r\n u = new Ctor(y);\r\n\r\n for (;;) {\r\n t = divide(u.times(x2), new Ctor(n++ * n++), pr, 1);\r\n u = isHyperbolic ? y.plus(t) : y.minus(t);\r\n y = divide(t.times(x2), new Ctor(n++ * n++), pr, 1);\r\n t = u.plus(y);\r\n\r\n if (t.d[k] !== void 0) {\r\n for (j = k; t.d[j] === u.d[j] && j--;);\r\n if (j == -1) break;\r\n }\r\n\r\n j = u;\r\n u = y;\r\n y = t;\r\n t = j;\r\n i++;\r\n }\r\n\r\n external = true;\r\n t.d.length = k + 1;\r\n\r\n return t;\r\n}\r\n\r\n\r\n// Exponent e must be positive and non-zero.\r\nfunction tinyPow(b, e) {\r\n var n = b;\r\n while (--e) n *= b;\r\n return n;\r\n}\r\n\r\n\r\n// Return the absolute value of `x` reduced to less than or equal to half pi.\r\nfunction toLessThanHalfPi(Ctor, x) {\r\n var t,\r\n isNeg = x.s < 0,\r\n pi = getPi(Ctor, Ctor.precision, 1),\r\n halfPi = pi.times(0.5);\r\n\r\n x = x.abs();\r\n\r\n if (x.lte(halfPi)) {\r\n quadrant = isNeg ? 4 : 1;\r\n return x;\r\n }\r\n\r\n t = x.divToInt(pi);\r\n\r\n if (t.isZero()) {\r\n quadrant = isNeg ? 3 : 2;\r\n } else {\r\n x = x.minus(t.times(pi));\r\n\r\n // 0 <= x < pi\r\n if (x.lte(halfPi)) {\r\n quadrant = isOdd(t) ? (isNeg ? 2 : 3) : (isNeg ? 4 : 1);\r\n return x;\r\n }\r\n\r\n quadrant = isOdd(t) ? (isNeg ? 1 : 4) : (isNeg ? 3 : 2);\r\n }\r\n\r\n return x.minus(pi).abs();\r\n}\r\n\r\n\r\n/*\r\n * Return the value of Decimal `x` as a string in base `baseOut`.\r\n *\r\n * If the optional `sd` argument is present include a binary exponent suffix.\r\n */\r\nfunction toStringBinary(x, baseOut, sd, rm) {\r\n var base, e, i, k, len, roundUp, str, xd, y,\r\n Ctor = x.constructor,\r\n isExp = sd !== void 0;\r\n\r\n if (isExp) {\r\n checkInt32(sd, 1, MAX_DIGITS);\r\n if (rm === void 0) rm = Ctor.rounding;\r\n else checkInt32(rm, 0, 8);\r\n } else {\r\n sd = Ctor.precision;\r\n rm = Ctor.rounding;\r\n }\r\n\r\n if (!x.isFinite()) {\r\n str = nonFiniteToString(x);\r\n } else {\r\n str = finiteToString(x);\r\n i = str.indexOf('.');\r\n\r\n // Use exponential notation according to `toExpPos` and `toExpNeg`? No, but if required:\r\n // maxBinaryExponent = floor((decimalExponent + 1) * log[2](10))\r\n // minBinaryExponent = floor(decimalExponent * log[2](10))\r\n // log[2](10) = 3.321928094887362347870319429489390175864\r\n\r\n if (isExp) {\r\n base = 2;\r\n if (baseOut == 16) {\r\n sd = sd * 4 - 3;\r\n } else if (baseOut == 8) {\r\n sd = sd * 3 - 2;\r\n }\r\n } else {\r\n base = baseOut;\r\n }\r\n\r\n // Convert the number as an integer then divide the result by its base raised to a power such\r\n // that the fraction part will be restored.\r\n\r\n // Non-integer.\r\n if (i >= 0) {\r\n str = str.replace('.', '');\r\n y = new Ctor(1);\r\n y.e = str.length - i;\r\n y.d = convertBase(finiteToString(y), 10, base);\r\n y.e = y.d.length;\r\n }\r\n\r\n xd = convertBase(str, 10, base);\r\n e = len = xd.length;\r\n\r\n // Remove trailing zeros.\r\n for (; xd[--len] == 0;) xd.pop();\r\n\r\n if (!xd[0]) {\r\n str = isExp ? '0p+0' : '0';\r\n } else {\r\n if (i < 0) {\r\n e--;\r\n } else {\r\n x = new Ctor(x);\r\n x.d = xd;\r\n x.e = e;\r\n x = divide(x, y, sd, rm, 0, base);\r\n xd = x.d;\r\n e = x.e;\r\n roundUp = inexact;\r\n }\r\n\r\n // The rounding digit, i.e. the digit after the digit that may be rounded up.\r\n i = xd[sd];\r\n k = base / 2;\r\n roundUp = roundUp || xd[sd + 1] !== void 0;\r\n\r\n roundUp = rm < 4\r\n ? (i !== void 0 || roundUp) && (rm === 0 || rm === (x.s < 0 ? 3 : 2))\r\n : i > k || i === k && (rm === 4 || roundUp || rm === 6 && xd[sd - 1] & 1 ||\r\n rm === (x.s < 0 ? 8 : 7));\r\n\r\n xd.length = sd;\r\n\r\n if (roundUp) {\r\n\r\n // Rounding up may mean the previous digit has to be rounded up and so on.\r\n for (; ++xd[--sd] > base - 1;) {\r\n xd[sd] = 0;\r\n if (!sd) {\r\n ++e;\r\n xd.unshift(1);\r\n }\r\n }\r\n }\r\n\r\n // Determine trailing zeros.\r\n for (len = xd.length; !xd[len - 1]; --len);\r\n\r\n // E.g. [4, 11, 15] becomes 4bf.\r\n for (i = 0, str = ''; i < len; i++) str += NUMERALS.charAt(xd[i]);\r\n\r\n // Add binary exponent suffix?\r\n if (isExp) {\r\n if (len > 1) {\r\n if (baseOut == 16 || baseOut == 8) {\r\n i = baseOut == 16 ? 4 : 3;\r\n for (--len; len % i; len++) str += '0';\r\n xd = convertBase(str, base, baseOut);\r\n for (len = xd.length; !xd[len - 1]; --len);\r\n\r\n // xd[0] will always be be 1\r\n for (i = 1, str = '1.'; i < len; i++) str += NUMERALS.charAt(xd[i]);\r\n } else {\r\n str = str.charAt(0) + '.' + str.slice(1);\r\n }\r\n }\r\n\r\n str = str + (e < 0 ? 'p' : 'p+') + e;\r\n } else if (e < 0) {\r\n for (; ++e;) str = '0' + str;\r\n str = '0.' + str;\r\n } else {\r\n if (++e > len) for (e -= len; e-- ;) str += '0';\r\n else if (e < len) str = str.slice(0, e) + '.' + str.slice(e);\r\n }\r\n }\r\n\r\n str = (baseOut == 16 ? '0x' : baseOut == 2 ? '0b' : baseOut == 8 ? '0o' : '') + str;\r\n }\r\n\r\n return x.s < 0 ? '-' + str : str;\r\n}\r\n\r\n\r\n// Does not strip trailing zeros.\r\nfunction truncate(arr, len) {\r\n if (arr.length > len) {\r\n arr.length = len;\r\n return true;\r\n }\r\n}\r\n\r\n\r\n// Decimal methods\r\n\r\n\r\n/*\r\n * abs\r\n * acos\r\n * acosh\r\n * add\r\n * asin\r\n * asinh\r\n * atan\r\n * atanh\r\n * atan2\r\n * cbrt\r\n * ceil\r\n * clamp\r\n * clone\r\n * config\r\n * cos\r\n * cosh\r\n * div\r\n * exp\r\n * floor\r\n * hypot\r\n * ln\r\n * log\r\n * log2\r\n * log10\r\n * max\r\n * min\r\n * mod\r\n * mul\r\n * pow\r\n * random\r\n * round\r\n * set\r\n * sign\r\n * sin\r\n * sinh\r\n * sqrt\r\n * sub\r\n * sum\r\n * tan\r\n * tanh\r\n * trunc\r\n */\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is the absolute value of `x`.\r\n *\r\n * x {number|string|Decimal}\r\n *\r\n */\r\nfunction abs(x) {\r\n return new this(x).abs();\r\n}\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is the arccosine in radians of `x`.\r\n *\r\n * x {number|string|Decimal}\r\n *\r\n */\r\nfunction acos(x) {\r\n return new this(x).acos();\r\n}\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is the inverse of the hyperbolic cosine of `x`, rounded to\r\n * `precision` significant digits using rounding mode `rounding`.\r\n *\r\n * x {number|string|Decimal} A value in radians.\r\n *\r\n */\r\nfunction acosh(x) {\r\n return new this(x).acosh();\r\n}\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is the sum of `x` and `y`, rounded to `precision` significant\r\n * digits using rounding mode `rounding`.\r\n *\r\n * x {number|string|Decimal}\r\n * y {number|string|Decimal}\r\n *\r\n */\r\nfunction add(x, y) {\r\n return new this(x).plus(y);\r\n}\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is the arcsine in radians of `x`, rounded to `precision`\r\n * significant digits using rounding mode `rounding`.\r\n *\r\n * x {number|string|Decimal}\r\n *\r\n */\r\nfunction asin(x) {\r\n return new this(x).asin();\r\n}\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is the inverse of the hyperbolic sine of `x`, rounded to\r\n * `precision` significant digits using rounding mode `rounding`.\r\n *\r\n * x {number|string|Decimal} A value in radians.\r\n *\r\n */\r\nfunction asinh(x) {\r\n return new this(x).asinh();\r\n}\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is the arctangent in radians of `x`, rounded to `precision`\r\n * significant digits using rounding mode `rounding`.\r\n *\r\n * x {number|string|Decimal}\r\n *\r\n */\r\nfunction atan(x) {\r\n return new this(x).atan();\r\n}\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is the inverse of the hyperbolic tangent of `x`, rounded to\r\n * `precision` significant digits using rounding mode `rounding`.\r\n *\r\n * x {number|string|Decimal} A value in radians.\r\n *\r\n */\r\nfunction atanh(x) {\r\n return new this(x).atanh();\r\n}\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is the arctangent in radians of `y/x` in the range -pi to pi\r\n * (inclusive), rounded to `precision` significant digits using rounding mode `rounding`.\r\n *\r\n * Domain: [-Infinity, Infinity]\r\n * Range: [-pi, pi]\r\n *\r\n * y {number|string|Decimal} The y-coordinate.\r\n * x {number|string|Decimal} The x-coordinate.\r\n *\r\n * atan2(±0, -0) = ±pi\r\n * atan2(±0, +0) = ±0\r\n * atan2(±0, -x) = ±pi for x > 0\r\n * atan2(±0, x) = ±0 for x > 0\r\n * atan2(-y, ±0) = -pi/2 for y > 0\r\n * atan2(y, ±0) = pi/2 for y > 0\r\n * atan2(±y, -Infinity) = ±pi for finite y > 0\r\n * atan2(±y, +Infinity) = ±0 for finite y > 0\r\n * atan2(±Infinity, x) = ±pi/2 for finite x\r\n * atan2(±Infinity, -Infinity) = ±3*pi/4\r\n * atan2(±Infinity, +Infinity) = ±pi/4\r\n * atan2(NaN, x) = NaN\r\n * atan2(y, NaN) = NaN\r\n *\r\n */\r\nfunction atan2(y, x) {\r\n y = new this(y);\r\n x = new this(x);\r\n var r,\r\n pr = this.precision,\r\n rm = this.rounding,\r\n wpr = pr + 4;\r\n\r\n // Either NaN\r\n if (!y.s || !x.s) {\r\n r = new this(NaN);\r\n\r\n // Both ±Infinity\r\n } else if (!y.d && !x.d) {\r\n r = getPi(this, wpr, 1).times(x.s > 0 ? 0.25 : 0.75);\r\n r.s = y.s;\r\n\r\n // x is ±Infinity or y is ±0\r\n } else if (!x.d || y.isZero()) {\r\n r = x.s < 0 ? getPi(this, pr, rm) : new this(0);\r\n r.s = y.s;\r\n\r\n // y is ±Infinity or x is ±0\r\n } else if (!y.d || x.isZero()) {\r\n r = getPi(this, wpr, 1).times(0.5);\r\n r.s = y.s;\r\n\r\n // Both non-zero and finite\r\n } else if (x.s < 0) {\r\n this.precision = wpr;\r\n this.rounding = 1;\r\n r = this.atan(divide(y, x, wpr, 1));\r\n x = getPi(this, wpr, 1);\r\n this.precision = pr;\r\n this.rounding = rm;\r\n r = y.s < 0 ? r.minus(x) : r.plus(x);\r\n } else {\r\n r = this.atan(divide(y, x, wpr, 1));\r\n }\r\n\r\n return r;\r\n}\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is the cube root of `x`, rounded to `precision` significant\r\n * digits using rounding mode `rounding`.\r\n *\r\n * x {number|string|Decimal}\r\n *\r\n */\r\nfunction cbrt(x) {\r\n return new this(x).cbrt();\r\n}\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is `x` rounded to an integer using `ROUND_CEIL`.\r\n *\r\n * x {number|string|Decimal}\r\n *\r\n */\r\nfunction ceil(x) {\r\n return finalise(x = new this(x), x.e + 1, 2);\r\n}\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is `x` clamped to the range delineated by `min` and `max`.\r\n *\r\n * x {number|string|Decimal}\r\n * min {number|string|Decimal}\r\n * max {number|string|Decimal}\r\n *\r\n */\r\nfunction clamp(x, min, max) {\r\n return new this(x).clamp(min, max);\r\n}\r\n\r\n\r\n/*\r\n * Configure global settings for a Decimal constructor.\r\n *\r\n * `obj` is an object with one or more of the following properties,\r\n *\r\n * precision {number}\r\n * rounding {number}\r\n * toExpNeg {number}\r\n * toExpPos {number}\r\n * maxE {number}\r\n * minE {number}\r\n * modulo {number}\r\n * crypto {boolean|number}\r\n * defaults {true}\r\n *\r\n * E.g. Decimal.config({ precision: 20, rounding: 4 })\r\n *\r\n */\r\nfunction config(obj) {\r\n if (!obj || typeof obj !== 'object') throw Error(decimalError + 'Object expected');\r\n var i, p, v,\r\n useDefaults = obj.defaults === true,\r\n ps = [\r\n 'precision', 1, MAX_DIGITS,\r\n 'rounding', 0, 8,\r\n 'toExpNeg', -EXP_LIMIT, 0,\r\n 'toExpPos', 0, EXP_LIMIT,\r\n 'maxE', 0, EXP_LIMIT,\r\n 'minE', -EXP_LIMIT, 0,\r\n 'modulo', 0, 9\r\n ];\r\n\r\n for (i = 0; i < ps.length; i += 3) {\r\n if (p = ps[i], useDefaults) this[p] = DEFAULTS[p];\r\n if ((v = obj[p]) !== void 0) {\r\n if (mathfloor(v) === v && v >= ps[i + 1] && v <= ps[i + 2]) this[p] = v;\r\n else throw Error(invalidArgument + p + ': ' + v);\r\n }\r\n }\r\n\r\n if (p = 'crypto', useDefaults) this[p] = DEFAULTS[p];\r\n if ((v = obj[p]) !== void 0) {\r\n if (v === true || v === false || v === 0 || v === 1) {\r\n if (v) {\r\n if (typeof crypto != 'undefined' && crypto &&\r\n (crypto.getRandomValues || crypto.randomBytes)) {\r\n this[p] = true;\r\n } else {\r\n throw Error(cryptoUnavailable);\r\n }\r\n } else {\r\n this[p] = false;\r\n }\r\n } else {\r\n throw Error(invalidArgument + p + ': ' + v);\r\n }\r\n }\r\n\r\n return this;\r\n}\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is the cosine of `x`, rounded to `precision` significant\r\n * digits using rounding mode `rounding`.\r\n *\r\n * x {number|string|Decimal} A value in radians.\r\n *\r\n */\r\nfunction cos(x) {\r\n return new this(x).cos();\r\n}\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is the hyperbolic cosine of `x`, rounded to precision\r\n * significant digits using rounding mode `rounding`.\r\n *\r\n * x {number|string|Decimal} A value in radians.\r\n *\r\n */\r\nfunction cosh(x) {\r\n return new this(x).cosh();\r\n}\r\n\r\n\r\n/*\r\n * Create and return a Decimal constructor with the same configuration properties as this Decimal\r\n * constructor.\r\n *\r\n */\r\nfunction clone(obj) {\r\n var i, p, ps;\r\n\r\n /*\r\n * The Decimal constructor and exported function.\r\n * Return a new Decimal instance.\r\n *\r\n * v {number|string|Decimal} A numeric value.\r\n *\r\n */\r\n function Decimal(v) {\r\n var e, i, t,\r\n x = this;\r\n\r\n // Decimal called without new.\r\n if (!(x instanceof Decimal)) return new Decimal(v);\r\n\r\n // Retain a reference to this Decimal constructor, and shadow Decimal.prototype.constructor\r\n // which points to Object.\r\n x.constructor = Decimal;\r\n\r\n // Duplicate.\r\n if (isDecimalInstance(v)) {\r\n x.s = v.s;\r\n\r\n if (external) {\r\n if (!v.d || v.e > Decimal.maxE) {\r\n\r\n // Infinity.\r\n x.e = NaN;\r\n x.d = null;\r\n } else if (v.e < Decimal.minE) {\r\n\r\n // Zero.\r\n x.e = 0;\r\n x.d = [0];\r\n } else {\r\n x.e = v.e;\r\n x.d = v.d.slice();\r\n }\r\n } else {\r\n x.e = v.e;\r\n x.d = v.d ? v.d.slice() : v.d;\r\n }\r\n\r\n return;\r\n }\r\n\r\n t = typeof v;\r\n\r\n if (t === 'number') {\r\n if (v === 0) {\r\n x.s = 1 / v < 0 ? -1 : 1;\r\n x.e = 0;\r\n x.d = [0];\r\n return;\r\n }\r\n\r\n if (v < 0) {\r\n v = -v;\r\n x.s = -1;\r\n } else {\r\n x.s = 1;\r\n }\r\n\r\n // Fast path for small integers.\r\n if (v === ~~v && v < 1e7) {\r\n for (e = 0, i = v; i >= 10; i /= 10) e++;\r\n\r\n if (external) {\r\n if (e > Decimal.maxE) {\r\n x.e = NaN;\r\n x.d = null;\r\n } else if (e < Decimal.minE) {\r\n x.e = 0;\r\n x.d = [0];\r\n } else {\r\n x.e = e;\r\n x.d = [v];\r\n }\r\n } else {\r\n x.e = e;\r\n x.d = [v];\r\n }\r\n\r\n return;\r\n\r\n // Infinity, NaN.\r\n } else if (v * 0 !== 0) {\r\n if (!v) x.s = NaN;\r\n x.e = NaN;\r\n x.d = null;\r\n return;\r\n }\r\n\r\n return parseDecimal(x, v.toString());\r\n\r\n } else if (t !== 'string') {\r\n throw Error(invalidArgument + v);\r\n }\r\n\r\n // Minus sign?\r\n if ((i = v.charCodeAt(0)) === 45) {\r\n v = v.slice(1);\r\n x.s = -1;\r\n } else {\r\n // Plus sign?\r\n if (i === 43) v = v.slice(1);\r\n x.s = 1;\r\n }\r\n\r\n return isDecimal.test(v) ? parseDecimal(x, v) : parseOther(x, v);\r\n }\r\n\r\n Decimal.prototype = P;\r\n\r\n Decimal.ROUND_UP = 0;\r\n Decimal.ROUND_DOWN = 1;\r\n Decimal.ROUND_CEIL = 2;\r\n Decimal.ROUND_FLOOR = 3;\r\n Decimal.ROUND_HALF_UP = 4;\r\n Decimal.ROUND_HALF_DOWN = 5;\r\n Decimal.ROUND_HALF_EVEN = 6;\r\n Decimal.ROUND_HALF_CEIL = 7;\r\n Decimal.ROUND_HALF_FLOOR = 8;\r\n Decimal.EUCLID = 9;\r\n\r\n Decimal.config = Decimal.set = config;\r\n Decimal.clone = clone;\r\n Decimal.isDecimal = isDecimalInstance;\r\n\r\n Decimal.abs = abs;\r\n Decimal.acos = acos;\r\n Decimal.acosh = acosh; // ES6\r\n Decimal.add = add;\r\n Decimal.asin = asin;\r\n Decimal.asinh = asinh; // ES6\r\n Decimal.atan = atan;\r\n Decimal.atanh = atanh; // ES6\r\n Decimal.atan2 = atan2;\r\n Decimal.cbrt = cbrt; // ES6\r\n Decimal.ceil = ceil;\r\n Decimal.clamp = clamp;\r\n Decimal.cos = cos;\r\n Decimal.cosh = cosh; // ES6\r\n Decimal.div = div;\r\n Decimal.exp = exp;\r\n Decimal.floor = floor;\r\n Decimal.hypot = hypot; // ES6\r\n Decimal.ln = ln;\r\n Decimal.log = log;\r\n Decimal.log10 = log10; // ES6\r\n Decimal.log2 = log2; // ES6\r\n Decimal.max = max;\r\n Decimal.min = min;\r\n Decimal.mod = mod;\r\n Decimal.mul = mul;\r\n Decimal.pow = pow;\r\n Decimal.random = random;\r\n Decimal.round = round;\r\n Decimal.sign = sign; // ES6\r\n Decimal.sin = sin;\r\n Decimal.sinh = sinh; // ES6\r\n Decimal.sqrt = sqrt;\r\n Decimal.sub = sub;\r\n Decimal.sum = sum;\r\n Decimal.tan = tan;\r\n Decimal.tanh = tanh; // ES6\r\n Decimal.trunc = trunc; // ES6\r\n\r\n if (obj === void 0) obj = {};\r\n if (obj) {\r\n if (obj.defaults !== true) {\r\n ps = ['precision', 'rounding', 'toExpNeg', 'toExpPos', 'maxE', 'minE', 'modulo', 'crypto'];\r\n for (i = 0; i < ps.length;) if (!obj.hasOwnProperty(p = ps[i++])) obj[p] = this[p];\r\n }\r\n }\r\n\r\n Decimal.config(obj);\r\n\r\n return Decimal;\r\n}\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is `x` divided by `y`, rounded to `precision` significant\r\n * digits using rounding mode `rounding`.\r\n *\r\n * x {number|string|Decimal}\r\n * y {number|string|Decimal}\r\n *\r\n */\r\nfunction div(x, y) {\r\n return new this(x).div(y);\r\n}\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is the natural exponential of `x`, rounded to `precision`\r\n * significant digits using rounding mode `rounding`.\r\n *\r\n * x {number|string|Decimal} The power to which to raise the base of the natural log.\r\n *\r\n */\r\nfunction exp(x) {\r\n return new this(x).exp();\r\n}\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is `x` round to an integer using `ROUND_FLOOR`.\r\n *\r\n * x {number|string|Decimal}\r\n *\r\n */\r\nfunction floor(x) {\r\n return finalise(x = new this(x), x.e + 1, 3);\r\n}\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is the square root of the sum of the squares of the arguments,\r\n * rounded to `precision` significant digits using rounding mode `rounding`.\r\n *\r\n * hypot(a, b, ...) = sqrt(a^2 + b^2 + ...)\r\n *\r\n * arguments {number|string|Decimal}\r\n *\r\n */\r\nfunction hypot() {\r\n var i, n,\r\n t = new this(0);\r\n\r\n external = false;\r\n\r\n for (i = 0; i < arguments.length;) {\r\n n = new this(arguments[i++]);\r\n if (!n.d) {\r\n if (n.s) {\r\n external = true;\r\n return new this(1 / 0);\r\n }\r\n t = n;\r\n } else if (t.d) {\r\n t = t.plus(n.times(n));\r\n }\r\n }\r\n\r\n external = true;\r\n\r\n return t.sqrt();\r\n}\r\n\r\n\r\n/*\r\n * Return true if object is a Decimal instance (where Decimal is any Decimal constructor),\r\n * otherwise return false.\r\n *\r\n */\r\nfunction isDecimalInstance(obj) {\r\n return obj instanceof Decimal || obj && obj.toStringTag === tag || false;\r\n}\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is the natural logarithm of `x`, rounded to `precision`\r\n * significant digits using rounding mode `rounding`.\r\n *\r\n * x {number|string|Decimal}\r\n *\r\n */\r\nfunction ln(x) {\r\n return new this(x).ln();\r\n}\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is the log of `x` to the base `y`, or to base 10 if no base\r\n * is specified, rounded to `precision` significant digits using rounding mode `rounding`.\r\n *\r\n * log[y](x)\r\n *\r\n * x {number|string|Decimal} The argument of the logarithm.\r\n * y {number|string|Decimal} The base of the logarithm.\r\n *\r\n */\r\nfunction log(x, y) {\r\n return new this(x).log(y);\r\n}\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is the base 2 logarithm of `x`, rounded to `precision`\r\n * significant digits using rounding mode `rounding`.\r\n *\r\n * x {number|string|Decimal}\r\n *\r\n */\r\nfunction log2(x) {\r\n return new this(x).log(2);\r\n}\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is the base 10 logarithm of `x`, rounded to `precision`\r\n * significant digits using rounding mode `rounding`.\r\n *\r\n * x {number|string|Decimal}\r\n *\r\n */\r\nfunction log10(x) {\r\n return new this(x).log(10);\r\n}\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is the maximum of the arguments.\r\n *\r\n * arguments {number|string|Decimal}\r\n *\r\n */\r\nfunction max() {\r\n return maxOrMin(this, arguments, 'lt');\r\n}\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is the minimum of the arguments.\r\n *\r\n * arguments {number|string|Decimal}\r\n *\r\n */\r\nfunction min() {\r\n return maxOrMin(this, arguments, 'gt');\r\n}\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is `x` modulo `y`, rounded to `precision` significant digits\r\n * using rounding mode `rounding`.\r\n *\r\n * x {number|string|Decimal}\r\n * y {number|string|Decimal}\r\n *\r\n */\r\nfunction mod(x, y) {\r\n return new this(x).mod(y);\r\n}\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is `x` multiplied by `y`, rounded to `precision` significant\r\n * digits using rounding mode `rounding`.\r\n *\r\n * x {number|string|Decimal}\r\n * y {number|string|Decimal}\r\n *\r\n */\r\nfunction mul(x, y) {\r\n return new this(x).mul(y);\r\n}\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is `x` raised to the power `y`, rounded to precision\r\n * significant digits using rounding mode `rounding`.\r\n *\r\n * x {number|string|Decimal} The base.\r\n * y {number|string|Decimal} The exponent.\r\n *\r\n */\r\nfunction pow(x, y) {\r\n return new this(x).pow(y);\r\n}\r\n\r\n\r\n/*\r\n * Returns a new Decimal with a random value equal to or greater than 0 and less than 1, and with\r\n * `sd`, or `Decimal.precision` if `sd` is omitted, significant digits (or less if trailing zeros\r\n * are produced).\r\n *\r\n * [sd] {number} Significant digits. Integer, 0 to MAX_DIGITS inclusive.\r\n *\r\n */\r\nfunction random(sd) {\r\n var d, e, k, n,\r\n i = 0,\r\n r = new this(1),\r\n rd = [];\r\n\r\n if (sd === void 0) sd = this.precision;\r\n else checkInt32(sd, 1, MAX_DIGITS);\r\n\r\n k = Math.ceil(sd / LOG_BASE);\r\n\r\n if (!this.crypto) {\r\n for (; i < k;) rd[i++] = Math.random() * 1e7 | 0;\r\n\r\n // Browsers supporting crypto.getRandomValues.\r\n } else if (crypto.getRandomValues) {\r\n d = crypto.getRandomValues(new Uint32Array(k));\r\n\r\n for (; i < k;) {\r\n n = d[i];\r\n\r\n // 0 <= n < 4294967296\r\n // Probability n >= 4.29e9, is 4967296 / 4294967296 = 0.00116 (1 in 865).\r\n if (n >= 4.29e9) {\r\n d[i] = crypto.getRandomValues(new Uint32Array(1))[0];\r\n } else {\r\n\r\n // 0 <= n <= 4289999999\r\n // 0 <= (n % 1e7) <= 9999999\r\n rd[i++] = n % 1e7;\r\n }\r\n }\r\n\r\n // Node.js supporting crypto.randomBytes.\r\n } else if (crypto.randomBytes) {\r\n\r\n // buffer\r\n d = crypto.randomBytes(k *= 4);\r\n\r\n for (; i < k;) {\r\n\r\n // 0 <= n < 2147483648\r\n n = d[i] + (d[i + 1] << 8) + (d[i + 2] << 16) + ((d[i + 3] & 0x7f) << 24);\r\n\r\n // Probability n >= 2.14e9, is 7483648 / 2147483648 = 0.0035 (1 in 286).\r\n if (n >= 2.14e9) {\r\n crypto.randomBytes(4).copy(d, i);\r\n } else {\r\n\r\n // 0 <= n <= 2139999999\r\n // 0 <= (n % 1e7) <= 9999999\r\n rd.push(n % 1e7);\r\n i += 4;\r\n }\r\n }\r\n\r\n i = k / 4;\r\n } else {\r\n throw Error(cryptoUnavailable);\r\n }\r\n\r\n k = rd[--i];\r\n sd %= LOG_BASE;\r\n\r\n // Convert trailing digits to zeros according to sd.\r\n if (k && sd) {\r\n n = mathpow(10, LOG_BASE - sd);\r\n rd[i] = (k / n | 0) * n;\r\n }\r\n\r\n // Remove trailing words which are zero.\r\n for (; rd[i] === 0; i--) rd.pop();\r\n\r\n // Zero?\r\n if (i < 0) {\r\n e = 0;\r\n rd = [0];\r\n } else {\r\n e = -1;\r\n\r\n // Remove leading words which are zero and adjust exponent accordingly.\r\n for (; rd[0] === 0; e -= LOG_BASE) rd.shift();\r\n\r\n // Count the digits of the first word of rd to determine leading zeros.\r\n for (k = 1, n = rd[0]; n >= 10; n /= 10) k++;\r\n\r\n // Adjust the exponent for leading zeros of the first word of rd.\r\n if (k < LOG_BASE) e -= LOG_BASE - k;\r\n }\r\n\r\n r.e = e;\r\n r.d = rd;\r\n\r\n return r;\r\n}\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is `x` rounded to an integer using rounding mode `rounding`.\r\n *\r\n * To emulate `Math.round`, set rounding to 7 (ROUND_HALF_CEIL).\r\n *\r\n * x {number|string|Decimal}\r\n *\r\n */\r\nfunction round(x) {\r\n return finalise(x = new this(x), x.e + 1, this.rounding);\r\n}\r\n\r\n\r\n/*\r\n * Return\r\n * 1 if x > 0,\r\n * -1 if x < 0,\r\n * 0 if x is 0,\r\n * -0 if x is -0,\r\n * NaN otherwise\r\n *\r\n * x {number|string|Decimal}\r\n *\r\n */\r\nfunction sign(x) {\r\n x = new this(x);\r\n return x.d ? (x.d[0] ? x.s : 0 * x.s) : x.s || NaN;\r\n}\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is the sine of `x`, rounded to `precision` significant digits\r\n * using rounding mode `rounding`.\r\n *\r\n * x {number|string|Decimal} A value in radians.\r\n *\r\n */\r\nfunction sin(x) {\r\n return new this(x).sin();\r\n}\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is the hyperbolic sine of `x`, rounded to `precision`\r\n * significant digits using rounding mode `rounding`.\r\n *\r\n * x {number|string|Decimal} A value in radians.\r\n *\r\n */\r\nfunction sinh(x) {\r\n return new this(x).sinh();\r\n}\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is the square root of `x`, rounded to `precision` significant\r\n * digits using rounding mode `rounding`.\r\n *\r\n * x {number|string|Decimal}\r\n *\r\n */\r\nfunction sqrt(x) {\r\n return new this(x).sqrt();\r\n}\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is `x` minus `y`, rounded to `precision` significant digits\r\n * using rounding mode `rounding`.\r\n *\r\n * x {number|string|Decimal}\r\n * y {number|string|Decimal}\r\n *\r\n */\r\nfunction sub(x, y) {\r\n return new this(x).sub(y);\r\n}\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is the sum of the arguments, rounded to `precision`\r\n * significant digits using rounding mode `rounding`.\r\n *\r\n * Only the result is rounded, not the intermediate calculations.\r\n *\r\n * arguments {number|string|Decimal}\r\n *\r\n */\r\nfunction sum() {\r\n var i = 0,\r\n args = arguments,\r\n x = new this(args[i]);\r\n\r\n external = false;\r\n for (; x.s && ++i < args.length;) x = x.plus(args[i]);\r\n external = true;\r\n\r\n return finalise(x, this.precision, this.rounding);\r\n}\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is the tangent of `x`, rounded to `precision` significant\r\n * digits using rounding mode `rounding`.\r\n *\r\n * x {number|string|Decimal} A value in radians.\r\n *\r\n */\r\nfunction tan(x) {\r\n return new this(x).tan();\r\n}\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is the hyperbolic tangent of `x`, rounded to `precision`\r\n * significant digits using rounding mode `rounding`.\r\n *\r\n * x {number|string|Decimal} A value in radians.\r\n *\r\n */\r\nfunction tanh(x) {\r\n return new this(x).tanh();\r\n}\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is `x` truncated to an integer.\r\n *\r\n * x {number|string|Decimal}\r\n *\r\n */\r\nfunction trunc(x) {\r\n return finalise(x = new this(x), x.e + 1, 1);\r\n}\r\n\r\n\r\nP[Symbol.for('nodejs.util.inspect.custom')] = P.toString;\r\nP[Symbol.toStringTag] = 'Decimal';\r\n\r\n// Create and configure initial Decimal constructor.\r\nexport var Decimal = P.constructor = clone(DEFAULTS);\r\n\r\n// Create the internal constants from their string values.\r\nLN10 = new Decimal(LN10);\r\nPI = new Decimal(PI);\r\n\r\nexport default Decimal;\r\n","import { PublicKey } from \"@solana/web3.js\";\n\nimport { PublicKeyish, SOLMint, validateAndParsePublicKey } from \"../common/pubKey\";\nimport { TOKEN_WSOL } from \"../raydium/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 { 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.raydium.io/icon/So11111111111111111111111111111111111111112.png`,\n tags: [],\n priority: 2,\n type: \"raydium\",\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.raydium.io/icon/So11111111111111111111111111111111111111112.png`,\n tags: [],\n priority: 2,\n type: \"raydium\",\n extensions: {\n coingeckoId: \"solana\",\n },\n};\n","import _Big from \"big.js\";\nimport BN from \"bn.js\";\nimport _Decimal from \"decimal.js-light\";\n\nimport { BigNumberish, parseBigNumberish, Rounding } from \"../common/bignumber\";\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 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 { BigNumberish, Rounding, tenExponential } from \"../common/bignumber\";\nimport { createLogger } from \"../common/logger\";\n\nimport { Fraction } from \"./fraction\";\nimport { Token } from \"./token\";\n\nconst logger = createLogger(\"Raydium_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 { SOL_INFO } from \"../raydium/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/bignumber\";\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 {\n Connection,\n PublicKey,\n sendAndConfirmTransaction,\n Signer,\n Transaction,\n TransactionInstruction,\n TransactionMessage,\n VersionedTransaction,\n} from \"@solana/web3.js\";\nimport axios from \"axios\";\n\nimport { SignAllTransactions, ComputeBudgetConfig } from \"@/raydium/type\";\nimport { Cluster } from \"@/solana\";\nimport { TxVersion } from \"./txType\";\nimport { Owner } from \"../owner\";\nimport { getRecentBlockHash, addComputeBudget, checkLegacyTxSize, checkV0TxSize, printSimulate } from \"./txUtils\";\nimport { CacheLTA, getMultipleLookupTableInfo, LOOKUP_TABLE_CACHE } from \"./lookupTable\";\n\ninterface SolanaFeeInfo {\n min: number;\n max: number;\n avg: number;\n priorityTx: number;\n nonVotes: number;\n priorityRatio: number;\n avgCuPerBlock: number;\n blockspaceUsageRatio: number;\n}\ntype SolanaFeeInfoJson = {\n \"1\": SolanaFeeInfo;\n \"5\": SolanaFeeInfo;\n \"15\": SolanaFeeInfo;\n};\n\ninterface ExecuteParams {\n skipPreflight?: boolean;\n recentBlockHash?: string;\n}\n\ninterface TxBuilderInit {\n connection: Connection;\n feePayer: PublicKey;\n cluster: Cluster;\n owner?: Owner;\n signAllTransactions?: SignAllTransactions;\n}\n\nexport interface AddInstructionParam {\n addresses?: Record<string, PublicKey>;\n instructions?: TransactionInstruction[];\n endInstructions?: TransactionInstruction[];\n lookupTableAddress?: string[];\n signers?: Signer[];\n instructionTypes?: string[];\n endInstructionTypes?: string[];\n}\n\nexport interface TxBuildData<T = Record<string, any>> {\n builder: TxBuilder;\n transaction: Transaction;\n instructionTypes: string[];\n signers: Signer[];\n execute: (params?: ExecuteParams) => Promise<{ txId: string; signedTx: Transaction }>;\n extInfo: T;\n}\n\nexport interface TxV0BuildData<T = Record<string, any>> extends Omit<TxBuildData<T>, \"transaction\" | \"execute\"> {\n builder: TxBuilder;\n transaction: VersionedTransaction;\n buildProps?: {\n lookupTableCache?: CacheLTA;\n lookupTableAddress?: string[];\n };\n execute: (params?: ExecuteParams) => Promise<{ txId: string; signedTx: VersionedTransaction }>;\n}\n\ntype TxUpdateParams = {\n txId: string;\n status: \"success\" | \"error\" | \"sent\";\n signedTx: Transaction | VersionedTransaction;\n};\nexport interface MultiTxExecuteParam extends ExecuteParams {\n sequentially: boolean;\n onTxUpdate?: (completeTxs: TxUpdateParams[]) => void;\n}\nexport interface MultiTxBuildData<T = Record<string, any>> {\n builder: TxBuilder;\n transactions: Transaction[];\n instructionTypes: string[];\n signers: Signer[][];\n execute: (executeParams?: MultiTxExecuteParam) => Promise<{ txIds: string[]; signedTxs: Transaction[] }>;\n extInfo: T;\n}\n\nexport interface MultiTxV0BuildData<T = Record<string, any>>\n extends Omit<MultiTxBuildData<T>, \"transactions\" | \"execute\"> {\n builder: TxBuilder;\n transactions: VersionedTransaction[];\n buildProps?: {\n lookupTableCache?: CacheLTA;\n lookupTableAddress?: string[];\n };\n execute: (executeParams?: MultiTxExecuteParam) => Promise<{ txIds: string[]; signedTxs: VersionedTransaction[] }>;\n}\n\nexport type MakeMultiTxData<T = TxVersion.LEGACY, O = Record<string, any>> = T extends TxVersion.LEGACY\n ? MultiTxBuildData<O>\n : MultiTxV0BuildData<O>;\n\nexport type MakeTxData<T = TxVersion.LEGACY, O = Record<string, any>> = T extends TxVersion.LEGACY\n ? TxBuildData<O>\n : TxV0BuildData<O>;\n\nexport class TxBuilder {\n private connection: Connection;\n private owner?: Owner;\n private instructions: TransactionInstruction[] = [];\n private endInstructions: TransactionInstruction[] = [];\n private lookupTableAddress: string[] = [];\n private signers: Signer[] = [];\n private instructionTypes: string[] = [];\n private endInstructionTypes: string[] = [];\n private feePayer: PublicKey;\n private cluster: Cluster;\n private signAllTransactions?: SignAllTransactions;\n\n constructor(params: TxBuilderInit) {\n this.connection = params.connection;\n this.feePayer = params.feePayer;\n this.signAllTransactions = params.signAllTransactions;\n this.owner = params.owner;\n this.cluster = params.cluster;\n }\n\n get AllTxData(): {\n instructions: TransactionInstruction[];\n endInstructions: TransactionInstruction[];\n signers: Signer[];\n instructionTypes: string[];\n endInstructionTypes: string[];\n lookupTableAddress: string[];\n } {\n return {\n instructions: this.instructions,\n endInstructions: this.endInstructions,\n signers: this.signers,\n instructionTypes: this.instructionTypes,\n endInstructionTypes: this.endInstructionTypes,\n lookupTableAddress: this.lookupTableAddress,\n };\n }\n\n get allInstructions(): TransactionInstruction[] {\n return [...this.instructions, ...this.endInstructions];\n }\n\n public async getComputeBudgetConfig(): Promise<ComputeBudgetConfig | undefined> {\n const json = (\n await axios.get<SolanaFeeInfoJson>(`https://solanacompass.com/api/fees?cacheFreshTime=${5 * 60 * 1000}`)\n ).data;\n const { avg } = json?.[15] ?? {};\n if (!avg) return undefined;\n return {\n units: 600000,\n microLamports: Math.min(Math.ceil((avg * 1000000) / 600000), 25000),\n };\n }\n\n public addCustomComputeBudget(config?: ComputeBudgetConfig): boolean {\n if (config) {\n const { instructions, instructionTypes } = addComputeBudget(config);\n this.instructions.unshift(...instructions);\n this.instructionTypes.unshift(...instructionTypes);\n return true;\n }\n return false;\n }\n\n public async calComputeBudget({\n config: propConfig,\n defaultIns,\n }: {\n config?: ComputeBudgetConfig;\n defaultIns?: TransactionInstruction[];\n }): Promise<void> {\n try {\n const config = propConfig || (await this.getComputeBudgetConfig());\n if (this.addCustomComputeBudget(config)) return;\n defaultIns && this.instructions.unshift(...defaultIns);\n } catch {\n defaultIns && this.instructions.unshift(...defaultIns);\n }\n }\n\n public addInstruction({\n instructions = [],\n endInstructions = [],\n signers = [],\n instructionTypes = [],\n endInstructionTypes = [],\n lookupTableAddress = [],\n }: AddInstructionParam): TxBuilder {\n this.instructions.push(...instructions);\n this.endInstructions.push(...endInstructions);\n this.signers.push(...signers);\n this.instructionTypes.push(...instructionTypes);\n this.endInstructionTypes.push(...endInstructionTypes);\n this.lookupTableAddress.push(...lookupTableAddress.filter((address) => address !== PublicKey.default.toString()));\n return this;\n }\n\n public async versionBuild<O = Record<string, any>>({\n txVersion,\n extInfo,\n }: {\n txVersion?: TxVersion;\n extInfo?: O;\n }): Promise<MakeTxData<TxVersion.LEGACY, O> | MakeTxData<TxVersion.V0, O>> {\n if (txVersion === TxVersion.V0) return (await this.buildV0({ ...(extInfo || {}) })) as MakeTxData<TxVersion.V0, O>;\n return this.build<O>(extInfo) as MakeTxData<TxVersion.LEGACY, O>;\n }\n\n public build<O = Record<string, any>>(extInfo?: O): MakeTxData<TxVersion.LEGACY, O> {\n const transaction = new Transaction();\n if (this.allInstructions.length) transaction.add(...this.allInstructions);\n transaction.feePayer = this.feePayer;\n\n return {\n builder: this,\n transaction,\n signers: this.signers,\n instructionTypes: [...this.instructionTypes, ...this.endInstructionTypes],\n execute: async (params) => {\n const { recentBlockHash: propBlockHash, skipPreflight = true } = params || {};\n const recentBlockHash = propBlockHash ?? (await getRecentBlockHash(this.connection));\n transaction.recentBlockhash = recentBlockHash;\n if (this.signers.length) transaction.sign(...this.signers);\n printSimulate([transaction]);\n if (this.owner?.isKeyPair) {\n return {\n txId: await sendAndConfirmTransaction(\n this.connection,\n transaction,\n this.signers.find((s) => s.publicKey.equals(this.owner!.publicKey))\n ? this.signers\n : [...this.signers, this.owner.signer!],\n { skipPreflight },\n ),\n signedTx: transaction,\n };\n }\n if (this.signAllTransactions) {\n const txs = await this.signAllTransactions([transaction]);\n return {\n txId: await this.connection.sendRawTransaction(txs[0].serialize(), { skipPreflight }),\n signedTx: txs[0],\n };\n }\n throw new Error(\"please provide owner in keypair format or signAllTransactions function\");\n },\n extInfo: extInfo || ({} as O),\n };\n }\n\n public buildMultiTx<T = Record<string, any>>(params: {\n extraPreBuildData?: MakeTxData<TxVersion.LEGACY>[];\n extInfo?: T;\n }): MultiTxBuildData {\n const { extraPreBuildData = [], extInfo } = params;\n const { transaction } = this.build(extInfo);\n\n const filterExtraBuildData = extraPreBuildData.filter((data) => data.transaction.instructions.length > 0);\n\n const allTransactions: Transaction[] = [transaction, ...filterExtraBuildData.map((data) => data.transaction)];\n const allSigners: Signer[][] = [this.signers, ...filterExtraBuildData.map((data) => data.signers)];\n const allInstructionTypes: string[] = [\n ...this.instructionTypes,\n ...filterExtraBuildData.map((data) => data.instructionTypes).flat(),\n ];\n\n return {\n builder: this,\n transactions: allTransactions,\n signers: allSigners,\n instructionTypes: allInstructionTypes,\n execute: async (executeParams?: MultiTxExecuteParam) => {\n const { sequentially, onTxUpdate, recentBlockHash: propBlockHash, skipPreflight = true } = executeParams || {};\n const recentBlockHash = propBlockHash ?? (await getRecentBlockHash(this.connection));\n if (this.owner?.isKeyPair) {\n if (sequentially) {\n const txIds: string[] = [];\n for (const tx of allTransactions) {\n const txId = await sendAndConfirmTransaction(\n this.connection,\n tx,\n this.signers.find((s) => s.publicKey.equals(this.owner!.publicKey))\n ? this.signers\n : [...this.signers, this.owner.signer!],\n { skipPreflight },\n );\n txIds.push(txId);\n }\n\n return {\n txIds,\n signedTxs: allTransactions,\n };\n }\n\n return {\n txIds: await await Promise.all(\n allTransactions.map(async (tx, idx) => {\n tx.recentBlockhash = recentBlockHash;\n return await sendAndConfirmTransaction(\n this.connection,\n tx,\n allSigners[idx].find((s) => s.publicKey.equals(this.owner!.publicKey))\n ? allSigners[idx]\n : [...allSigners[idx], this.owner!.signer!],\n { skipPreflight },\n );\n }),\n ),\n signedTxs: allTransactions,\n };\n }\n\n if (this.signAllTransactions) {\n const partialSignedTxs = allTransactions.map((tx, idx) => {\n tx.recentBlockhash = recentBlockHash;\n if (allSigners[idx].length) tx.sign(...allSigners[idx]);\n return tx;\n });\n printSimulate(partialSignedTxs);\n const signedTxs = await this.signAllTransactions(partialSignedTxs);\n if (sequentially) {\n let i = 0;\n const processedTxs: TxUpdateParams[] = [];\n const checkSendTx = async (): Promise<void> => {\n if (!signedTxs[i]) return;\n const txId = await this.connection.sendRawTransaction(signedTxs[i].serialize(), { skipPreflight });\n processedTxs.push({ txId, status: \"sent\", signedTx: signedTxs[i] });\n onTxUpdate?.([...processedTxs]);\n i++;\n this.connection.onSignature(\n txId,\n (signatureResult) => {\n const targetTxIdx = processedTxs.findIndex((tx) => tx.txId === txId);\n if (targetTxIdx > -1) processedTxs[targetTxIdx].status = signatureResult.err ? \"error\" : \"success\";\n onTxUpdate?.([...processedTxs]);\n if (!signatureResult.err) checkSendTx();\n },\n \"processed\",\n );\n this.connection.getSignatureStatus(txId);\n };\n await checkSendTx();\n return {\n txIds: processedTxs.map((d) => d.txId),\n signedTxs,\n };\n } else {\n const txIds: string[] = [];\n for (let i = 0; i < signedTxs.length; i += 1) {\n const txId = await this.connection.sendRawTransaction(signedTxs[i].serialize(), { skipPreflight });\n txIds.push(txId);\n }\n return {\n txIds,\n signedTxs,\n };\n }\n }\n throw new Error(\"please provide owner in keypair format or signAllTransactions function\");\n },\n extInfo: extInfo || {},\n };\n }\n\n public async versionMultiBuild<T extends TxVersion, O = Record<string, any>>({\n extraPreBuildData,\n txVersion,\n extInfo,\n }: {\n extraPreBuildData?: MakeTxData<TxVersion.V0>[] | MakeTxData<TxVersion.LEGACY>[];\n txVersion?: T;\n extInfo?: O;\n }): Promise<MakeMultiTxData<T, O>> {\n if (txVersion === TxVersion.V0)\n return (await this.buildV0MultiTx({\n extraPreBuildData: extraPreBuildData as MakeTxData<TxVersion.V0>[],\n buildProps: extInfo || {},\n })) as MakeMultiTxData<T, O>;\n return this.buildMultiTx<O>({\n extraPreBuildData: extraPreBuildData as MakeTxData<TxVersion.LEGACY>[],\n extInfo,\n }) as MakeMultiTxData<T, O>;\n }\n\n public async buildV0<O = Record<string, any>>(\n props?: O & {\n lookupTableCache?: CacheLTA;\n lookupTableAddress?: string[];\n forerunCreate?: boolean;\n },\n ): Promise<MakeTxData<TxVersion.V0, O>> {\n const { lookupTableCache = {}, lookupTableAddress = [], forerunCreate, ...extInfo } = props || {};\n const lookupTableAddressAccount = {\n ...(this.cluster === \"devnet\" ? {} : LOOKUP_TABLE_CACHE),\n ...lookupTableCache,\n };\n const allLTA = Array.from(new Set<string>([...lookupTableAddress, ...this.lookupTableAddress]));\n const needCacheLTA: PublicKey[] = [];\n for (const item of allLTA) {\n if (lookupTableAddressAccount[item] === undefined) needCacheLTA.push(new PublicKey(item));\n }\n const newCacheLTA = await getMultipleLookupTableInfo({ connection: this.connection, address: needCacheLTA });\n for (const [key, value] of Object.entries(newCacheLTA)) lookupTableAddressAccount[key] = value;\n\n const messageV0 = new TransactionMessage({\n payerKey: this.feePayer,\n recentBlockhash: forerunCreate ? PublicKey.default.toBase58() : await getRecentBlockHash(this.connection),\n instructions: [...this.allInstructions],\n }).compileToV0Message(Object.values(lookupTableAddressAccount));\n const transaction = new VersionedTransaction(messageV0);\n transaction.sign(this.signers);\n\n return {\n builder: this,\n transaction,\n signers: this.signers,\n instructionTypes: [...this.instructionTypes, ...this.endInstructionTypes],\n execute: async (params) => {\n const { recentBlockHash: propBlockHash, skipPreflight = true } = params || {};\n if (propBlockHash) transaction.message.recentBlockhash = propBlockHash;\n printSimulate([transaction]);\n if (this.owner?.isKeyPair) {\n if (!this.signers.find((s) => s.publicKey.equals(this.owner!.publicKey)))\n transaction.sign([this.owner.signer as Signer]);\n const txId = await this.connection.sendTransaction(transaction, { skipPreflight });\n const { lastValidBlockHeight, blockhash } = await this.connection.getLatestBlockhash();\n await this.connection.confirmTransaction(\n {\n blockhash,\n lastValidBlockHeight,\n signature: txId,\n },\n \"confirmed\",\n );\n\n return {\n txId,\n signedTx: transaction,\n };\n }\n if (this.signAllTransactions) {\n const txs = await this.signAllTransactions<VersionedTransaction>([transaction]);\n return {\n txId: await this.connection.sendTransaction(txs[0], { skipPreflight }),\n signedTx: txs[0],\n };\n }\n throw new Error(\"please provide owner in keypair format or signAllTransactions function\");\n },\n extInfo: (extInfo || {}) as O,\n };\n }\n\n public async buildV0MultiTx<T = Record<string, any>>(params: {\n extraPreBuildData?: MakeTxData<TxVersion.V0>[];\n buildProps?: T & {\n lookupTableCache?: CacheLTA;\n lookupTableAddress?: string[];\n };\n }): Promise<MultiTxV0BuildData> {\n const { extraPreBuildData = [], buildProps } = params;\n const { transaction } = await this.buildV0(buildProps);\n\n const filterExtraBuildData = extraPreBuildData.filter((data) => data.builder.instructions.length > 0);\n\n const allTransactions: VersionedTransaction[] = [\n transaction,\n ...filterExtraBuildData.map((data) => data.transaction),\n ];\n const allSigners: Signer[][] = [this.signers, ...filterExtraBuildData.map((data) => data.signers)];\n const allInstructionTypes: string[] = [\n ...this.instructionTypes,\n ...filterExtraBuildData.map((data) => data.instructionTypes).flat(),\n ];\n\n allTransactions.forEach(async (tx, idx) => {\n tx.sign(allSigners[idx]);\n });\n\n return {\n builder: this,\n transactions: allTransactions,\n signers: allSigners,\n instructionTypes: allInstructionTypes,\n buildProps,\n execute: async (executeParams?: MultiTxExecuteParam) => {\n const { sequentially, onTxUpdate, recentBlockHash: propBlockHash, skipPreflight = true } = executeParams || {};\n if (propBlockHash) allTransactions.forEach((tx) => (tx.message.recentBlockhash = propBlockHash));\n printSimulate(allTransactions);\n if (this.owner?.isKeyPair) {\n const { lastValidBlockHeight, blockhash } = await this.connection.getLatestBlockhash();\n allTransactions.forEach((tx, idx) => {\n if (!allSigners[idx].find((s) => s.publicKey.equals(this.owner!.publicKey)))\n tx.sign([this.owner!.signer as Signer]);\n });\n\n if (sequentially) {\n const txIds: string[] = [];\n for (const tx of allTransactions) {\n const txId = await this.connection.sendTransaction(tx, { skipPreflight });\n const { lastValidBlockHeight, blockhash } = await this.connection.getLatestBlockhash();\n await this.connection.confirmTransaction(\n {\n blockhash,\n lastValidBlockHeight,\n signature: txId,\n },\n \"confirmed\",\n );\n txIds.push(txId);\n }\n\n return { txIds, signedTxs: allTransactions };\n }\n\n return {\n txIds: await Promise.all(\n allTransactions.map(async (tx) => {\n const txId = await this.connection.sendTransaction(tx, { skipPreflight });\n await this.connection.confirmTransaction(\n {\n blockhash,\n lastValidBlockHeight,\n signature: txId,\n },\n \"confirmed\",\n );\n return txId;\n }),\n ),\n signedTxs: allTransactions,\n };\n }\n\n if (this.signAllTransactions) {\n const signedTxs = await this.signAllTransactions(allTransactions);\n\n if (sequentially) {\n let i = 0;\n const processedTxs: TxUpdateParams[] = [];\n const checkSendTx = async (): Promise<void> => {\n if (!signedTxs[i]) return;\n const txId = await this.connection.sendTransaction(signedTxs[i], { skipPreflight });\n processedTxs.push({ txId, status: \"sent\", signedTx: signedTxs[i] });\n onTxUpdate?.([...processedTxs]);\n i++;\n this.connection.onSignature(\n txId,\n (signatureResult) => {\n const targetTxIdx = processedTxs.findIndex((tx) => tx.txId === txId);\n if (targetTxIdx > -1) processedTxs[targetTxIdx].status = signatureResult.err ? \"error\" : \"success\";\n onTxUpdate?.([...processedTxs]);\n if (!signatureResult.err) checkSendTx();\n },\n \"processed\",\n );\n this.connection.getSignatureStatus(txId);\n };\n checkSendTx();\n return {\n txIds: [],\n signedTxs,\n };\n } else {\n const txIds: string[] = [];\n for (let i = 0; i < signedTxs.length; i += 1) {\n const txId = await this.connection.sendTransaction(signedTxs[i], { skipPreflight });\n txIds.push(txId);\n }\n return { txIds, signedTxs };\n }\n }\n throw new Error(\"please provide owner in keypair format or signAllTransactions function\");\n },\n extInfo: buildProps || {},\n };\n }\n\n public async sizeCheckBuild(\n props?: Record<string, any> & { computeBudgetConfig?: ComputeBudgetConfig },\n ): Promise<MultiTxBuildData> {\n const { computeBudgetConfig, ...extInfo } = props || {};\n\n const computeBudgetData: { instructions: TransactionInstruction[]; instructionTypes: string[] } =\n computeBudgetConfig\n ? addComputeBudget(computeBudgetConfig)\n : {\n instructions: [],\n instructionTypes: [],\n };\n\n const signerKey: { [key: string]: Signer } = this.signers.reduce(\n (acc, cur) => ({ ...acc, [cur.publicKey.toBase58()]: cur }),\n {},\n );\n\n const allTransactions: Transaction[] = [];\n const allSigners: Signer[][] = [];\n\n let instructionQueue: TransactionInstruction[] = [];\n this.allInstructions.forEach((item) => {\n const _itemIns = [...instructionQueue, item];\n const _itemInsWithCompute = computeBudgetConfig ? [...computeBudgetData.instructions, ..._itemIns] : _itemIns;\n const _signerStrs = new Set<string>(\n _itemIns.map((i) => i.keys.filter((ii) => ii.isSigner).map((ii) => ii.pubkey.toString())).flat(),\n );\n const _signer = [..._signerStrs.values()].map((i) => new PublicKey(i));\n\n if (\n (instructionQueue.length < 12 &&\n checkLegacyTxSize({ instructions: _itemInsWithCompute, payer: this.feePayer, signers: _signer })) ||\n checkLegacyTxSize({ instructions: _itemIns, payer: this.feePayer, signers: _signer })\n ) {\n // current ins add to queue still not exceed tx size limit\n instructionQueue.push(item);\n } else {\n if (instructionQueue.length === 0) throw Error(\"item ins too big\");\n\n // if add computeBudget still not exceed tx size limit\n if (\n checkLegacyTxSize({\n instructions: computeBudgetConfig\n ? [...computeBudgetData.instructions, ...instructionQueue]\n : [...instructionQueue],\n payer: this.feePayer,\n signers: _signer,\n })\n ) {\n allTransactions.push(new Transaction().add(...computeBudgetData.instructions, ...instructionQueue));\n } else {\n allTransactions.push(new Transaction().add(...instructionQueue));\n }\n allSigners.push(\n Array.from(\n new Set<string>(\n instructionQueue.map((i) => i.keys.filter((ii) => ii.isSigner).map((ii) => ii.pubkey.toString())).flat(),\n ),\n )\n .map((i) => signerKey[i])\n .filter((i) => i !== undefined),\n );\n instructionQueue = [item];\n }\n });\n\n if (instructionQueue.length > 0) {\n const _signerStrs = new Set<string>(\n instructionQueue.map((i) => i.keys.filter((ii) => ii.isSigner).map((ii) => ii.pubkey.toString())).flat(),\n );\n const _signers = [..._signerStrs.values()].map((i) => signerKey[i]).filter((i) => i !== undefined);\n\n if (\n checkLegacyTxSize({\n instructions: computeBudgetConfig\n ? [...computeBudgetData.instructions, ...instructionQueue]\n : [...instructionQueue],\n payer: this.feePayer,\n signers: _signers.map((s) => s.publicKey),\n })\n ) {\n allTransactions.push(new Transaction().add(...computeBudgetData.instructions, ...instructionQueue));\n } else {\n allTransactions.push(new Transaction().add(...instructionQueue));\n }\n allSigners.push(_signers);\n }\n allTransactions.forEach((tx) => (tx.feePayer = this.feePayer));\n\n return {\n builder: this,\n transactions: allTransactions,\n signers: allSigners,\n instructionTypes: this.instructionTypes,\n execute: async (executeParams?: MultiTxExecuteParam) => {\n const { sequentially, onTxUpdate, recentBlockHash: propBlockHash, skipPreflight = true } = executeParams || {};\n const recentBlockHash = propBlockHash ?? (await getRecentBlockHash(this.connection));\n allTransactions.forEach(async (tx, idx) => {\n tx.recentBlockhash = recentBlockHash;\n if (allSigners[idx].length) tx.sign(...allSigners[idx]);\n });\n printSimulate(allTransactions);\n if (this.owner?.isKeyPair) {\n if (sequentially) {\n const txIds: string[] = [];\n for (const tx of allTransactions) {\n const txId = await sendAndConfirmTransaction(\n this.connection,\n tx,\n this.signers.find((s) => s.publicKey.equals(this.owner!.publicKey))\n ? this.signers\n : [...this.signers, this.owner.signer!],\n { skipPreflight },\n );\n txIds.push(txId);\n }\n\n return {\n txIds,\n signedTxs: allTransactions,\n };\n }\n return {\n txIds: await Promise.all(\n allTransactions.map(async (tx, idx) => {\n return await sendAndConfirmTransaction(\n this.connection,\n tx,\n allSigners[idx].find((s) => s.publicKey.equals(this.owner!.publicKey))\n ? allSigners[idx]\n : [...allSigners[idx], this.owner!.signer!],\n { skipPreflight },\n );\n }),\n ),\n signedTxs: allTransactions,\n };\n }\n if (this.signAllTransactions) {\n const signedTxs = await this.signAllTransactions(allTransactions);\n if (sequentially) {\n let i = 0;\n const processedTxs: TxUpdateParams[] = [];\n const checkSendTx = async (): Promise<void> => {\n if (!signedTxs[i]) return;\n const txId = await this.connection.sendRawTransaction(signedTxs[i].serialize(), { skipPreflight });\n processedTxs.push({ txId, status: \"sent\", signedTx: signedTxs[i] });\n onTxUpdate?.([...processedTxs]);\n i++;\n this.connection.onSignature(\n txId,\n (signatureResult) => {\n const targetTxIdx = processedTxs.findIndex((tx) => tx.txId === txId);\n if (targetTxIdx > -1) processedTxs[targetTxIdx].status = signatureResult.err ? \"error\" : \"success\";\n onTxUpdate?.([...processedTxs]);\n if (!signatureResult.err) checkSendTx();\n },\n \"processed\",\n );\n this.connection.getSignatureStatus(txId);\n };\n await checkSendTx();\n return {\n txIds: processedTxs.map((d) => d.txId),\n signedTxs,\n };\n } else {\n const txIds: string[] = [];\n for (let i = 0; i < signedTxs.length; i += 1) {\n const txId = await this.connection.sendRawTransaction(signedTxs[i].serialize(), { skipPreflight });\n txIds.push(txId);\n }\n return { txIds, signedTxs };\n }\n }\n throw new Error(\"please provide owner in keypair format or signAllTransactions function\");\n },\n extInfo: extInfo || {},\n };\n }\n\n public async sizeCheckBuildV0(\n props?: Record<string, any> & {\n computeBudgetConfig?: ComputeBudgetConfig;\n lookupTableCache?: CacheLTA;\n lookupTableAddress?: string[];\n },\n ): Promise<MultiTxV0BuildData> {\n const { computeBudgetConfig, lookupTableCache = {}, lookupTableAddress = [], ...extInfo } = props || {};\n const lookupTableAddressAccount = {\n ...(this.cluster === \"devnet\" ? {} : LOOKUP_TABLE_CACHE),\n ...lookupTableCache,\n };\n const allLTA = Array.from(new Set<string>([...this.lookupTableAddress, ...lookupTableAddress]));\n const needCacheLTA: PublicKey[] = [];\n for (const item of allLTA) {\n if (lookupTableAddressAccount[item] === undefined) needCacheLTA.push(new PublicKey(item));\n }\n const newCacheLTA = await getMultipleLookupTableInfo({ connection: this.connection, address: needCacheLTA });\n for (const [key, value] of Object.entries(newCacheLTA)) lookupTableAddressAccount[key] = value;\n\n const computeBudgetData: { instructions: TransactionInstruction[]; instructionTypes: string[] } =\n computeBudgetConfig\n ? addComputeBudget(computeBudgetConfig)\n : {\n instructions: [],\n instructionTypes: [],\n };\n\n const blockHash = await getRecentBlockHash(this.connection);\n\n const signerKey: { [key: string]: Signer } = this.signers.reduce(\n (acc, cur) => ({ ...acc, [cur.publicKey.toBase58()]: cur }),\n {},\n );\n\n const allTransactions: VersionedTransaction[] = [];\n const allSigners: Signer[][] = [];\n\n let instructionQueue: TransactionInstruction[] = [];\n this.allInstructions.forEach((item) => {\n const _itemIns = [...instructionQueue, item];\n const _itemInsWithCompute = computeBudgetConfig ? [...computeBudgetData.instructions, ..._itemIns] : _itemIns;\n if (\n (instructionQueue.length < 12 &&\n checkV0TxSize({ instructions: _itemInsWithCompute, payer: this.feePayer, lookupTableAddressAccount })) ||\n checkV0TxSize({ instructions: _itemIns, payer: this.feePayer, lookupTableAddressAccount })\n ) {\n // current ins add to queue still not exceed tx size limit\n instructionQueue.push(item);\n } else {\n if (instructionQueue.length === 0) throw Error(\"item ins too big\");\n\n const lookupTableAddress: undefined | CacheLTA = {};\n for (const item of [...new Set<string>(allLTA)]) {\n if (lookupTableAddressAccount[item] !== undefined) lookupTableAddress[item] = lookupTableAddressAccount[item];\n }\n // if add computeBudget still not exceed tx size limit\n if (\n computeBudgetConfig &&\n checkV0TxSize({\n instructions: [...computeBudgetData.instructions, ...instructionQueue],\n payer: this.feePayer,\n lookupTableAddressAccount,\n recentBlockhash: blockHash,\n })\n ) {\n const messageV0 = new TransactionMessage({\n payerKey: this.feePayer,\n recentBlockhash: blockHash,\n\n instructions: [...computeBudgetData.instructions, ...instructionQueue],\n }).compileToV0Message(Object.values(lookupTableAddressAccount));\n allTransactions.push(new VersionedTransaction(messageV0));\n } else {\n const messageV0 = new TransactionMessage({\n payerKey: this.feePayer,\n recentBlockhash: blockHash,\n instructions: [...instructionQueue],\n }).compileToV0Message(Object.values(lookupTableAddressAccount));\n allTransactions.push(new VersionedTransaction(messageV0));\n }\n allSigners.push(\n Array.from(\n new Set<string>(\n instructionQueue.map((i) => i.keys.filter((ii) => ii.isSigner).map((ii) => ii.pubkey.toString())).flat(),\n ),\n )\n .map((i) => signerKey[i])\n .filter((i) => i !== undefined),\n );\n instructionQueue = [item];\n }\n });\n\n if (instructionQueue.length > 0) {\n const _signerStrs = new Set<string>(\n instructionQueue.map((i) => i.keys.filter((ii) => ii.isSigner).map((ii) => ii.pubkey.toString())).flat(),\n );\n const _signers = [..._signerStrs.values()].map((i) => signerKey[i]).filter((i) => i !== undefined);\n\n if (\n computeBudgetConfig &&\n checkV0TxSize({\n instructions: [...computeBudgetData.instructions, ...instructionQueue],\n payer: this.feePayer,\n lookupTableAddressAccount,\n recentBlockhash: blockHash,\n })\n ) {\n const messageV0 = new TransactionMessage({\n payerKey: this.feePayer,\n recentBlockhash: blockHash,\n instructions: [...computeBudgetData.instructions, ...instructionQueue],\n }).compileToV0Message(Object.values(lookupTableAddressAccount));\n allTransactions.push(new VersionedTransaction(messageV0));\n } else {\n const messageV0 = new TransactionMessage({\n payerKey: this.feePayer,\n recentBlockhash: blockHash,\n instructions: [...instructionQueue],\n }).compileToV0Message(Object.values(lookupTableAddressAccount));\n allTransactions.push(new VersionedTransaction(messageV0));\n }\n allSigners.push(_signers);\n }\n\n return {\n builder: this,\n transactions: allTransactions,\n buildProps: props,\n signers: allSigners,\n instructionTypes: this.instructionTypes,\n execute: async (executeParams?: MultiTxExecuteParam) => {\n const { sequentially, onTxUpdate, recentBlockHash: propBlockHash, skipPreflight = true } = executeParams || {};\n allTransactions.map(async (tx, idx) => {\n if (allSigners[idx].length) tx.sign(allSigners[idx]);\n if (propBlockHash) tx.message.recentBlockhash = propBlockHash;\n });\n printSimulate(allTransactions);\n if (this.owner?.isKeyPair) {\n const { lastValidBlockHeight, blockhash } = await this.connection.getLatestBlockhash();\n allTransactions.forEach((tx, idx) => {\n if (!allSigners[idx].find((s) => s.publicKey.equals(this.owner!.publicKey)))\n tx.sign([this.owner!.signer as Signer]);\n });\n\n if (sequentially) {\n const txIds: string[] = [];\n for (const tx of allTransactions) {\n const txId = await this.connection.sendTransaction(tx, { skipPreflight });\n const { lastValidBlockHeight, blockhash } = await this.connection.getLatestBlockhash();\n await this.connection.confirmTransaction(\n {\n blockhash,\n lastValidBlockHeight,\n signature: txId,\n },\n \"confirmed\",\n );\n txIds.push(txId);\n }\n\n return { txIds, signedTxs: allTransactions };\n }\n\n return {\n txIds: await Promise.all(\n allTransactions.map(async (tx) => {\n const txId = await this.connection.sendTransaction(tx, { skipPreflight });\n await this.connection.confirmTransaction(\n {\n blockhash,\n lastValidBlockHeight,\n signature: txId,\n },\n \"confirmed\",\n );\n return txId;\n }),\n ),\n signedTxs: allTransactions,\n };\n }\n if (this.signAllTransactions) {\n const signedTxs = await this.signAllTransactions(allTransactions);\n if (sequentially) {\n let i = 0;\n const processedTxs: TxUpdateParams[] = [];\n const checkSendTx = async (): Promise<void> => {\n if (!signedTxs[i]) return;\n const txId = await this.connection.sendTransaction(signedTxs[i], { skipPreflight });\n processedTxs.push({ txId, status: \"sent\", signedTx: signedTxs[i] });\n onTxUpdate?.([...processedTxs]);\n i++;\n this.connection.onSignature(\n txId,\n (signatureResult) => {\n const targetTxIdx = processedTxs.findIndex((tx) => tx.txId === txId);\n if (targetTxIdx > -1) processedTxs[targetTxIdx].status = signatureResult.err ? \"error\" : \"success\";\n onTxUpdate?.([...processedTxs]);\n if (!signatureResult.err) checkSendTx();\n },\n \"processed\",\n );\n this.connection.getSignatureStatus(txId);\n };\n checkSendTx();\n return {\n txIds: [],\n signedTxs,\n };\n } else {\n const txIds: string[] = [];\n for (let i = 0; i < signedTxs.length; i += 1) {\n const txId = await this.connection.sendTransaction(signedTxs[i], { skipPreflight });\n txIds.push(txId);\n }\n return { txIds, signedTxs };\n }\n }\n throw new Error(\"please provide owner in keypair format or signAllTransactions function\");\n },\n extInfo: extInfo || {},\n };\n }\n}\n","export enum TxVersion {\n \"V0\",\n \"LEGACY\",\n}\n\nexport const InstructionType = {\n CreateAccount: \"CreateAccount\",\n InitAccount: \"InitAccount\",\n CreateATA: \"CreateATA\",\n CloseAccount: \"CloseAccount\",\n TransferAmount: \"TransferAmount\",\n InitMint: \"InitMint\",\n MintTo: \"MintTo\",\n\n InitMarket: \"InitMarket\", // create market main ins\n Util1216OwnerClaim: \"Util1216OwnerClaim\", // owner claim token ins\n\n SetComputeUnitPrice: \"SetComputeUnitPrice\",\n SetComputeUnitLimit: \"SetComputeUnitLimit\",\n\n // CLMM\n ClmmCreatePool: \"ClmmCreatePool\",\n ClmmOpenPosition: \"ClmmOpenPosition\",\n ClmmIncreasePosition: \"ClmmIncreasePosition\",\n ClmmDecreasePosition: \"ClmmDecreasePosition\",\n ClmmClosePosition: \"ClmmClosePosition\",\n ClmmSwapBaseIn: \"ClmmSwapBaseIn\",\n ClmmSwapBaseOut: \"ClmmSwapBaseOut\",\n ClmmInitReward: \"ClmmInitReward\",\n ClmmSetReward: \"ClmmSetReward\",\n ClmmCollectReward: \"ClmmCollectReward\",\n\n AmmV4Swap: \"AmmV4Swap\",\n AmmV4AddLiquidity: \"AmmV4AddLiquidity\",\n AmmV4RemoveLiquidity: \"AmmV4RemoveLiquidity\",\n AmmV4SimulatePoolInfo: \"AmmV4SimulatePoolInfo\",\n AmmV4SwapBaseIn: \"AmmV4SwapBaseIn\",\n AmmV4SwapBaseOut: \"AmmV4SwapBaseOut\",\n AmmV4CreatePool: \"AmmV4CreatePool\",\n AmmV4InitPool: \"AmmV4InitPool\",\n\n AmmV5AddLiquidity: \"AmmV5AddLiquidity\",\n AmmV5RemoveLiquidity: \"AmmV5RemoveLiquidity\",\n AmmV5SimulatePoolInfo: \"AmmV5SimulatePoolInfo\",\n AmmV5SwapBaseIn: \"AmmV5SwapBaseIn\",\n AmmV5SwapBaseOut: \"AmmV5SwapBaseOut\",\n\n RouteSwap: \"RouteSwap\",\n RouteSwap1: \"RouteSwap1\",\n RouteSwap2: \"RouteSwap2\",\n\n FarmV3Deposit: \"FarmV3Deposit\",\n FarmV3Withdraw: \"FarmV3Withdraw\",\n FarmV3CreateLedger: \"FarmV3CreateLedger\",\n\n FarmV5Deposit: \"FarmV5Deposit\",\n FarmV5Withdraw: \"FarmV5Withdraw\",\n FarmV5CreateLedger: \"FarmV5CreateLedger\",\n\n FarmV6Deposit: \"FarmV6Deposit\",\n FarmV6Withdraw: \"FarmV6Withdraw\",\n FarmV6Create: \"FarmV6Create\",\n FarmV6Restart: \"FarmV6Restart\",\n FarmV6CreatorAddReward: \"FarmV6CreatorAddReward\",\n FarmV6CreatorWithdraw: \"FarmV6CreatorWithdraw\",\n\n CpmmCreatePool: \"CpmmCreatePool\",\n CpmmAddLiquidity: \"CpmmAddLiquidity\",\n CpmmWithdrawLiquidity: \"CpmmWithdrawLiquidity\",\n CpmmSwapBaseIn: \"CpmmSwapBaseIn\",\n CpmmSwapBaseOut: \"CpmmSwapBaseOut\",\n};\n","import {\n Connection,\n PublicKey,\n ComputeBudgetProgram,\n SimulatedTransactionResponse,\n Transaction,\n TransactionInstruction,\n TransactionMessage,\n Keypair,\n EpochInfo,\n VersionedTransaction,\n} from \"@solana/web3.js\";\nimport { TOKEN_PROGRAM_ID } from \"@solana/spl-token\";\n\nimport { createLogger } from \"../logger\";\nimport { InstructionType } from \"./txType\";\nimport { CacheLTA } from \"./lookupTable\";\n\nimport { ComputeBudgetConfig } from \"@/raydium/type\";\n\nconst logger = createLogger(\"Raydium_txUtil\");\n\nexport const MAX_BASE64_SIZE = 1644;\n\nexport function addComputeBudget(config: ComputeBudgetConfig): {\n instructions: TransactionInstruction[];\n instructionTypes: string[];\n} {\n const ins: TransactionInstruction[] = [];\n const insTypes: string[] = [];\n if (config.microLamports) {\n ins.push(ComputeBudgetProgram.setComputeUnitPrice({ microLamports: config.microLamports }));\n insTypes.push(InstructionType.SetComputeUnitPrice);\n }\n if (config.units) {\n ins.push(ComputeBudgetProgram.setComputeUnitLimit({ units: config.units }));\n insTypes.push(InstructionType.SetComputeUnitLimit);\n }\n\n return {\n instructions: ins,\n instructionTypes: insTypes,\n };\n}\n\nexport async function getRecentBlockHash(connection: Connection): Promise<string> {\n try {\n return (await connection.getLatestBlockhash?.())?.blockhash || (await connection.getRecentBlockhash()).blockhash;\n } catch {\n return (await connection.getRecentBlockhash()).blockhash;\n }\n}\n\n/**\n * Forecast transaction size\n */\nexport function forecastTransactionSize(instructions: TransactionInstruction[], signers: PublicKey[]): boolean {\n if (instructions.length < 1) logger.logWithError(`no instructions provided: ${instructions.toString()}`);\n if (signers.length < 1) logger.logWithError(`no signers provided:, ${signers.toString()}`);\n\n const transaction = new Transaction();\n transaction.recentBlockhash = \"11111111111111111111111111111111\";\n transaction.feePayer = signers[0];\n transaction.add(...instructions);\n\n try {\n return Buffer.from(transaction.serialize({ verifySignatures: false })).toString(\"base64\").length < MAX_BASE64_SIZE;\n } catch (error) {\n return false;\n }\n}\n\n/**\n * Simulates multiple instruction\n */\n/**\n * Simulates multiple instruction\n */\nexport async function simulateMultipleInstruction(\n connection: Connection,\n instructions: TransactionInstruction[],\n keyword: string,\n batchRequest = true,\n): Promise<string[]> {\n const feePayer = new PublicKey(\"RaydiumSimuLateTransaction11111111111111111\");\n\n const transactions: Transaction[] = [];\n\n let transaction = new Transaction();\n transaction.feePayer = feePayer;\n\n for (const instruction of instructions) {\n if (!forecastTransactionSize([...transaction.instructions, instruction], [feePayer])) {\n transactions.push(transaction);\n transaction = new Transaction();\n transaction.feePayer = feePayer;\n }\n transaction.add(instruction);\n }\n if (transaction.instructions.length > 0) {\n transactions.push(transaction);\n }\n\n let results: SimulatedTransactionResponse[] = [];\n\n try {\n results = await simulateTransaction(connection, transactions, batchRequest);\n if (results.find((i) => i.err !== null)) throw Error(\"rpc simulateTransaction error\");\n } catch (error) {\n if (error instanceof Error) {\n logger.logWithError(\"failed to simulate for instructions\", \"RPC_ERROR\", {\n message: error.message,\n });\n }\n }\n\n const logs: string[] = [];\n for (const result of results) {\n logger.debug(\"simulate result:\", result);\n\n if (result.logs) {\n const filteredLog = result.logs.filter((log) => log && log.includes(keyword));\n logger.debug(\"filteredLog:\", logs);\n if (!filteredLog.length) logger.logWithError(\"simulate log not match keyword\", \"keyword\", keyword);\n logs.push(...filteredLog);\n }\n }\n\n return logs;\n}\n\nexport function parseSimulateLogToJson(log: string, keyword: string): any {\n const results = log.match(/{[\"\\w:,]+}/g);\n if (!results || results.length !== 1) {\n return logger.logWithError(`simulate log fail to match json, keyword: ${keyword}`);\n }\n\n return results[0];\n}\n\nexport function parseSimulateValue(log: string, key: string): any {\n const reg = new RegExp(`\"${key}\":(\\\\d+)`, \"g\");\n\n const results = reg.exec(log);\n if (!results || results.length !== 2) {\n return logger.logWithError(`simulate log fail to match key\", key: ${key}`);\n }\n\n return results[1];\n}\n\nexport interface ProgramAddress {\n publicKey: PublicKey;\n nonce: number;\n}\nexport function findProgramAddress(\n seeds: Array<Buffer | Uint8Array>,\n programId: PublicKey,\n): {\n publicKey: PublicKey;\n nonce: number;\n} {\n const [publicKey, nonce] = PublicKey.findProgramAddressSync(seeds, programId);\n return { publicKey, nonce };\n}\n\nexport async function simulateTransaction(\n connection: Connection,\n transactions: Transaction[],\n batchRequest?: boolean,\n): Promise<any[]> {\n let results: any[] = [];\n if (batchRequest) {\n const getLatestBlockhash = await connection.getLatestBlockhash();\n\n const encodedTransactions: string[] = [];\n for (const transaction of transactions) {\n transaction.recentBlockhash = getLatestBlockhash.blockhash;\n transaction.lastValidBlockHeight = getLatestBlockhash.lastValidBlockHeight;\n\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n const message = transaction._compile();\n const signData = message.serialize();\n\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n const wireTransaction = transaction._serialize(signData);\n const encodedTransaction = wireTransaction.toString(\"base64\");\n\n encodedTransactions.push(encodedTransaction);\n }\n\n const batch = encodedTransactions.map((keys) => {\n const args = connection._buildArgs([keys], undefined, \"base64\");\n return {\n methodName: \"simulateTransaction\",\n args,\n };\n });\n\n const reqData: { methodName: string; args: any[] }[][] = [];\n const itemReqIndex = 20;\n for (let i = 0; i < Math.ceil(batch.length / itemReqIndex); i++) {\n reqData.push(batch.slice(i * itemReqIndex, (i + 1) * itemReqIndex));\n }\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n results = await (\n await Promise.all(\n reqData.map(async (i) => (await (connection as any)._rpcBatchRequest(i)).map((ii) => ii.result.value)),\n )\n ).flat();\n } else {\n try {\n results = await Promise.all(\n transactions.map(async (transaction) => await (await connection.simulateTransaction(transaction)).value),\n );\n } catch (error) {\n if (error instanceof Error) {\n logger.logWithError(\"failed to get info for multiple accounts\", \"RPC_ERROR\", {\n message: error.message,\n });\n }\n }\n }\n\n return results;\n}\n\nexport function checkLegacyTxSize({\n instructions,\n payer,\n signers,\n}: {\n instructions: TransactionInstruction[];\n payer: PublicKey;\n signers: PublicKey[];\n}): boolean {\n return forecastTransactionSize(instructions, [payer, ...signers]);\n}\n\nexport function checkV0TxSize({\n instructions,\n payer,\n lookupTableAddressAccount,\n recentBlockhash = Keypair.generate().publicKey.toString(),\n}: {\n instructions: TransactionInstruction[];\n payer: PublicKey;\n lookupTableAddressAccount?: CacheLTA;\n recentBlockhash?: string;\n}): boolean {\n const transactionMessage = new TransactionMessage({\n payerKey: payer,\n recentBlockhash,\n instructions,\n });\n\n const messageV0 = transactionMessage.compileToV0Message(Object.values(lookupTableAddressAccount ?? {}));\n try {\n const buildLength = Buffer.from(new VersionedTransaction(messageV0).serialize()).toString(\"base64\").length;\n return buildLength < MAX_BASE64_SIZE;\n } catch (error) {\n return false;\n }\n}\n\nlet epochInfoCache: { time: number; data?: EpochInfo } = {\n time: 0,\n data: undefined,\n};\n\nexport async function getEpochInfo(connection: Connection): Promise<EpochInfo> {\n if (!epochInfoCache.data || (Date.now() - epochInfoCache.time) / 1000 > 30) {\n const data = await connection.getEpochInfo();\n epochInfoCache = {\n time: Date.now(),\n data,\n };\n return data;\n } else {\n return epochInfoCache.data;\n }\n}\n\nexport const toBuffer = (arr: Buffer | Uint8Array | Array<number>): Buffer => {\n if (Buffer.isBuffer(arr)) {\n return arr;\n } else if (arr instanceof Uint8Array) {\n return Buffer.from(arr.buffer, arr.byteOffset, arr.byteLength);\n } else {\n return Buffer.from(arr);\n }\n};\n\nexport function printSimulate(transactions: Transaction[] | VersionedTransaction[]): string[] {\n const allBase64: string[] = [];\n transactions.forEach((transaction) => {\n if (transaction instanceof Transaction) {\n if (!transaction.recentBlockhash) transaction.recentBlockhash = TOKEN_PROGRAM_ID.toBase58();\n if (!transaction.feePayer) transaction.feePayer = Keypair.generate().publicKey;\n }\n let serialized = transaction.serialize({ requireAllSignatures: false, verifySignatures: false });\n if (transaction instanceof VersionedTransaction) serialized = toBuffer(serialized);\n const base64 = serialized.toString(\"base64\");\n allBase64.push(base64);\n });\n console.log(\"simulate tx string:\", allBase64);\n\n return allBase64;\n}\n","import { Connection, PublicKey, AddressLookupTableAccount } from \"@solana/web3.js\";\nimport { getMultipleAccountsInfo } from \"../accountInfo\";\n\nexport interface CacheLTA {\n [key: string]: AddressLookupTableAccount;\n}\n\nexport async function getMultipleLookupTableInfo({\n connection,\n address,\n}: {\n connection: Connection;\n address: PublicKey[];\n}): Promise<CacheLTA> {\n const dataInfos = await getMultipleAccountsInfo(\n connection,\n [...new Set<string>(address.map((i) => i.toString()))].map((i) => new PublicKey(i)),\n );\n\n const outDict: CacheLTA = {};\n for (let i = 0; i < address.length; i++) {\n const info = dataInfos[i];\n const key = address[i];\n if (!info) continue;\n const lookupAccount = new AddressLookupTableAccount({\n key,\n state: AddressLookupTableAccount.deserialize(info.data),\n });\n outDict[key.toString()] = lookupAccount;\n LOOKUP_TABLE_CACHE[key.toString()] = lookupAccount;\n }\n\n return outDict;\n}\n\nexport const LOOKUP_TABLE_CACHE: CacheLTA = {\n \"2immgwYNHBbyVQKVGCEkgWpi53bLwWNRMB5G2nbgYV17\": new AddressLookupTableAccount({\n key: new PublicKey(\"2immgwYNHBbyVQKVGCEkgWpi53bLwWNRMB5G2nbgYV17\"),\n state: AddressLookupTableAccount.deserialize(\n Buffer.from(\n \"AQAAAP//////////d49+DAAAAAAAAQZMWvw7GUNJdaccNBVnb57OKakxL2BHLYvhRwVILRsgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMGRm/lIRcy/+ytunLDm+e8jOW7xfcSayxDmzpAAAAABt324ddloZPZy+FGzut5rBy0he1fWzeROoz1hX7/AKkG3fbh7nWP3hhCXbzkbM3athr8TYO5DSf+vfko2KGL/AVKU1D4XciC1hSlVnJ4iilt3x6rq9CmBniISTL07vagBqfVFxksXFEhjMlMPUrxf1ja7gibof1E49vZigAAAAAGp9UXGMd0yShWY5hpHV62i164o5tLbVxzVVshAAAAAIyXJY9OJInxuz0QKRSODYMLWhOZ2v8QhASOe9jb6fhZC3BlsePRfEU4nVJ/awTDzVi4bHMaoP21SbbRvAP4KUbIScv+6Yw2LHF/6K0ZjUPibbSWXCirYPGuuVl7zT789IUPLW4CpHr4JNCatp3ELXDLKMv6JJ+37le50lbBJ2LvDQdRqCgtphMF/imcN7mY5YRx2xE1A3MQ+L4QRaYK9u4GRfZP3LsAd00a+IkCpA22UNQMKdq5BFbJuwuOLqc8zxCTDlqxBG8J0HcxtfogQHDK06ukzfaXiNDKAob1MqBHS9lJxDYCwz8gd5DtFqNSTKG5l1zxIaKpDP/sffi2is1H9aKveyXSu5StXElYRl9SD5As0DHE4N0GLnf84/siiKXVyp4Ez121kLcUui/jLLFZEz/BwZK3Ilf9B9OcsEAeDMKAy2vjGSxQODgBz0QwGA+eP4ZjIjrIAQaXENv31QfLlOdXSRCkaybRniDHF4C8YcwhcvsqrOVuTP4B2Na+9wLdtrB31uz2rtlFI5kahdsnp/d1SrASDInYCtTYtdoke4kX+hoKWcEWM4Tle8pTUkUVv4BxS6fje/EzKBE4Qu9N9LMnrw/JNO0hqMVB4rk/2ou4AB1loQ7FZoPwut2o4KZB+0p9xnbrQKw038qjpHar+PyDwvxBRcu5hpHw3dguezeWv+IwvgW5icu8EGkhGa9AkFPPJT7VMSFb8xowveU=\",\n \"base64\",\n ),\n ),\n }),\n};\n","import { AccountInfo, Commitment, Connection, PublicKey } from \"@solana/web3.js\";\nimport { getTransferFeeConfig, unpackMint } from \"@solana/spl-token\";\nimport { chunkArray } from \"./\";\nimport { createLogger } from \"./logger\";\nimport { ReturnTypeFetchMultipleMintInfos } from \"../raydium/type\";\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}\n\nconst logger = createLogger(\"Raydium_accountInfo_util\");\n\nexport async function getMultipleAccountsInfo(\n connection: Connection,\n publicKeys: PublicKey[],\n config?: GetMultipleAccountsInfoConfig,\n): Promise<(AccountInfo<Buffer> | null)[]> {\n const { batchRequest, commitment = \"confirmed\" } = {\n batchRequest: false,\n ...config,\n };\n\n const chunkedKeys = chunkArray(publicKeys, 100);\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}: {\n connection: Connection;\n mints: PublicKey[];\n}): Promise<ReturnTypeFetchMultipleMintInfos> {\n if (mints.length === 0) return {};\n const mintInfos = await getMultipleAccountsInfoWithCustomFlags(\n connection,\n mints.map((i) => ({ pubkey: i })),\n );\n\n const mintK: ReturnTypeFetchMultipleMintInfos = {};\n for (const i of mintInfos) {\n const t = unpackMint(i.pubkey, i.accountInfo, i.accountInfo?.owner);\n mintK[i.pubkey.toString()] = {\n ...t,\n feeConfig: getTransferFeeConfig(t) ?? undefined,\n };\n }\n\n return mintK;\n}\n","/**\n * https://youmightnotneed.com/lodash/\n */\n\nexport function chunkArray<T>(arr: T[], chunkSize = 1, cache: T[][] = []): T[][] {\n const tmp = [...arr];\n if (chunkSize <= 0) return cache;\n while (tmp.length) cache.push(tmp.splice(0, chunkSize));\n return cache;\n}\n\nexport function intersection<T>(arr: T[], ...args: T[][]): T[] {\n return arr.filter((item) => args.every((arr) => arr.includes(item)));\n}\n\nexport function xor<T>(arr: T[], ...args: T[][]): T[] {\n return arr.filter((item) => args.every((arr) => !arr.includes(item)));\n}\n\nexport function uniq<T>(arr: T[]): T[] {\n return [...new Set(arr)];\n}\n","import { PublicKey } from \"@solana/web3.js\";\n\n// raydium\nexport const FARM_PROGRAM_ID_V3 = new PublicKey(\"EhhTKczWMGQt46ynNeRX1WfeagwwJd7ufHvCDjRxjo5Q\");\n// \"fusion\"\nexport const FARM_PROGRAM_ID_V5 = new PublicKey(\"9KEPoZmtHUrBbhWN1v1KWLMkkvwY6WLtAVUCPRtRjP4z\");\n// echosystem\nexport const FARM_PROGRAM_ID_V6 = new PublicKey(\"FarmqiPv5eAj3j1GMdMCMUGXqPUvmquZtMy86QH6rzhG\");\n\nexport const UTIL1216 = new PublicKey(\"CLaimxFqjHzgTJtAGHU47NPhg6qrc5sCnpC4tBLyABQS\");\n\nexport const OPEN_BOOK_PROGRAM = new PublicKey(\"srmqPvymJeFKQ4zGQed1GFppgkRHL9kaELCbyksJtPX\");\nexport const SERUM_PROGRAM_ID_V3 = new PublicKey(\"9xQeWvG816bUx9EPjHmaT23yvVM2ZWbrrpZb9PusVFin\");\n\nexport const AMM_V4 = new PublicKey(\"675kPX9MHTjS2zt1qfr1NYHuzeLXfQM9H24wFSUt1Mp8\");\nexport const AMM_STABLE = new PublicKey(\"5quBtoiQqxF9Jv6KYKctB59NT3gtJD2Y65kdnB1Uev3h\");\nexport const CLMM_PROGRAM_ID = new PublicKey(\"CAMMCzo5YL8w4VFF8KVHrK22GGUsp5VTaW7grrKgrWqK\");\nexport const Router = new PublicKey(\"routeUGWgWzqBWFcrCfv8tritsqukccJPu3q5GPP3xS\");\nexport const FEE_DESTINATION_ID = new PublicKey(\"7YttLkHDoNj9wyDur5pM1ejNaAvT9X4eqaYcHQqtj2G5\");\n\nexport const IDO_PROGRAM_ID_V1 = new PublicKey(\"6FJon3QE27qgPVggARueB22hLvoh22VzJpXv4rBEoSLF\");\nexport const IDO_PROGRAM_ID_V2 = new PublicKey(\"CC12se5To1CdEuw7fDS27B7Geo5jJyL7t5UK2B44NgiH\");\nexport const IDO_PROGRAM_ID_V3 = new PublicKey(\"9HzJyW1qZsEiSfMUf6L2jo3CcTKAyBmSyKdwQeYisHrC\");\nexport const IDO_PROGRAM_ID_V4 = new PublicKey(\"DropEU8AvevN3UrXWXTMuz3rqnMczQVNjq3kcSdW2SQi\");\n\nexport const CREATE_CPMM_POOL_PROGRAM = new PublicKey(\"CPMMoo8L3F4NbTegBCKVNunggL7H1ZpdTHKxQB5qKP1C\");\nexport const CREATE_CPMM_POOL_AUTH = new PublicKey(\"GpMZbSM2GgvTKHJirzeGfMFoaZ8UR2X7F4v8vHTvxFbL\");\nexport const CREATE_CPMM_POOL_FEE_ACC = new PublicKey(\"DNXgeM9EiiaAbaWvwjHj9fQQLAX5ZsfHyvmYUNRAdNC8\");\n\nexport const DEV_CREATE_CPMM_POOL_PROGRAM = new PublicKey(\"CPMDWBwJDtYax9qW7AyRuVC19Cc4L4Vcy4n2BHAbHkCW\");\nexport const DEV_CREATE_CPMM_POOL_AUTH = new PublicKey(\"7rQ1QFNosMkUCuh7Z7fPbTHvh73b68sQYdirycEzJVuw\");\nexport const DEV_CREATE_CPMM_POOL_FEE_ACC = new PublicKey(\"G11FKBRaAkHAKuLCgLM6K6NUc9rTjPAznRCjZifrTQe2\");\n\nexport const IDO_ALL_PROGRAM = {\n IDO_PROGRAM_ID_V1,\n IDO_PROGRAM_ID_V2,\n IDO_PROGRAM_ID_V3,\n IDO_PROGRAM_ID_V4,\n};\n\nexport const ALL_PROGRAM_ID = {\n AMM_V4,\n AMM_STABLE,\n CLMM_PROGRAM_ID,\n\n FARM_PROGRAM_ID_V3,\n FARM_PROGRAM_ID_V5,\n FARM_PROGRAM_ID_V6,\n\n OPEN_BOOK_PROGRAM,\n SERUM_PROGRAM_ID_V3,\n\n UTIL1216,\n\n Router,\n\n CREATE_CPMM_POOL_PROGRAM,\n CREATE_CPMM_POOL_AUTH,\n CREATE_CPMM_POOL_FEE_ACC,\n};\n\nexport type ProgramIdConfig = Partial<typeof ALL_PROGRAM_ID>;\n\nexport const DEVNET_PROGRAM_ID = {\n SERUM_MARKET: PublicKey.default,\n OPENBOOK_MARKET: new PublicKey(\"EoTcMgcDRTJVZDMZWBoU6rhYHZfkNTVEAfz3uUJRcYGj\"),\n\n UTIL1216: PublicKey.default,\n\n FarmV3: new PublicKey(\"85BFyr98MbCUU9MVTEgzx1nbhWACbJqLzho6zd6DZcWL\"),\n FarmV5: new PublicKey(\"EcLzTrNg9V7qhcdyXDe2qjtPkiGzDM2UbdRaeaadU5r2\"),\n FarmV6: new PublicKey(\"Farm2hJLcqPtPg8M4rR6DMrsRNc5TPm5Cs4bVQrMe2T7\"),\n\n AmmV4: new PublicKey(\"HWy1jotHpo6UqeQxx49dpYYdQB8wj9Qk9MdxwjLvDHB8\"),\n AmmStable: new PublicKey(\"DDg4VmQaJV9ogWce7LpcjBA9bv22wRp5uaTPa5pGjijF\"),\n\n CLMM: new PublicKey(\"devi51mZmdwUJGU9hjN27vEz64Gps7uUefqxg27EAtH\"),\n\n Router: new PublicKey(\"BVChZ3XFEwTMUk1o9i3HAf91H6mFxSwa5X2wFAWhYPhU\"),\n\n CREATE_CPMM_POOL_PROGRAM: DEV_CREATE_CPMM_POOL_PROGRAM,\n CREATE_CPMM_POOL_AUTH: DEV_CREATE_CPMM_POOL_AUTH,\n CREATE_CPMM_POOL_FEE_ACC: DEV_CREATE_CPMM_POOL_FEE_ACC,\n\n FEE_DESTINATION_ID: new PublicKey(\"3XMrhbv989VxAMi3DErLV9eJht1pHppW5LbKxe9fkEFR\"),\n};\n","import { PublicKey } from \"@solana/web3.js\";\n\nimport { findProgramAddress } from \"./txTool/txUtils\";\nimport { TOKEN_PROGRAM_ID } from \"@solana/spl-token\";\n\nexport function getATAAddress(\n owner: PublicKey,\n mint: PublicKey,\n programId?: PublicKey,\n): {\n publicKey: PublicKey;\n nonce: number;\n} {\n return findProgramAddress(\n [owner.toBuffer(), (programId ?? TOKEN_PROGRAM_ID).toBuffer(), mint.toBuffer()],\n new PublicKey(\"ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL\"),\n );\n}\n","import { EpochInfo } from \"@solana/web3.js\";\nimport { TransferFeeConfig, TransferFee } from \"@solana/spl-token\";\nimport BN from \"bn.js\";\n\nimport { GetTransferAmountFee } from \"../raydium/type\";\nimport { TransferFeeDataBaseType } from \"../api/type\";\n\nconst POINT = 10_000;\nexport function getTransferAmountFee(\n amount: BN,\n feeConfig: TransferFeeConfig | undefined,\n epochInfo: EpochInfo,\n addFee: boolean,\n): GetTransferAmountFee {\n if (feeConfig === undefined) {\n return {\n amount,\n fee: undefined,\n expirationTime: undefined,\n };\n }\n\n const nowFeeConfig: TransferFee =\n epochInfo.epoch < feeConfig.newerTransferFee.epoch ? feeConfig.olderTransferFee : feeConfig.newerTransferFee;\n const maxFee = new BN(nowFeeConfig.maximumFee.toString());\n const expirationTime: number | undefined =\n epochInfo.epoch < feeConfig.newerTransferFee.epoch\n ? ((Number(feeConfig.newerTransferFee.epoch) * epochInfo.slotsInEpoch - epochInfo.absoluteSlot) * 400) / 1000\n : undefined;\n\n if (addFee) {\n if (nowFeeConfig.transferFeeBasisPoints === POINT) {\n const nowMaxFee = new BN(nowFeeConfig.maximumFee.toString());\n return {\n amount: amount.add(nowMaxFee),\n fee: nowMaxFee,\n expirationTime,\n };\n } else {\n const _TAmount = BNDivCeil(amount.mul(new BN(POINT)), new BN(POINT - nowFeeConfig.transferFeeBasisPoints));\n\n const nowMaxFee = new BN(nowFeeConfig.maximumFee.toString());\n const TAmount = _TAmount.sub(amount).gt(nowMaxFee) ? amount.add(nowMaxFee) : _TAmount;\n\n const _fee = BNDivCeil(TAmount.mul(new BN(nowFeeConfig.transferFeeBasisPoints)), new BN(POINT));\n const fee = _fee.gt(maxFee) ? maxFee : _fee;\n return {\n amount: TAmount,\n fee,\n expirationTime,\n };\n }\n } else {\n const _fee = BNDivCeil(amount.mul(new BN(nowFeeConfig.transferFeeBasisPoints)), new BN(POINT));\n const fee = _fee.gt(maxFee) ? maxFee : _fee;\n\n return {\n amount,\n fee,\n expirationTime,\n };\n }\n}\n\nexport function getTransferAmountFeeV2(\n amount: BN,\n _feeConfig: TransferFeeDataBaseType | undefined,\n epochInfo: EpochInfo,\n addFee: boolean,\n): GetTransferAmountFee {\n if (_feeConfig === undefined) {\n return {\n amount,\n fee: undefined,\n expirationTime: undefined,\n };\n }\n const feeConfig = {\n ..._feeConfig,\n olderTransferFee: {\n epoch: BigInt(_feeConfig.olderTransferFee.epoch),\n maximumFee: BigInt(_feeConfig.olderTransferFee.maximumFee),\n transferFeeBasisPoints: _feeConfig.olderTransferFee.transferFeeBasisPoints,\n },\n newerTransferFee: {\n epoch: BigInt(_feeConfig.newerTransferFee.epoch),\n maximumFee: BigInt(_feeConfig.newerTransferFee.maximumFee),\n transferFeeBasisPoints: _feeConfig.newerTransferFee.transferFeeBasisPoints,\n },\n };\n\n const nowFeeConfig: TransferFee =\n epochInfo.epoch < feeConfig.newerTransferFee.epoch ? feeConfig.olderTransferFee : feeConfig.newerTransferFee;\n const maxFee = new BN(nowFeeConfig.maximumFee.toString());\n const expirationTime: number | undefined =\n epochInfo.epoch < feeConfig.newerTransferFee.epoch\n ? ((Number(feeConfig.newerTransferFee.epoch) * epochInfo.slotsInEpoch - epochInfo.absoluteSlot) * 400) / 1000\n : undefined;\n\n if (addFee) {\n if (nowFeeConfig.transferFeeBasisPoints === POINT) {\n const nowMaxFee = new BN(nowFeeConfig.maximumFee.toString());\n return {\n amount: amount.add(nowMaxFee),\n fee: nowMaxFee,\n expirationTime,\n };\n } else {\n const _TAmount = BNDivCeil(amount.mul(new BN(POINT)), new BN(POINT - nowFeeConfig.transferFeeBasisPoints));\n\n const nowMaxFee = new BN(nowFeeConfig.maximumFee.toString());\n const TAmount = _TAmount.sub(amount).gt(nowMaxFee) ? amount.add(nowMaxFee) : _TAmount;\n\n const _fee = BNDivCeil(TAmount.mul(new BN(nowFeeConfig.transferFeeBasisPoints)), new BN(POINT));\n const fee = _fee.gt(maxFee) ? maxFee : _fee;\n return {\n amount: TAmount,\n fee,\n expirationTime,\n };\n }\n } else {\n const _fee = BNDivCeil(amount.mul(new BN(nowFeeConfig.transferFeeBasisPoints)), new BN(POINT));\n const fee = _fee.gt(maxFee) ? maxFee : _fee;\n\n return {\n amount,\n fee,\n expirationTime,\n };\n }\n}\n\nexport function minExpirationTime(\n expirationTime1: number | undefined,\n expirationTime2: number | undefined,\n): number | undefined {\n if (expirationTime1 === undefined) return expirationTime2;\n if (expirationTime2 === undefined) return expirationTime1;\n\n return Math.min(expirationTime1, expirationTime2);\n}\n\nexport function BNDivCeil(bn1: BN, bn2: BN): BN {\n const { div, mod } = bn1.divmod(bn2);\n\n if (mod.gt(new BN(0))) {\n return div.add(new BN(1));\n } else {\n return div;\n }\n}\n","import { PublicKey } from \"@solana/web3.js\";\n\nimport { createLogger, Logger } from \"../common/logger\";\nimport { TxBuilder } from \"../common/txTool/txTool\";\n\nimport { Raydium } from \"./\";\n\nexport interface ModuleBaseProps {\n scope: Raydium;\n moduleName: string;\n}\n\nconst joinMsg = (...args: (string | number | Record<string, any>)[]): string =>\n args\n .map((arg) => {\n try {\n return typeof arg === \"object\" ? JSON.stringify(arg) : arg;\n } catch {\n return arg;\n }\n })\n .join(\", \");\nexport default class ModuleBase {\n public scope: Raydium;\n private disabled = false;\n protected logger: Logger;\n\n constructor({ scope, moduleName }: ModuleBaseProps) {\n this.scope = scope;\n this.logger = createLogger(moduleName);\n }\n\n protected createTxBuilder(feePayer?: PublicKey): TxBuilder {\n this.scope.checkOwner();\n return new TxBuilder({\n connection: this.scope.connection,\n feePayer: feePayer || this.scope.ownerPubKey,\n cluster: this.scope.cluster,\n owner: this.scope.owner,\n signAllTransactions: this.scope.signAllTransactions,\n });\n }\n\n public logDebug(...args: (string | number | Record<string, any>)[]): void {\n this.logger.debug(joinMsg(args));\n }\n\n public logInfo(...args: (string | number | Record<string, any>)[]): void {\n this.logger.info(joinMsg(args));\n }\n\n public logAndCreateError(...args: (string | number | Record<string, any>)[]): void {\n const message = joinMsg(args);\n // this.logger.error(message);\n throw new Error(message);\n }\n\n public checkDisabled(): void {\n if (this.disabled || !this.scope) this.logAndCreateError(\"module not working\");\n }\n}\n","import {\n createInitializeAccountInstruction,\n createCloseAccountInstruction,\n createTransferInstruction,\n TOKEN_PROGRAM_ID,\n} from \"@solana/spl-token\";\nimport { Commitment, Connection, PublicKey, Signer, SystemProgram, TransactionInstruction } from \"@solana/web3.js\";\nimport BN from \"bn.js\";\nimport { generatePubKey } from \"./util\";\nimport { BigNumberish, parseBigNumberish } from \"@/common\";\nimport { AddInstructionParam } from \"@/common/txTool/txTool\";\nimport { InstructionType } from \"@/common/txTool/txType\";\nimport { TOKEN_WSOL } from \"../token/constant\";\n\nimport { splAccountLayout } from \"./layout\";\n\nexport function initTokenAccountInstruction(params: {\n mint: PublicKey;\n tokenAccount: PublicKey;\n owner: PublicKey;\n programId?: PublicKey;\n}): TransactionInstruction {\n const { mint, tokenAccount, owner, programId = TOKEN_PROGRAM_ID } = params;\n return createInitializeAccountInstruction(tokenAccount, mint, owner, programId);\n}\n\nexport function closeAccountInstruction(params: {\n tokenAccount: PublicKey;\n payer: PublicKey;\n multiSigners?: Signer[];\n owner: PublicKey;\n programId?: PublicKey;\n}): TransactionInstruction {\n const { tokenAccount, payer, multiSigners = [], owner, programId = TOKEN_PROGRAM_ID } = params;\n return createCloseAccountInstruction(tokenAccount, payer, owner, multiSigners, programId);\n}\n\ninterface CreateWSolTokenAccount {\n connection: Connection;\n payer: PublicKey;\n owner: PublicKey;\n amount: BigNumberish;\n commitment?: Commitment;\n skipCloseAccount?: boolean;\n}\n/**\n * WrappedNative account = wsol account\n */\nexport async function createWSolAccountInstructions(params: CreateWSolTokenAccount): Promise<\n AddInstructionParam & {\n addresses: { newAccount: PublicKey };\n }\n> {\n const { connection, amount, commitment, payer, owner, skipCloseAccount } = params;\n\n const balanceNeeded = await connection.getMinimumBalanceForRentExemption(splAccountLayout.span, commitment);\n const lamports = parseBigNumberish(amount).add(new BN(balanceNeeded));\n const newAccount = generatePubKey({ fromPublicKey: payer, programId: TOKEN_PROGRAM_ID });\n\n return {\n addresses: { newAccount: newAccount.publicKey },\n signers: [],\n instructions: [\n SystemProgram.createAccountWithSeed({\n fromPubkey: payer,\n basePubkey: payer,\n seed: newAccount.seed,\n newAccountPubkey: newAccount.publicKey,\n lamports: lamports.toNumber(),\n space: splAccountLayout.span,\n programId: TOKEN_PROGRAM_ID,\n }),\n initTokenAccountInstruction({\n mint: new PublicKey(TOKEN_WSOL.address),\n tokenAccount: newAccount.publicKey,\n owner,\n programId: TOKEN_PROGRAM_ID,\n }),\n ],\n instructionTypes: [InstructionType.CreateAccount, InstructionType.InitAccount],\n endInstructionTypes: skipCloseAccount ? [] : [InstructionType.CloseAccount],\n endInstructions: skipCloseAccount\n ? []\n : [\n closeAccountInstruction({\n tokenAccount: newAccount.publicKey,\n payer,\n owner,\n }),\n ],\n };\n}\n\nexport function makeTransferInstruction({\n source,\n destination,\n owner,\n amount,\n multiSigners = [],\n tokenProgram = TOKEN_PROGRAM_ID,\n}: {\n source: PublicKey;\n destination: PublicKey;\n owner: PublicKey;\n amount: BigNumberish;\n multiSigners?: Signer[];\n tokenProgram?: PublicKey;\n}): TransactionInstruction {\n return createTransferInstruction(source, destination, owner, BigInt(String(amount)), multiSigners, tokenProgram);\n}\n","import { AccountInfo, PublicKey, RpcResponseAndContext, Keypair, GetProgramAccountsResponse } from \"@solana/web3.js\";\nimport { TOKEN_PROGRAM_ID } from \"@solana/spl-token\";\nimport BN from \"bn.js\";\nimport { createLogger, getATAAddress } from \"@/common\";\n\nimport { splAccountLayout } from \"./layout\";\nimport { TokenAccount, TokenAccountRaw } from \"./types\";\nimport { sha256 } from \"@noble/hashes/sha256\";\n\nconst logger = createLogger(\"Raydium_Util\");\n\nexport interface ParseTokenAccount {\n owner: PublicKey;\n solAccountResp?: AccountInfo<Buffer> | null;\n tokenAccountResp: RpcResponseAndContext<GetProgramAccountsResponse>;\n}\n\nexport function parseTokenAccountResp({ owner, solAccountResp, tokenAccountResp }: ParseTokenAccount): {\n tokenAccounts: TokenAccount[];\n tokenAccountRawInfos: TokenAccountRaw[];\n} {\n const tokenAccounts: TokenAccount[] = [];\n const tokenAccountRawInfos: TokenAccountRaw[] = [];\n\n for (const { pubkey, account } of tokenAccountResp.value) {\n const accountInfo = splAccountLayout.decode(account.data);\n const { mint, amount } = accountInfo;\n tokenAccounts.push({\n publicKey: pubkey,\n mint,\n amount,\n isAssociated: getATAAddress(owner, mint, account.owner).publicKey.equals(pubkey),\n isNative: false,\n programId: account.owner,\n });\n // todo programId should get from api\n tokenAccountRawInfos.push({ pubkey, accountInfo, programId: account.owner });\n }\n\n if (solAccountResp) {\n tokenAccounts.push({\n mint: PublicKey.default,\n amount: new BN(solAccountResp.lamports),\n isNative: true,\n programId: solAccountResp.owner,\n });\n }\n\n return {\n tokenAccounts,\n tokenAccountRawInfos,\n };\n}\n\nexport function generatePubKey({\n fromPublicKey,\n programId = TOKEN_PROGRAM_ID,\n}: {\n fromPublicKey: PublicKey;\n programId: PublicKey;\n}): { publicKey: PublicKey; seed: string } {\n const seed = Keypair.generate().publicKey.toBase58().slice(0, 32);\n const publicKey = createWithSeed(fromPublicKey, seed, programId);\n return { publicKey, seed };\n}\n\nfunction createWithSeed(fromPublicKey: PublicKey, seed: string, programId: PublicKey): PublicKey {\n const buffer = Buffer.concat([fromPublicKey.toBuffer(), Buffer.from(seed), programId.toBuffer()]);\n const publicKeyBytes = sha256(buffer);\n return new PublicKey(publicKeyBytes);\n}\n","import { PublicKey } from \"@solana/web3.js\";\nimport BN, { isBN } from \"bn.js\";\n\nimport {\n bits,\n blob,\n Blob,\n Layout,\n offset as _offset,\n seq as _seq,\n Structure as _Structure,\n u32 as _u32,\n u8 as _u8,\n UInt,\n union as _union,\n Union as _Union,\n} from \"./buffer-layout\";\n\nexport * from \"./buffer-layout\";\nexport { blob };\n\nexport class BNLayout<P extends string = \"\"> extends Layout<BN, P> {\n blob: Layout<Buffer>;\n signed: boolean;\n\n constructor(span: number, signed: boolean, property?: P) {\n //@ts-expect-error type wrong for super()'s type different from extends, but it desn't matter\n super(span, property);\n this.blob = blob(span);\n this.signed = signed;\n }\n\n /** @override */\n decode(b: Buffer, offset = 0): BN {\n const num = new BN(this.blob.decode(b, offset), 10, \"le\");\n if (this.signed) {\n return num.fromTwos(this.span * 8).clone();\n }\n return num;\n }\n\n /** @override */\n encode(src: BN, b: Buffer, offset = 0): number {\n if (typeof src === \"number\") src = new BN(src); // src will pass a number accidently in union\n if (this.signed) {\n src = src.toTwos(this.span * 8);\n }\n return this.blob.encode(src.toArrayLike(Buffer, \"le\", this.span), b, offset);\n }\n}\n\nexport class WideBits<P extends string = \"\"> extends Layout<Record<string, boolean>, P> {\n _lower: any;\n _upper: any;\n // TODO: unknown\n constructor(property?: P) {\n //@ts-expect-error type wrong for super()'s type different from extends , but it desn't matter\n super(8, property);\n this._lower = bits(_u32(), false);\n this._upper = bits(_u32(), false);\n }\n\n addBoolean(property: string): void {\n if (this._lower.fields.length < 32) {\n this._lower.addBoolean(property);\n } else {\n this._upper.addBoolean(property);\n }\n }\n\n decode(b: Buffer, offset = 0): Record<string, boolean> {\n const lowerDecoded = this._lower.decode(b, offset);\n const upperDecoded = this._upper.decode(b, offset + this._lower.span);\n return { ...lowerDecoded, ...upperDecoded };\n }\n\n encode(src: any /* TEMP */, b: Buffer, offset = 0): any {\n return this._lower.encode(src, b, offset) + this._upper.encode(src, b, offset + this._lower.span);\n }\n}\n\nexport function u8<P extends string = \"\">(property?: P): UInt<number, P> {\n return new UInt(1, property);\n}\n\nexport function u32<P extends string = \"\">(property?: P): UInt<number, P> {\n return new UInt(4, property);\n}\n\nexport function u64<P extends string = \"\">(property?: P): BNLayout<P> {\n return new BNLayout(8, false, property);\n}\n\nexport function u128<P extends string = \"\">(property?: P): BNLayout<P> {\n return new BNLayout(16, false, property);\n}\n\nexport function i8<P extends string = \"\">(property?: P): BNLayout<P> {\n return new BNLayout(1, true, property);\n}\n\nexport function i64<P extends string = \"\">(property?: P): BNLayout<P> {\n return new BNLayout(8, true, property);\n}\n\nexport function i128<P extends string = \"\">(property?: P): BNLayout<P> {\n return new BNLayout(16, true, property);\n}\n\nexport class WrappedLayout<T, U, P extends string = \"\"> extends Layout<U, P> {\n layout: Layout<T>;\n decoder: (data: T) => U;\n encoder: (src: U) => T;\n\n constructor(layout: Layout<T>, decoder: (data: T) => U, encoder: (src: U) => T, property?: P) {\n //@ts-expect-error type wrong for super()'s type different from extends , but it desn't matter\n super(layout.span, property);\n this.layout = layout;\n this.decoder = decoder;\n this.encoder = encoder;\n }\n\n decode(b: Buffer, offset?: number): U {\n return this.decoder(this.layout.decode(b, offset));\n }\n\n encode(src: U, b: Buffer, offset?: number): number {\n return this.layout.encode(this.encoder(src), b, offset);\n }\n\n getSpan(b: Buffer, offset?: number): number {\n return this.layout.getSpan(b, offset);\n }\n}\n\nexport function publicKey<P extends string = \"\">(property?: P): Layout<PublicKey, P> {\n return new WrappedLayout(\n blob(32),\n (b: Buffer) => new PublicKey(b),\n (key: PublicKey) => key.toBuffer(),\n property,\n );\n}\n\nexport class OptionLayout<T, P> extends Layout<T | null, P> {\n layout: Layout<T>;\n discriminator: Layout<number>;\n\n constructor(layout: Layout<T>, property?: P) {\n //@ts-expect-error type wrong for super()'s type different from extends , but it desn't matter\n super(-1, property);\n this.layout = layout;\n this.discriminator = _u8();\n }\n\n encode(src: T | null, b: Buffer, offset = 0): number {\n if (src === null || src === undefined) {\n return this.discriminator.encode(0, b, offset);\n }\n this.discriminator.encode(1, b, offset);\n return this.layout.encode(src, b, offset + 1) + 1;\n }\n\n decode(b: Buffer, offset = 0): T | null {\n const discriminator = this.discriminator.decode(b, offset);\n if (discriminator === 0) {\n return null;\n } else if (discriminator === 1) {\n return this.layout.decode(b, offset + 1);\n }\n throw new Error(\"Invalid option \" + this.property);\n }\n\n getSpan(b: Buffer, offset = 0): number {\n const discriminator = this.discriminator.decode(b, offset);\n if (discriminator === 0) {\n return 1;\n } else if (discriminator === 1) {\n return this.layout.getSpan(b, offset + 1) + 1;\n }\n throw new Error(\"Invalid option \" + this.property);\n }\n}\n\nexport function option<T, P extends string = \"\">(layout: Layout<T>, property?: P): Layout<T | null, P> {\n return new OptionLayout<T, P>(layout, property);\n}\n\nexport function bool<P extends string = \"\">(property?: P): Layout<boolean, P> {\n return new WrappedLayout(_u8(), decodeBool, encodeBool, property);\n}\n\nexport function decodeBool(value: number): boolean {\n if (value === 0) {\n return false;\n } else if (value === 1) {\n return true;\n }\n throw new Error(\"Invalid bool: \" + value);\n}\n\nexport function encodeBool(value: boolean): number {\n return value ? 1 : 0;\n}\n\nexport function vec<T, P extends string = \"\">(elementLayout: Layout<T>, property?: P): Layout<T[], P> {\n const length = _u32(\"length\");\n const layout: Layout<{ values: T[] }> = struct([\n length,\n seq(elementLayout, _offset(length, -length.span), \"values\"),\n ]) as any; // Something I don't know\n return new WrappedLayout(\n layout,\n ({ values }) => values,\n (values) => ({ values }),\n property,\n );\n}\n\nexport function tagged<T, P extends string = \"\">(tag: BN, layout: Layout<T>, property?: P): Layout<T, P> {\n const wrappedLayout: Layout<{ tag: BN; data: T }> = struct([u64(\"tag\"), layout.replicate(\"data\")]) as any; // Something I don't know\n\n function decodeTag({ tag: receivedTag, data }: { tag: BN; data: T }): T {\n if (!receivedTag.eq(tag)) {\n throw new Error(\"Invalid tag, expected: \" + tag.toString(\"hex\") + \", got: \" + receivedTag.toString(\"hex\"));\n }\n return data;\n }\n\n return new WrappedLayout(wrappedLayout, decodeTag, (data) => ({ tag, data }), property);\n}\n\nexport function vecU8<P extends string = \"\">(property?: P): Layout<Buffer, P> {\n const length = _u32(\"length\");\n const layout: Layout<{ data: Buffer }> = struct([length, blob(_offset(length, -length.span), \"data\")]) as any; // Something I don't know\n return new WrappedLayout(\n layout,\n ({ data }) => data,\n (data) => ({ data }),\n property,\n );\n}\n\nexport function str<P extends string = \"\">(property?: P): Layout<string, P> {\n return new WrappedLayout(\n vecU8(),\n (data) => data.toString(\"utf-8\"),\n (s) => Buffer.from(s, \"utf-8\"),\n property,\n );\n}\n\nexport interface EnumLayout<T, P extends string = \"\"> extends Layout<T, P> {\n registry: Record<string, Layout<any>>;\n}\n\nexport function rustEnum<T, P extends string = \"\">(variants: Layout<any>[], property?: P): EnumLayout<T, P> {\n const unionLayout = _union(_u8(), property);\n variants.forEach((variant, index) => unionLayout.addVariant(index, variant, variant.property));\n return unionLayout as any; // ?why use UnionLayout? This must be a fault\n}\n\nexport function array<T, P extends string = \"\">(\n elementLayout: Layout<T>,\n length: number,\n property?: P,\n): Layout<T[], P> {\n const layout = struct([seq(elementLayout, length, \"values\")]) as any as Layout<{ values: T[] }>; // Something I don't know\n return new WrappedLayout(\n layout,\n ({ values }) => values,\n (values) => ({ values }),\n property,\n );\n}\n\nexport class Structure<T, P, D> extends _Structure<T, P, D> {\n /** @override */\n decode(b: Buffer, offset?: number): D {\n return super.decode(b, offset);\n }\n}\n\nexport function struct<T, P extends string = \"\">(\n fields: T,\n property?: P,\n decodePrefixes?: boolean,\n): T extends Layout<infer Value, infer Property>[]\n ? Structure<\n Value,\n P,\n {\n [K in Exclude<Extract<Property, string>, \"\">]: Extract<T[number], Layout<any, K>> extends Layout<infer V, any>\n ? V\n : any;\n }\n >\n : any {\n //@ts-expect-error this type is not quite satisfied the define, but, never no need to worry about.\n return new Structure(fields, property, decodePrefixes);\n}\n\nexport type GetLayoutSchemaFromStructure<T extends Structure<any, any, any>> = T extends Structure<any, any, infer S>\n ? S\n : any;\nexport type GetStructureFromLayoutSchema<S> = Structure<any, any, S>;\n\nexport class Union<Schema> extends _Union<Schema> {\n encodeInstruction(instruction: any): Buffer {\n const instructionMaxSpan = Math.max(...Object.values(this.registry).map((r) => r.span));\n const b = Buffer.alloc(instructionMaxSpan);\n return b.slice(0, this.encode(instruction, b));\n }\n\n decodeInstruction(instruction: any): Partial<Schema> {\n return this.decode(instruction);\n }\n}\nexport function union<UnionSchema extends { [key: string]: any } = any>(\n discr: any,\n defaultLayout?: any,\n property?: string,\n): Union<UnionSchema> {\n return new Union(discr, defaultLayout, property);\n}\n\nclass Zeros extends Blob {\n decode(b: Buffer, offset: number): Buffer {\n const slice = super.decode(b, offset);\n if (!slice.every((v) => v === 0)) {\n throw new Error(\"nonzero padding bytes\");\n }\n return slice;\n }\n}\n\nexport function zeros(length: number): Zeros {\n return new Zeros(length);\n}\n\nexport function seq<T, P extends string = \"\", AnotherP extends string = \"\">(\n elementLayout: Layout<T, P>,\n count: number | BN | Layout<BN | number, P>,\n property?: AnotherP,\n): Layout<T[], AnotherP> {\n let parsedCount: number;\n const superCount =\n typeof count === \"number\"\n ? count\n : isBN(count)\n ? count.toNumber()\n : new Proxy(count as unknown as Layout<number> /* pretend to be Layout<number> */, {\n get(target, property): any {\n if (!parsedCount) {\n // get count in targetLayout. note that count may be BN\n const countProperty = Reflect.get(target, \"count\");\n\n // let targetLayout's property:count be a number\n parsedCount = isBN(countProperty) ? countProperty.toNumber() : countProperty;\n\n // record the count\n Reflect.set(target, \"count\", parsedCount);\n }\n return Reflect.get(target, property);\n },\n set(target, property, value): any {\n if (property === \"count\") {\n parsedCount = value;\n }\n return Reflect.set(target, property, value);\n },\n });\n\n // @ts-expect-error force type\n return _seq(elementLayout, superCount, property);\n}\n","import {\n bits as _bits,\n BitStructure as _BitStructure,\n blob as _blob,\n Blob as _Blob,\n cstr as _cstr,\n f32 as _f32,\n f32be as _f32be,\n f64 as _f64,\n f64be as _f64be,\n greedy as _greedy,\n Layout as _Layout,\n ns64 as _ns64,\n ns64be as _ns64be,\n nu64 as _nu64,\n nu64be as _nu64be,\n offset as _offset,\n s16 as _s16,\n s16be as _s16be,\n s24 as _s24,\n s24be as _s24be,\n s32 as _s32,\n s32be as _s32be,\n s40 as _s40,\n s40be as _s40be,\n s48 as _s48,\n s48be as _s48be,\n s8 as _s8,\n seq as _seq,\n struct as _struct,\n Structure as _Structure,\n u16 as _u16,\n u16be as _u16be,\n u24 as _u24,\n u24be as _u24be,\n u32 as _u32,\n u32be as _u32be,\n u40 as _u40,\n u40be as _u40be,\n u48 as _u48,\n u48be as _u48be,\n u8 as _u8,\n UInt as _UInt,\n union as _union,\n Union as _Union,\n unionLayoutDiscriminator as _unionLayoutDiscriminator,\n utf8 as _utf8,\n} from \"@solana/buffer-layout\";\n\n//#region ------------------- Layout -------------------\nexport interface Layout<T = any, P = \"\"> {\n span: number;\n property?: P;\n decode(b: Buffer, offset?: number): T;\n encode(src: T, b: Buffer, offset?: number): number;\n getSpan(b: Buffer, offset?: number): number;\n replicate<AP extends string>(name: AP): Layout<T, AP>;\n}\nexport interface LayoutConstructor {\n new <T, P>(): Layout<T, P>; // for class extends syntex\n new <T, P>(span?: T, property?: P): Layout<T, P>;\n readonly prototype: Layout;\n}\nexport const Layout = _Layout as unknown as LayoutConstructor;\n//#endregion\n\n//#region ------------------- Structure -------------------\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nexport interface Structure<T = any, P = \"\", DecodeSchema extends { [key: string]: any } = any>\n extends Layout<DecodeSchema, P> {\n span: number;\n decode(b: Buffer, offset?: number): DecodeSchema;\n layoutFor<AP extends string>(property: AP): Layout<DecodeSchema[AP]>;\n offsetOf<AP extends string>(property: AP): number;\n}\ninterface StructureConstructor {\n new <T = any, P = \"\", DecodeSchema extends { [key: string]: any } = any>(): Structure<T, P, DecodeSchema>;\n new <T = any, P = \"\", DecodeSchema extends { [key: string]: any } = any>(\n fields: T,\n property?: P,\n decodePrefixes?: boolean,\n ): Structure<T, P, DecodeSchema>;\n}\nexport const Structure = _Structure as unknown as StructureConstructor;\n//#endregion\n\n//#region ------------------- Union -------------------\nexport interface Union<UnionSchema extends { [key: string]: any } = any> extends Layout {\n registry: object;\n decode(b: Buffer, offset?: number): Partial<UnionSchema>;\n addVariant(\n variant: number,\n layout: Structure<any, any, Partial<UnionSchema>> | Layout<any, keyof UnionSchema>,\n property?: string,\n ): any /* TEMP: code in Layout.js 1809 */;\n}\ninterface UnionConstructor {\n new <UnionSchema extends { [key: string]: any } = any>(): Union<UnionSchema>;\n new <UnionSchema extends { [key: string]: any } = any>(\n discr: Layout<any, any>,\n defaultLayout: Layout<any, any>,\n property?: string,\n ): Union<UnionSchema>;\n}\nexport const Union = _Union as unknown as UnionConstructor;\n//#endregion\n\n//#region ------------------- BitStructure -------------------\nexport type BitStructure<T = unknown /* TEMP */, P = \"\"> = Layout<T, P>;\ninterface BitStructureConstructor {\n new (...params: any[]): BitStructure;\n}\nexport const BitStructure = _BitStructure as BitStructureConstructor;\n//#endregion\n\n//#region ------------------- UInt -------------------\nexport type UInt<T = any, P = \"\"> = Layout<T, P>;\ninterface UIntConstructor {\n new <T, P>(span?: T, property?: P): UInt<T, P>;\n}\nexport const UInt = _UInt as UIntConstructor;\n//#endregion\n\n//#region ------------------- Blob -------------------\nexport type Blob<P extends string = \"\"> = Layout<Buffer, P>;\ninterface BlobConstructor {\n new (...params: ConstructorParameters<LayoutConstructor>): Blob;\n}\nexport const Blob = _Blob as unknown as BlobConstructor;\n//#endregion\n\nexport const greedy = _greedy as <P extends string = \"\">(elementSpan?: number, property?: P) => Layout<number, P>;\nexport const u8 = _u8 as <P extends string = \"\">(property?: P) => Layout<number, P>;\nexport const u16 = _u16 as <P extends string = \"\">(property?: P) => Layout<number, P>;\nexport const u24 = _u24 as <P extends string = \"\">(property?: P) => Layout<number, P>;\nexport const u32 = _u32 as <P extends string = \"\">(property?: P) => Layout<number, P>;\nexport const u40 = _u40 as <P extends string = \"\">(property?: P) => Layout<number, P>;\nexport const u48 = _u48 as <P extends string = \"\">(property?: P) => Layout<number, P>;\nexport const nu64 = _nu64 as <P extends string = \"\">(property?: P) => Layout<number, P>;\nexport const u16be = _u16be as <P extends string = \"\">(property?: P) => Layout<number, P>;\nexport const u24be = _u24be as <P extends string = \"\">(property?: P) => Layout<number, P>;\nexport const u32be = _u32be as <P extends string = \"\">(property?: P) => Layout<number, P>;\nexport const u40be = _u40be as <P extends string = \"\">(property?: P) => Layout<number, P>;\nexport const u48be = _u48be as <P extends string = \"\">(property?: P) => Layout<number, P>;\nexport const nu64be = _nu64be as <P extends string = \"\">(property?: P) => Layout<number, P>;\nexport const s8 = _s8 as <P extends string = \"\">(property?: P) => Layout<number, P>;\nexport const s16 = _s16 as <P extends string = \"\">(property?: P) => Layout<number, P>;\nexport const s24 = _s24 as <P extends string = \"\">(property?: P) => Layout<number, P>;\nexport const s32 = _s32 as <P extends string = \"\">(property?: P) => Layout<number, P>;\nexport const s40 = _s40 as <P extends string = \"\">(property?: P) => Layout<number, P>;\nexport const s48 = _s48 as <P extends string = \"\">(property?: P) => Layout<number, P>;\nexport const ns64 = _ns64 as <P extends string = \"\">(property?: P) => Layout<number, P>;\nexport const s16be = _s16be as <P extends string = \"\">(property?: P) => Layout<number, P>;\nexport const s24be = _s24be as <P extends string = \"\">(property?: P) => Layout<number, P>;\nexport const s32be = _s32be as <P extends string = \"\">(property?: P) => Layout<number, P>;\nexport const s40be = _s40be as <P extends string = \"\">(property?: P) => Layout<number, P>;\nexport const s48be = _s48be as <P extends string = \"\">(property?: P) => Layout<number, P>;\nexport const ns64be = _ns64be as <P extends string = \"\">(property?: P) => Layout<number, P>;\nexport const f32 = _f32 as <P extends string = \"\">(property?: P) => Layout<number, P>;\nexport const f32be = _f32be as <P extends string = \"\">(property?: P) => Layout<number, P>;\nexport const f64 = _f64 as <P extends string = \"\">(property?: P) => Layout<number, P>;\nexport const f64be = _f64be as <P extends string = \"\">(property?: P) => Layout<number, P>;\n\nexport const struct = _struct as <T, P extends string = \"\">(\n fields: T,\n property?: P,\n decodePrefixes?: boolean,\n) => T extends Layout<infer Value, infer Property>[]\n ? Structure<\n Value,\n P,\n {\n [K in Exclude<Extract<Property, string>, \"\">]: Extract<T[number], Layout<any, K>> extends Layout<infer V, any>\n ? V\n : any;\n }\n >\n : any;\n\nexport const seq = _seq as unknown as <T, P>(\n elementLayout: Layout<T, string>,\n count: number | Layout<number, string>,\n property?: P,\n) => Layout<T[]>;\nexport const union = _union as <UnionSchema extends { [key: string]: any } = any>(\n discr: Layout<any, any>,\n defaultLayout?: any,\n property?: string,\n) => Union<UnionSchema>;\nexport const unionLayoutDiscriminator = _unionLayoutDiscriminator as <P extends string = \"\">(\n layout: Layout<any, P>,\n property?: P,\n) => any;\nexport const blob = _blob as unknown as <P extends string = \"\">(\n length: number | Layout<number, P>,\n property?: P,\n) => Blob<P>;\nexport const cstr = _cstr as <P extends string = \"\">(property?: P) => Layout<string, P>;\nexport const utf8 = _utf8 as <P extends string = \"\">(maxSpan: number, property?: P) => Layout<string, P>;\nexport const bits = _bits as unknown as <T, P extends string = \"\">(\n word: Layout<T>,\n msb?: boolean,\n property?: P,\n) => BitStructure<T, P>; // TODO: not quite sure\nexport const offset = _offset as unknown as <T, P extends string = \"\">(\n layout: Layout<T, P>,\n offset?: number,\n property?: P,\n) => Layout<T, P>;\n\nexport type GetStructureSchema<T extends Structure> = T extends Structure<any, any, infer S> ? S : unknown;\n","import { publicKey, struct, u32, u64, u8 } from \"@/marshmallow\";\n\nexport const splAccountLayout = struct([\n publicKey(\"mint\"),\n publicKey(\"owner\"),\n u64(\"amount\"),\n u32(\"delegateOption\"),\n publicKey(\"delegate\"),\n u8(\"state\"),\n u32(\"isNativeOption\"),\n u64(\"isNative\"),\n u64(\"delegatedAmount\"),\n u32(\"closeAuthorityOption\"),\n publicKey(\"closeAuthority\"),\n]);\n",null,null,null,null],"mappings":"8kCAAA,wDAAA,MAKO,6BACP,GAA6E,2BCN7E,OAAyB,kBACzB,GAAkB,oBAClB,GAAgB,+BAChB,WAAM,OAAO,UAAG,EAUT,YAAa,CAGlB,YAAY,EAA+C,CACzD,KAAK,SAAW,EAAO,WAAa,OAAY,EAAO,SAAW,EAClE,KAAK,KAAO,EAAO,IACrB,IAEI,OAAM,EAAoB,CAC5B,KAAK,SAAW,CAClB,IACI,OAAe,CACjB,MAAO,eAAM,EAAE,IAAI,EAAE,OAAO,yBAAyB,CACvD,IACI,aAAqB,CACvB,MAAO,MAAK,IACd,CAEQ,WAAW,EAA0B,CAC3C,MAAO,IAAS,KAAK,QACvB,CAEO,SAAS,EAAe,CAC7B,MAAK,MAAK,WAAW,CAAc,EACnC,SAAQ,MAAM,KAAK,KAAM,KAAK,KAAM,mBAAoB,GAAG,CAAK,EACzD,MAFsC,IAG/C,CAEO,gBAAgB,EAAe,CAEpC,GAAM,GAAM,EAAM,IAAI,AAAC,GAAS,MAAO,IAAQ,SAAW,KAAK,UAAU,CAAG,EAAI,CAAI,EAAE,KAAK,IAAI,EAC/F,KAAM,IAAI,OAAM,CAAG,CACrB,CAEO,WAAW,EAAe,CAC/B,MAAK,MAAK,WAAW,CAAgB,EACrC,SAAQ,KAAK,KAAK,KAAM,KAAK,KAAM,qBAAsB,GAAG,CAAK,EAC1D,MAFwC,IAGjD,CAEO,QAAQ,EAAe,CAC5B,MAAK,MAAK,WAAW,CAAa,EAClC,SAAQ,KAAK,KAAK,KAAM,KAAK,KAAM,kBAAmB,GAAG,CAAK,EACvD,MAFqC,IAG9C,CAEO,SAAS,EAAe,CAC7B,M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